Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

Release 1.7.0

YanissAmzbdcf42bfcae9
diff --git a/README.md b/README.md
index 267a3a1..955f6e7 100644
--- a/README.md
+++ b/README.md
@@ -57,6 +57,52 @@ These are first versions. Speed, context length and model support keep improving
DeepSeek-V4.1-Flash-1017 (763B parameters, about 16B active) runs on one 128 GB machine with an NVMe: the 172 GiB EXL3 pack is larger than memory, so the engine keeps a pool of experts in RAM and reads the others from the SSD, exactly. It uses the model's own DSpark draft stages and the original Engram tables (about 190 GB, downloaded from the DeepSeek repository). Pack: [yamz-labs/DeepSeek-V4.1-Flash-EXL3-Yamz](https://huggingface.co/yamz-labs/DeepSeek-V4.1-Flash-EXL3-Yamz). Setup, SSD tier, Engram and speeds: [doc/DS41.md](doc/DS41.md).
+## NVIDIA RTX 3090
+
+Kyojin also runs on NVIDIA (sm_80 and up, tested on one RTX 3090 with 24 GB). It uses the same sources as the ROCm build; the CUDA path adds a quantized-KV decode attention kernel, a Flint sliding-window ring with whole-forward CUDA graphs, a grouped MoE prefill tier, an sm_86 GEMM layout and a decode GEMV policy. Build: [tools/cuda/README.md](tools/cuda/README.md). Switches: [doc/env_vars.md](doc/env_vars.md#nvidia-cuda-sm_80).
+
+Measured on the 3090 with real text, greedy, one user, KV cache quantized (Flint 6/6 bits, Qwen27 4/4 bits), tokens per second:
+
+| model | | 4K | 16K | 32K | 64K | 128K | 256K |
+|---|---|---|---|---|---|---|---|
+| Flint V1 (3.43 bpw, 17 GiB) | decode | 133.5 | 127.0 | 122.9 | 119.5 | 102.6 | 81.3 |
+| | prefill | 6282 | 6956 | 5938 | 4449 | 2995 | 1807 |
+
+| model (server, vision on) | | 5K | 39K | 79K | 150K | 250K |
+|---|---|---|---|---|---|---|
+| Qwen3.8-27B (EXL3 4.0 bpw, MTP + n-gram) | decode | 70.6 | 65.9 | 64.3 | 55.1 | 49.9 |
+| | prefill | 1356 | 1143 | 977 | 787 | 611 |
+
+Plain decode without speculation on Qwen27: 45.6 tok/s at 4K, 41.5 at 32K, 37.2 at 128K, 32.8 at 256K. Both models fit 256K tokens of context in 24 GB (peak 21 GiB for Flint, 20.5 GiB for Qwen27 with the vision tower).
+
+Run at 256K:
+
+```bash
+# Flint V1: 256K with 6-bit K and V (fp16 KV fits about 131K)
+python tools/flint/serve.py --model ./flint-pack -c 262144 --kv 6,6
+# Qwen27: 256K, 4-bit K and V, vision and the MTP drafter on
+python tools/qwen/serve.py --model ./qwen27-pack -c 262144 --k-bits 4 --v-bits 4
+```
+
+On NVIDIA both servers turn on the CUDA graph and these cache widths by default; `--kv` and `--k-bits`/`--v-bits` override them. The quantized caches are lossy: the Flint 6/6 cache measures about +9 % KL against fp16 and Qwen27 4/4 measures 1.4e-3 KL and finds the needle 3 times out of 3 at 256K (2 of 3 at 128K, the miss being a refusal wording that fp16 shares on other texts); `tools/flint/kvgate.py` and `tools/qwen/kvgate.py` rerun both checks.
+
+Against other engines on the same card (same prompts, greedy, decode | prefill, tokens per second):
+
+| Qwen3.8-27B | 4K | 32K | 128K | ~250K | max context |
+|---|---|---|---|---|---|
+| Kyojin, K4V4 (no speculation) | 44.6 \| 1130 | 43.0 \| 1074 | 37.6 \| 794 | 25.3 \| 582 | 262144 |
+| ExLlamaV3 upstream, K4V4 | 41.6 \| 1109 | 38.2 \| 896 | 30.2 \| 709 | 24.7 \| 524 | 262144 |
+| llama.cpp Q4_K_M, KV q4_0 | 40.5 \| 1246 | 33.9 \| 1275 | 21.6 \| 880 | 14.8 \| 628 | 262144 |
+| llama.cpp Q4_K_M, KV q8_0 | 38.7 \| - | 24.1 \| 900 | - | - | about 196K |
+
+| Flint V1 | 4K | 32K | 128K | ~250K | max context |
+|---|---|---|---|---|---|
+| Kyojin, KV 6/6 | 136.6 \| 4275 | 127.1 \| 4436 | 103.0 \| 2639 | 82.2 \| 1733 | 262144 |
+| llama.cpp Q3_K_XL, KV f16 | 123.1 \| 4630 | 111.3 \| 4262 | 78.5 \| 2411 | - | 131072 tested |
+| llama.cpp Q3_K_XL, KV q8_0 | 112.8 \| 4624 | 83.9 \| 4209 | 43.8 \| 2399 | 27.4 \| 1562 | 262144 |
+
+Kyojin leads on decode at every depth and on the context that fits; llama.cpp prefills Qwen27 10 to 19 % faster up to 32K. These two tables come from one earlier measurement session (single user, same prompts for every engine, Kyojin without the later prefill work), so the Kyojin rows are lower than in the first two tables. Weights differ between engines (EXL3 against GGUF), so quality is not compared.
+
## Contributors
Thank you to everyone who tests Kyojin on their own machine and writes precise reports.
@@ -68,6 +114,7 @@ Thank you to everyone who tests Kyojin on their own machine and writes precise r
- [@ChrisC381](https://github.com/ChrisC381): reported the GLM difference between paired jobs.
- [@dturini12](https://github.com/dturini12): reported streaming without `finish_reason`; fixed and confirmed.
- [@mostlygeek](https://github.com/mostlygeek): proposal for a container setup.
+- [@kamjin3086](https://github.com/kamjin3086): benchmark of Kyojin 1.6 against another engine and the report of a host freeze at start-up; both led to fixes in 1.7.
## Quickstart
diff --git a/README.tmpl.md b/README.tmpl.md
index 73b80d7..ebce092 100644
--- a/README.tmpl.md
+++ b/README.tmpl.md
@@ -14,7 +14,7 @@ Open source. Our own quantised builds of GLM and Qwen. Built on <a href="https:/
{{TABLE}}
-<p align="center"><sub>Tokens per second on one Ryzen AI Max+ 395 with 128 GB. Prefill at the context shown in each cell, speculative decode across chat, prose and code prompts. Method, sources and full tables: <a href="doc/benchmarks.md">doc/benchmarks.md</a>.</sub></p>
+<p align="center"><sub>Tokens per second on one Ryzen AI Max+ 395 with 128 GB. Prefill at the context shown in each cell, speculative decode across chat, prose and code prompts. DeepSeek-V4.1-Flash is larger than memory: most experts are read from the NVMe (about 3 GB/s), so its prefill is warm/cold and its decode is plain decoding on real sessions; a tool turn of about 2K tokens waits 21 to 35 s for the first token. Details: <a href="doc/DS41.md#speed">doc/DS41.md</a>. Method, sources and full tables: <a href="doc/benchmarks.md">doc/benchmarks.md</a>.</sub></p>
<p align="center">
<img src="doc/img/prefill.svg" alt="Prefill speed against context length" width="49%">
@@ -37,8 +37,56 @@ These are first versions. Speed, context length and model support keep improving
## DeepSeek-V4.1-Flash
+**Experimental.** A demonstration that a 763B model runs exactly on one 128 GB machine. It is slow and not meant for daily agent use: real decode is about 5 to 11 tokens per second, and a tool turn adding about 2K tokens takes about 20 to 35 seconds before the first token (the SSD floor is about 24 s).
+
DeepSeek-V4.1-Flash-1017 (763B parameters, about 16B active) runs on one 128 GB machine with an NVMe: the 172 GiB EXL3 pack is larger than memory, so the engine keeps a pool of experts in RAM and reads the others from the SSD, exactly. It uses the model's own DSpark draft stages and the original Engram tables (about 190 GB, downloaded from the DeepSeek repository). Pack: [yamz-labs/DeepSeek-V4.1-Flash-EXL3-Yamz](https://huggingface.co/yamz-labs/DeepSeek-V4.1-Flash-EXL3-Yamz). Setup, SSD tier, Engram and speeds: [doc/DS41.md](doc/DS41.md).
+## NVIDIA RTX 3090
+
+Kyojin also runs on NVIDIA (sm_80 and up, tested on one RTX 3090 with 24 GB). It uses the same sources as the ROCm build; the CUDA path adds a quantized-KV decode attention kernel, a Flint sliding-window ring with whole-forward CUDA graphs, a grouped MoE prefill tier, an sm_86 GEMM layout and a decode GEMV policy. Build: [tools/cuda/README.md](tools/cuda/README.md). Switches: [doc/env_vars.md](doc/env_vars.md#nvidia-cuda-sm_80).
+
+Measured on the 3090 with real text, greedy, one user, KV cache quantized (Flint 6/6 bits, Qwen27 4/4 bits), tokens per second:
+
+| model | | 4K | 16K | 32K | 64K | 128K | 256K |
+|---|---|---|---|---|---|---|---|
+| Flint V1 (3.43 bpw, 17 GiB) | decode | 133.5 | 127.0 | 122.9 | 119.5 | 102.6 | 81.3 |
+| | prefill | 6282 | 6956 | 5938 | 4449 | 2995 | 1807 |
+
+| model (server, vision on) | | 5K | 39K | 79K | 150K | 250K |
+|---|---|---|---|---|---|---|
+| Qwen3.8-27B (EXL3 4.0 bpw, MTP + n-gram) | decode | 70.6 | 65.9 | 64.3 | 55.1 | 49.9 |
+| | prefill | 1356 | 1143 | 977 | 787 | 611 |
+
+Plain decode without speculation on Qwen27: 45.6 tok/s at 4K, 41.5 at 32K, 37.2 at 128K, 32.8 at 256K. Both models fit 256K tokens of context in 24 GB (peak 21 GiB for Flint, 20.5 GiB for Qwen27 with the vision tower).
+
+Run at 256K:
+
+```bash
+# Flint V1: 256K with 6-bit K and V (fp16 KV fits about 131K)
+python tools/flint/serve.py --model ./flint-pack -c 262144 --kv 6,6
+# Qwen27: 256K, 4-bit K and V, vision and the MTP drafter on
+python tools/qwen/serve.py --model ./qwen27-pack -c 262144 --k-bits 4 --v-bits 4
+```
+
+On NVIDIA both servers turn on the CUDA graph and these cache widths by default; `--kv` and `--k-bits`/`--v-bits` override them. The quantized caches are lossy: the Flint 6/6 cache measures about +9 % KL against fp16 and Qwen27 4/4 measures 1.4e-3 KL and finds the needle 3 times out of 3 at 256K (2 of 3 at 128K, the miss being a refusal wording that fp16 shares on other texts); `tools/flint/kvgate.py` and `tools/qwen/kvgate.py` rerun both checks.
+
+Against other engines on the same card (same prompts, greedy, decode | prefill, tokens per second):
+
+| Qwen3.8-27B | 4K | 32K | 128K | ~250K | max context |
+|---|---|---|---|---|---|
+| Kyojin, K4V4 (no speculation) | 44.6 \| 1130 | 43.0 \| 1074 | 37.6 \| 794 | 25.3 \| 582 | 262144 |
+| ExLlamaV3 upstream, K4V4 | 41.6 \| 1109 | 38.2 \| 896 | 30.2 \| 709 | 24.7 \| 524 | 262144 |
+| llama.cpp Q4_K_M, KV q4_0 | 40.5 \| 1246 | 33.9 \| 1275 | 21.6 \| 880 | 14.8 \| 628 | 262144 |
+| llama.cpp Q4_K_M, KV q8_0 | 38.7 \| - | 24.1 \| 900 | - | - | about 196K |
+
+| Flint V1 | 4K | 32K | 128K | ~250K | max context |
+|---|---|---|---|---|---|
+| Kyojin, KV 6/6 | 136.6 \| 4275 | 127.1 \| 4436 | 103.0 \| 2639 | 82.2 \| 1733 | 262144 |
+| llama.cpp Q3_K_XL, KV f16 | 123.1 \| 4630 | 111.3 \| 4262 | 78.5 \| 2411 | - | 131072 tested |
+| llama.cpp Q3_K_XL, KV q8_0 | 112.8 \| 4624 | 83.9 \| 4209 | 43.8 \| 2399 | 27.4 \| 1562 | 262144 |
+
+Kyojin leads on decode at every depth and on the context that fits; llama.cpp prefills Qwen27 10 to 19 % faster up to 32K. These two tables come from one earlier measurement session (single user, same prompts for every engine, Kyojin without the later prefill work), so the Kyojin rows are lower than in the first two tables. Weights differ between engines (EXL3 against GGUF), so quality is not compared.
+
## Contributors
Thank you to everyone who tests Kyojin on their own machine and writes precise reports.
@@ -50,6 +98,7 @@ Thank you to everyone who tests Kyojin on their own machine and writes precise r
- [@ChrisC381](https://github.com/ChrisC381): reported the GLM difference between paired jobs.
- [@dturini12](https://github.com/dturini12): reported streaming without `finish_reason`; fixed and confirmed.
- [@mostlygeek](https://github.com/mostlygeek): proposal for a container setup.
+- [@kamjin3086](https://github.com/kamjin3086): benchmark of Kyojin 1.6 against another engine and the report of a host freeze at start-up; both led to fixes in 1.7.
## Quickstart
diff --git a/doc/container.md b/doc/container.md
index 650aff2..e2374f5 100644
--- a/doc/container.md
+++ b/doc/container.md
@@ -10,14 +10,14 @@ ROCm torch and `rocm-sdk-devel` from AMD's gfx1151 nightly index, the Kyojin tre
## Prebuilt images
-Nothing to build: the images of Kyojin 1.5 are on the GitHub registry (about 3 GB to download, 11 GB on disk).
+Nothing to build: the images of Kyojin 1.7 are on the GitHub registry (about 3 GB to download, 11 GB on disk).
```bash
-docker pull ghcr.io/yamz-labs/kyojin-qwen:1.5 # or podman pull
-docker pull ghcr.io/yamz-labs/kyojin-glm:1.5
+docker pull ghcr.io/yamz-labs/kyojin-qwen:1.7 # or podman pull
+docker pull ghcr.io/yamz-labs/kyojin-glm:1.7
```
-Then use `ghcr.io/yamz-labs/kyojin-qwen:1.5` in place of `kyojin-qwen` (or `localhost/kyojin-qwen`) in the run lines below. The MiMo image is not published: build it with the line below.
+Then use `ghcr.io/yamz-labs/kyojin-qwen:1.7` in place of `kyojin-qwen` (or `localhost/kyojin-qwen`) in the run lines below. The MiMo image is not published: build it with the line below.
## Build (tested)
@@ -44,20 +44,22 @@ docker run --rm --name kyojin-qwen \
The image has no `video` or `render` group by name, so docker needs the numeric ids of the host. With no `-e` at all the server starts with 131072 tokens of context, the sampling of the model card and the port 8731. The port opens when the model is loaded and warmed up; then `curl http://localhost:8731/v1/models` and `python tools/bench.py --base http://localhost:8731/v1` work from the host.
-Measured (Qwen pack, 89 GB, 131072 context, docker 29, nothing else on the GPU):
+Time to ready, measured on a Strix Halo machine with nothing else on the GPU, 131072 tokens of context:
-| Start | Time to ready |
-|---|---|
-| First start, empty cache volume | 566 s (kernels are compiled, the dense GEMM table is tuned, both are cached) |
-| Second start, same cache volume | 82 s |
-| GLM pack, first start | 813 s |
-| MiMo pack, first start | 130 s |
+| Start | 1.6 | 1.7 |
+|---|---|---|
+| Qwen pack, first start, empty cache | 493 s (kernels compiled, dense GEMM table tuned, both cached) | 67 s |
+| Qwen pack, second start, same cache | 84 s | 68 s |
+| GLM pack, first start, empty cache | 77 s, plus 28 s of kernel compiles inside the first request | 69 s, plus about 5 s of kernel compiles in the first requests |
+| GLM pack, second start, same cache | 70 s | 67 s |
+
+The Triton kernels and the dense GEMM tune table now ship with the code (see `EXL3_KERNEL_SEED`), so an empty cache no longer costs a compile or a tuning run. A restart with warm caches still reads the whole pack from the disk, so it is bound by the disk speed (about 2 GB/s: 45 to 65 s for a 72 to 89 GB pack). The MiMo image is not part of these figures: first start 130 s (1.5).
A chat completion and a tool call (`tools` in the request, the answer carries `tool_calls`) worked on Qwen and on GLM; MiMo was loaded and answered one completion. `docker stop` returns in 1 s (Qwen), 10 s (GLM), 2 s (MiMo); the exit code is 143 (SIGTERM) for Qwen and 0 for GLM and MiMo.
### Keep the cache
-The cache holds compiled HIP/Triton kernels and, for GLM, the dense GEMM tuning table. It must outlive the container, or every start pays the full first-start time again, and Qwen's 10 minutes may exceed a supervisor timeout. In order: a volume on `/root/.cache` (as above); else a hidden folder `.kyojin-cache` inside `/models` if it is mounted writable; `KYOJIN_CACHE_DIR=/some/folder` forces a folder. Warm the cache once by hand before you put the model behind a supervisor.
+The cache holds compiled HIP kernels and the dense GEMM tuning table; the Triton kernels ship with the image and are unpacked into it at start. Keep it across restarts so that kernels and tune results found at run time are not recomputed. In order: a volume on `/root/.cache` (as above); else a hidden folder `.kyojin-cache` inside `/models` if it is mounted writable; `KYOJIN_CACHE_DIR=/some/folder` forces a folder.
### No pack yet
diff --git a/doc/env_vars.md b/doc/env_vars.md
index 9c79805..32f8416 100644
--- a/doc/env_vars.md
+++ b/doc/env_vars.md
@@ -25,6 +25,50 @@ Free space that must remain on the volume after a write; writes are skipped belo
### `EXL3_PREFIX_DISK_MB_MIN` (default: `8000`)
Write budget per minute, so long agent sessions do not hit the sustained-write slowdown of QLC drives.
+## Prefill scheduling (GLM and Qwen servers, `--sessions` 2 or more)
+
+A prompt is prefilled in chunks of `EXL3_PREFILL_CHUNK` rows, one chunk per scheduler step. By default every active request
+runs its chunk in every step, so a 45K-token prompt holds back every short request that arrives next to it, and four 8K prompts
+sent together all finish together. The interleave only changes when a chunk runs, never the chunks: each request's chunk
+boundaries, and so its prefill math, are the ones of the default path. A single running request is not touched.
+
+### `EXL3_SCHED_CHUNK_IL` (default: `0`)
+`1` turns the interleave on. A prompt with more than `EXL3_CIL_SHORT_TOK` rows left to prefill (counted after the prompt-cache and
+tail-checkpoint restore) is a big prefill; the oldest one is the leader and the other big prefills wait for it, in arrival order.
+Between two leader chunks the short requests get a slice: their prefill, then one single-sequence decode step per scheduler
+step, for up to `EXL3_CIL_SLICE_S`. A leader chunk never shares its step with other work. The time the leader spends waiting is
+capped per leader (below), after which only its chunks run until it is done. A planner error turns the feature off for the
+process with one warning. Needs `--sessions` 2 or more; the server prints one line at start-up when it is on.
+
+### `EXL3_CIL_DEFER_FRAC` (default: `0.18`), `EXL3_CIL_MAX_DEFER_S` (default: `8`)
+Most the leader may be delayed by others: `min(EXL3_CIL_MAX_DEFER_S, EXL3_CIL_DEFER_FRAC x its estimated prefill time)`. A
+45K-row prefill of 36 s is delayed by at most 6.5 s, an 8K one of 6.5 s by at most 1.2 s. `EXL3_CIL_DEFER_FRAC=0` uses the
+seconds cap alone. The step that crosses the limit is the only overshoot: a slice step is only taken when its estimated cost
+(rows x measured seconds per row of the leader, plus `EXL3_CIL_DECODE_S` per decode step) still fits.
+
+### `EXL3_CIL_SHORT_TOK` (default: `4096`), `EXL3_CIL_SLICE_S` (default: `0.6`)
+Rows at or below which a prefill counts as short; length of one slice in seconds.
+
+### `EXL3_CIL_SINGLE_DECODE` (default: `1`)
+In a slice only one decode-ready request decodes per step (least recently served first), alone, as it would without the big
+prefill. `0` lets all of them decode in one batch: the slice is cheaper for the leader, but a batched decode is not
+guaranteed to give the tokens of a solo run.
+
+### `EXL3_CIL_ROW_S` (default: `0.0007`), `EXL3_CIL_DECODE_S` (default: `0.05`)
+Starting estimates in seconds of one prefill row and of one decode step; the row estimate is replaced by the measured leader
+chunk times after the first chunk.
+
+## Prompt encoding (GLM and Qwen servers)
+
+### `KYO_TOKCACHE` (default: `8`)
+Number of recent prompts whose token ids the server keeps. A client that re-sends the whole conversation, or the same long
+document with another question, then encodes only the part after the last shared turn marker or line break; the ids equal a
+full encode (a self-test at start-up turns the cache off where they would not). Encoding a re-sent prompt of about 90K tokens:
+118 ms to 4 ms. `0` turns it off.
+
+### `KYO_TOKCACHE_CHECK` (default: unset)
+`1` also runs the full encode for every request and compares the ids. For debugging.
+
## Attention
### `EXL3_BC_ATTN` (default: `1`)
@@ -568,7 +612,7 @@ into tens of thousands of segments with large reserved-but-unallocated overhead.
module frees its blocks; at most one boundary block shared with a neighboring module stays
pinned. Set to `0` to fall back to per-tensor allocations.
-### `EXL3_NGRAM_STREAM` (default: `1`)
+### `EXL3_NGRAM_STREAM` (default: unset = stream from disk)
Default for `Config.infer_params.ngram_stream_from_disk`: stream an n-gram embedding table
(PLE models, e.g. Qwen3.8-Flash-Next) from disk with per-forward row gathers (run-coalesced
@@ -577,9 +621,27 @@ queue depth on Windows) instead of loading the whole table into system RAM. The
is tens of GB, and streaming costs little on SSD-class storage (decode is latency-tolerant at
~30 rows/token; prefill gathers are batched). Set to `0` to hold the table in RAM — worthwhile
only when the table lives on high-latency storage (e.g. HDD, where per-row seeks make streaming
-unusable). Also settable per load via `config.infer_params.ngram_stream_from_disk` or
+unusable). There is no automatic RAM choice: unset always streams from disk, because host memory sampled mid-load
+does not predict what the rest of the load (weights, KV cache, towers) will still take. The load log prints the
+placement, the reason, the table size and MemAvailable. Also settable per load via `config.infer_params.ngram_stream_from_disk` or
`--ngram_ram` in `model_init`-based scripts.
+### `EXL3_NGRAM_IO_THREADS` (default: `128`)
+
+Upper bound on the reader threads of the n-gram table's disk gather (`EXL3_NGRAM_STREAM` on; read
+once, when the first gather starts). A cold gather is bound by the queue depth the disk sees, one
+blocking read per thread: 32 threads keep a consumer NVMe at about 45k random reads/s, 128 at about
+85k. The pool is also capped at 8 threads per CPU thread (at least 4). Lower the value on storage
+that saturates early or when the gather competes with CPU-bound work. Minimum 1.
+
+### `EXL3_NGRAM_WARM_TOKENS` (default: `8192`)
+
+How many prompt positions of the later part of a prompt the engine reads ahead from the n-gram
+table, on the prefetch worker, behind the chunk being issued. The rows land in the page cache, so
+the gather of the next chunks costs a few milliseconds instead of about 0.4 s of cold reads per
+4096-token chunk. It changes no result. `0` turns the look-ahead off. It matters only for models
+with an n-gram embedding table read from disk.
+
### `EXL3_AUTOSPLIT_WORSTCASE` (default: `1`)
The layer-split autosplit loader measures each module's transient VRAM with one forward of a
@@ -799,6 +861,29 @@ ignored under tensor parallel; both lane launchers set it.
released, because on unified memory the page cache and the weights are the same physical pool and
keeping it leaves the box carrying a large pack twice.
+#### `EXL3_KERNEL_SEED` (default: `1`)
+
+`0` does not unpack the pre-compiled Triton kernels shipped in `exllamav3/kernel_seed/` into the
+Triton cache. With the seed a start with an empty cache compiles no kernel (GLM saved about 55 s,
+spread over start-up and the first requests). A seed is tied to one Triton version and GPU
+architecture; another build simply does not use it (nor does a GPU of another architecture).
+The seed hits from any install prefix: Triton hashes the absolute path of its bundled device
+libraries into the cache key, and the engine replaces that prefix by a placeholder in the key
+(HIP only, and only when a seed matches). `build` uses the same keys but installs nothing: it is
+the mode in which a seed is built from an empty cache. Rebuild with `tools/kernel_seed/` (sweep,
+then build).
+
+#### `EXL3_LOG_JIT` (default: `0`)
+
+`1` prints one `[jit]` line per Triton kernel the server compiles or loads, with its time. Use it to
+check that nothing compiles after READY.
+
+#### `EXL3_WARM_TUNE_BUDGET_S` (default: `90`)
+
+Seconds the start-up warm-up may spend screening dense GEMM solutions. After that the remaining
+shapes run untuned (bit-exact) and are tuned on first use. `0` never defers. The shipped tune
+seed makes a start on the pinned rocBLAS spend about 1 s here.
+
#### `EXL3_DENSE_GEMM_TUNE_FILE` (default: `$HOME/.cache/exllamav3/dense_gemm_tune.txt`)
The file that holds the tuned dense GEMM solution per shape class. Point it at a seeded file to
@@ -852,9 +937,28 @@ While on, a verify forward of up to 8 rows takes the per-row exact path in the M
the MoE router, so each row is bit-equal to the same row decoded alone, which is two GLM jobs at
draft depth 2. Only those two modules and only up to 8 rows: `0` drops the limit to 4, lets the
faster batched paths take over, and a near-tied token can then change. Even with it on, more than
-one session does not guarantee greedy output equal to a solo run: the decode attention kernel picks
-how to split the cache from the batch it runs with, so a near-tie can change (see
-[tools/qwen/SERVE.md](../tools/qwen/SERVE.md)).
+one session does not guarantee greedy output equal to a solo run: the decode attention kernel
+picks how to split the cache from the batch it runs with, so a near-tie can change.
+`EXL3_ROW_INV_GROUPS` closes that gap on Qwen.
+
+#### `EXL3_ROW_INV_GROUPS` (default: `0`, off)
+
+Qwen with `--sessions` above 1, and `EXL3_ROW_INV` on. `1` packs the jobs of a decode step, in order, into
+forwards of at most 8 token rows (jobs times `1 + drafted tokens`), and inside a forward with several
+sequences each attention layer runs one sequence at a time, with that sequence's own block table and cache
+length. Every row then gets the bits of the same row decoded alone, and a step with one job runs as it always
+did. Four cold 8K prompts at `--sessions 4`, `--ndt 7`, greedy: answers equal to the serial ones, 16 of 16
+(16-bit and 8-bit cache; the same load gave 5 to 7 of 16 without it). It costs about 3 % wall time on that load
+and 8 to 10 % of the aggregate decode throughput on short prompts. Not covered: a step where a sequence crosses
+the sparse-attention threshold (2051 cached tokens) while the draft width of the group differs from the width the
+same request would have drafted alone (any request that grows past that length while it shares a step), and
+every step shared with a request that carries images (it keeps the plain one-forward path).
+
+#### `EXL3_ROW_INV_GROUP_ROWS` (default: `8`)
+
+With `EXL3_ROW_INV_GROUPS=1`: the most token rows one forward of a decode step may carry. `1` runs one forward per
+job, which is the slowest plan and exact by construction. Values above 8 leave the range where the row-exact
+kernels apply.
#### `EXL3_MTP_EH_FP16` (default: unset, off)
@@ -870,6 +974,14 @@ vocabulary. Every draft is still verified, so the output does not change. The GL
`draft2s.st` from the model folder when its header (vocabulary size, hidden width) matches `config.json`. A path in the
variable wins; `0`, `off` or an empty value uses the full head. Sampled jobs always use the full head.
+#### `EXL3_DRAFT_VOCAB` (default: unset; the Qwen server sets `98304` on NVIDIA)
+
+Qwen3.5 MTP drafter, 1-row greedy draft steps: read only the first N rows (a multiple of 128) of the shared 248K-row head
+instead of all of it. On the RTX 3090 the K5 head is 0.93 ms of a ~1.5 ms draft step; N = 98304 makes it ~0.4 ms and
+costs nothing on English and code (99.3 % of tokens have an id below 98304). Every 8th step runs both heads; a language whose tokens sit
+above N (French, CJK) turns the subset off by itself (misses EMA >= 0.12) and back on when the probes agree (< 0.04). Every draft is
+verified, so the text is the one without the flag. `0` or unset uses the full head; sampled jobs always use the full head.
+
#### `EXL3_MIMO_LOSSLESS` (default: `1`)
`0` restores the fast MiMo verify that is not token-identical. With it on, speculative output
@@ -915,6 +1027,44 @@ tuning and the matching `/health` stage. Read only with `EXL3_DENSE_GEMM_TUNE=1`
`1` prints a memory line after the GLM warm-up.
+#### `EXL3_TAIL_DENSE` (default: `0` in the engine; the Qwen server sets `7`, the GLM server `0`)
+
+Dense prompt-tail checkpoints. Besides the checkpoint on the last page of a prompt, the recurrent
+state is written at each of the `N` page boundaries below it, so a follow-up prompt that shares the
+cached prefix up to anywhere in its last `N` pages (the same document with another question)
+resumes within one page of the divergence instead of at the previous chunk start. Costs a few
+hundred MiB of host memory. The kernel side-writes at most 8 rows per chunk: the last page and the
+branch row come first, the dense rows fill the free slots, deepest first. On the KDA (GLM) layers
+the rows are added only with `EXL3_MIDCHUNK_CKPT=2`; the other mode splits the layer at every row
+and would drop all mid-chunk checkpoints. A resume replays a different number of rows than a cold
+prefill and the dense GEMM path depends on the row count, so the output of a resumed turn is not
+yet bit-identical to a cold prefill (a fix is in progress). `0` is off.
+
+#### `EXL3_TAIL_SUB` (default: `0`)
+
+Sub-page prompt-tail checkpoints: how many of the last multiples of 64 rows of the chunk that holds
+the prompt end get a checkpoint, so a prompt that diverges in its final tokens replays at most
+about 64 rows instead of up to a page. Entries that do not fall on a page boundary are kept in host
+memory (about 142 MiB each, at most `EXL3_TAIL_SUB_MAX`). Same numerics caveat as
+`EXL3_TAIL_DENSE`. `0` is off.
+
+#### `EXL3_TAIL_SUB_MAX` (default: `8`)
+
+Cap on the sub-page checkpoint entries the generator keeps (oldest dropped first). `0` keeps none
+and requests no kernel slot for them. Read only with `EXL3_TAIL_SUB`.
+
+#### `EXL3_LOOP_GUARD` (default: `1`)
+
+The answer-phase loop guard of the Qwen and GLM servers (`tools/loopguard.py`). `0` turns it off for
+every request. It ends a reply that has fallen into a loop: a repeated token period, or a tail that
+replays itself. The finish reason is `length` and the choice carries `stop_reason: "loop_guard"`
+(with the detail in `timings.loop_guard`), so a client can tell a guard stop from a natural end.
+A request can switch the guard off for itself with `"loop_guard": false` (a boolean; `true` or
+absent follows this variable). The Qwen server also watches the thinking block and restarts it
+from the kept thinking; the GLM server leaves a thinking block alone and watches the answer after
+`</think>`. Repetitive data that is valid (a grid of zeros, identical JSON lines, a zero-padded
+hex dump) is not cut before 16384 tokens of repetition.
+
### Speed defaults the servers set
Each server applies a measured configuration before the engine loads, so a bare `serve.py` runs
@@ -945,6 +1095,11 @@ latch the value at import.
| `EXL3_PF_DEFER` | `0` | `1` runs the draft prefill after the first token instead of chunk by chunk with the target prefill. Needs a single session and no spec gate. |
| `EXL3_PF_NO_TAIL` | `1` | Lets the last prefill chunk run to the end of the prompt instead of stopping at the last page, which saves a second pass over every expert. |
| `EXL3_PF_TAIL_MERGE` | `1024` | How many rows past the chunk size a merged last chunk may take, so a short tail is merged rather than re-read. |
+| `EXL3_PF_SPLIT` | empty (off) | Comma list of offsets, in rows before the end of the prompt, at which the last prefill chunk is cut into extra passes, for example `256` or `1280,256`. Each cut lands on a page-aligned row and is stored as an exact recurrent checkpoint, so a later request that shares the prefix up to a cut resumes with the same pass shapes as a cold prefill and gets bit-identical logits. The extra passes cost a little prefill time. |
+| `EXL3_PF_SPLIT_MIN` | `4096` | The shortest prompt, in tokens, that `EXL3_PF_SPLIT` applies to. |
+| `EXL3_PF_SPLIT_HEAD` | `1024` | The fewest rows the first pass of a split last chunk must keep. A cut that would leave less is dropped. |
+| `EXL3_PF_SPLIT_STEP` | `512` | The least spacing, in rows, between two cuts of a split last chunk. |
+| `EXL3_PF_SPLIT_Q` | `256` | The grid, in rows, that split cuts are rounded down to. Rounded down to a multiple of the page size. |
| `EXL3_VERIFY_QSA_PROJ` | `0` | `1` runs the indexer q and k projection per row instead of batched. |
| `EXL3_VERIFY_QSA_ATTN` | `0` | `1` or `all` runs sparse selection and attention per row, `sel` selection only, `att` attention only. |
| `EXL3_QSA_ROWINV` | `1` | Computes the sparse-attention split plan as if the batch were a single row, so a batched verify reduces in the same order as plain decode. `0` restores the batch-dependent plan. |
@@ -1040,3 +1195,54 @@ progress and report `eta_s`: `startup-qwen.json`, `startup-glm.json` and `startu
it to share one cache between several checkouts. The GLM server keeps two files there, one for
starts with the dense GEMM tuning already cached and one without, so a cached start is not timed
with the slow first one.
+
+## NVIDIA (CUDA, sm_80+)
+
+Switches of the CUDA path. Defaults are the shipped behaviour on NVIDIA; none of them changes ROCm builds. Several
+are not bit-identical to the Triton / eager path on greedy output (first divergences sit on near-ties, KL within the
+noise of the quantization), which is why each has an off switch for A/B work.
+
+#### `EXL3_CUDA_GRAPH` (default `0`; `tools/qwen/serve.py` and `tools/flint/serve.py` set it to `1` on NVIDIA)
+
+Whole-forward CUDA graph for decode steps (Qwen GDN, Flint sliding-window ring, MTP verify). `EXL3_CUDA_GRAPH_MULTI=1`
+(default off) lets several jobs share one graph (B in 1..4, B*Q <= 32). `EXL3_CUDA_GRAPH_MAX` bounds the graph cache.
+
+#### `EXL3_QDEC` (default `1`), `EXL3_QDEC_GRAPH` (default `1`), `EXL3_QDEC_ROWS` (default `1`)
+
+Decode attention for quantized KV caches (K/V bits 2..8): a tensor-core split kernel compiled at run time (NVRTC, no
+build step) that reads the packed pages directly. `EXL3_QDEC=0` falls back to the Triton kernels, `EXL3_QDEC_GRAPH=0`
+disables its CUDA-graph capture path, `EXL3_QDEC_ROWS` selects the many-row kernel for verify steps (q_len 2..8 at
+head dim 256): `0` off, `1` only where the single-row kernel cannot serve, `2` always.
+
+#### `EXL3_PREFILL_WIDE` (default `1`)
+
+Models with sliding-window attention only and a fused MoE (Flint): prompts that fit are prefilled in one pass, in
+8192-row chunks while the cache holds less than 64K tokens, 4096 beyond. `0` restores the plain 4096-row plan.
+
+#### `EXL3_MOE_GROUPED` (default `1`), `EXL3_MOE_GROUPED_LO` (default `33`), `EXL3_MOE_GROUPED_ROWS`
+
+Grouped MoE prefill tier: one CTA per (expert, 64-row tile, 128-column tile) with fp32 accumulation and the output
+Hadamard fused with the top-k combine, for experts that receive at least `EXL3_MOE_GROUPED_LO` rows. `0` restores the
+persistent expert-group kernel.
+
+#### `EXL3_GEMV_POLICY` (default `1`), `EXL3_GEMV_ROWS`
+
+Slice height of the int8 decode GEMV on 4/5-bit weights: taller k-slices, about two work units per SM. `0` restores the
+former rule, `EXL3_GEMV_ROWS=<n>` forces a slice height.
+
+#### `EXL3_QC_PF_MAXNREG` (default `255` for 8-bit K+V and above, else `0`)
+
+Register cap of the quantized-KV prefill attention kernel (`0` = compiler default). Uncapped registers free 1.3 GiB of
+driver local memory and let Flint run `--kv 8,8` at 256K.
+
+#### `EXL3_TAIL_PIN` (default `1` on NVIDIA), `EXL3_TAIL_RING` (default `0`)
+
+`EXL3_TAIL_PIN=0` makes the prompt-end recurrent checkpoint a synchronous `.cpu()` copy instead of an asynchronous copy
+into pinned host memory. `EXL3_TAIL_RING=1` allows a tail restore into a partial page when the draft cache is a ring
+smaller than the target cache (a DFlash2 drafter).
+
+#### `QWSPEC_DEPTHRULE` (default unset)
+
+`N:thf,thv,maxd,thfd,thvd`: above N context tokens the MTP draft tier rule switches to these thresholds and draft depth
+(`QWSPEC_THF/THV/THFD/THVD` set the base tiers). Needed only with `EXL3_QDEC=0` or `EXL3_QDEC_ROWS=0`, where the
+Triton verify makes deep drafts expensive: `96000:0.45,0.2,4,0.8,0.6`.
diff --git a/doc/figures.json b/doc/figures.json
index bb058b8..480f4c2 100644
--- a/doc/figures.json
+++ b/doc/figures.json
@@ -4,6 +4,10 @@
"method": "new-user install, published packs, default environment, card prompts, greedy, server-reported prefill",
"date": "2026-10-17",
"commit": "db6103b",
+ "version": "1.5.10",
+ "readme_extra_rows": [
+ "<tr><td>DeepSeek-V4.1-Flash <sub>(experimental, SSD tier)</sub></td><td align=\"right\">185 GB</td><td align=\"right\">187 to 257 at 8K</td><td align=\"right\">5 to 11 <sub>(plain)</sub></td></tr>"
+ ],
"models": [
{
"id": "qwen",
diff --git a/exllamav3/architecture/architectures.py b/exllamav3/architecture/architectures.py
index 8669598..ff746c3 100644
--- a/exllamav3/architecture/architectures.py
+++ b/exllamav3/architecture/architectures.py
@@ -8,11 +8,13 @@ from .deepseek_v3 import DeepseekV3Model
from .deepseek_v4 import DeepseekV4Model
from .deepseek_v41 import DeepseekV41Model
from .dflash import DFlashModel
+from .dflash2 import DFlash2Model
from .dflash_laguna import DFlashLagunaModel
from .dots1 import Dots1Model
from .ernie4_5 import Ernie4_5Model
from .ernie4_5_moe import Ernie4_5MoEModel
from .exaone4 import Exaone4Model
+from .flint import FlintModel
from .gemma2 import Gemma2Model
from .gemma3 import Gemma3Model, Gemma3TextModel
from .gemma4 import Gemma4TextModel, Gemma4UnifiedTextModel
@@ -35,6 +37,7 @@ from .lfm2_moe import Lfm2MoeModel
from .llama import LlamaModel
from .mimo import MiMoModel
from .mimo_v2 import MiMoV2Model
+from .minicpm_v47 import MiniCPMV47TextModel
from .minimax_m2 import MiniMaxM2Model
from .ministral3 import Ministral3Model
from .mistral import MistralModel
@@ -43,6 +46,7 @@ from .mixtral import MixtralModel
from .muse_glimmer import MuseGlimmerTextModel
from .muse_glimmer_assistant import MuseGlimmerAssistantModel
from .nemotronh import NemotronHModel
+from .nemotronh_puzzle import NemotronHPuzzleModel
from .olmo3 import Olmo3Model
from .olmohybrid import OlmoHybridModel
from .phi3 import Phi3Model
@@ -78,11 +82,13 @@ ARCHITECTURES = {
DeepseekV4Model,
DeepseekV41Model,
DFlashModel,
+ DFlash2Model,
DFlashLagunaModel,
Dots1Model,
Ernie4_5Model,
Ernie4_5MoEModel,
Exaone4Model,
+ FlintModel,
Gemma2Model,
Gemma3Model,
Gemma3TextModel,
@@ -107,6 +113,7 @@ ARCHITECTURES = {
LlamaModel,
MiMoModel,
MiMoV2Model,
+ MiniCPMV47TextModel,
MiniMaxM2Model,
Ministral3Model,
MistralModel,
@@ -115,6 +122,7 @@ ARCHITECTURES = {
MuseGlimmerTextModel,
MuseGlimmerAssistantModel,
NemotronHModel,
+ NemotronHPuzzleModel,
Olmo3Model,
OlmoHybridModel,
Phi3Model,
diff --git a/exllamav3/architecture/dflash2.py b/exllamav3/architecture/dflash2.py
new file mode 100644
index 0000000..bfbea69
--- /dev/null
+++ b/exllamav3/architecture/dflash2.py
@@ -0,0 +1,360 @@
+# ported from exllamav3 1.6.0, MIT, (c) turboderp
+from __future__ import annotations
+from typing_extensions import override
+import torch
+import weakref
+
+from ..cache import Cache
+from ..model.config import no_default
+from ..model.model import Model
+from ..modules import RMSNorm, Attention, GatedMLP
+from ..modules.arch_specific.dflash import DFlashInputLayer
+from ..modules.arch_specific.dflash2 import DFlash2Block, DFlash2DynConv, DFlash2Selector
+from ..modules.attn import prepare_for_attn
+from .dflash import DFlashConfig, DFlashModel
+from ..util.tensor import get_for_device
+from ..util.device_copy import to_device
+
+# DFlash2 draft model: the DFlash encoder (fc + hidden_norm over the concatenated target taps)
+# and SWA/GQA layers, with grouped dynamic convolutions around every attention/MLP sublayer and
+# a top-k candidate selector in place of row-wise argmax.
+#
+# Conventions:
+# - Block input = [anchor, mask x (block_size-1)]; each remaining row predicts
+# its own position and the selector walks candidates starting from the anchor.
+# - Taps: reference reads HF hidden_states[target_layer_ids[i] + 1] = output
+# of target layer id => tap_shift 0 (exl3 export index = layer output).
+# - Block attention direction: the checkpoint's "is_causal" decides whether block rows
+# see later rows (reference default: causal only on sliding-window layers); windowed
+# layers express it through (left, right) window bounds, see DFlashConfig.block_window.
+# - Draft cache ctx K/V come from the shared DFlash K/V update (fc+hidden_norm
+# projected tap stream); per-round writes at the new cache position overwrite
+# the transient noise-block K/V, reproducing the reference's crop semantics.
+# - Proposals are the greedy selector path (T-independent), verified by the
+# stock accept-while-match rule — trivially lossless at every temperature
+# (per-position output marginal equals the target distribution).
+
+
+class DFlash2Config(DFlashConfig):
+
+ arch_string = "DFlash2DraftModel"
+
+ # Reference extract uses hidden_states[id + 1] == output of layer id
+ tap_shift = 0
+
+ def __init__(
+ self,
+ directory: str,
+ model_classes: dict | None = None,
+ **kwargs,
+ ):
+ super().__init__(
+ directory,
+ model_classes or {"text": DFlash2Model},
+ **kwargs
+ )
+
+ self.conv_kernel_size = self.read_cfg(
+ int, ["dflash_config->conv_kernel_size", "conv_kernel_size"], 2)
+ self.conv_group_size = self.read_cfg(
+ int, ["dflash_config->conv_group_size", "conv_group_size"], 16)
+ self.selector_rank = self.read_cfg(
+ int, ["dflash_config->selector_rank", "selector_rank"], no_default)
+ self.selector_top_k = self.read_cfg(
+ int, ["dflash_config->selector_top_k", "selector_top_k"], no_default)
+ self.input_embedding_scale = float(self.read_cfg(
+ [float, int], ["dflash_config->input_embedding_scale", "input_embedding_scale"], 1.0))
+ self.output_multiplier = float(self.read_cfg(
+ [float, int], ["dflash_config->output_multiplier", "output_multiplier"], 1.0))
+ self.final_logit_softcapping = float(self.read_cfg(
+ [float, int], ["dflash_config->final_logit_softcapping", "final_logit_softcapping"], 0.0))
+ # Block attention direction, as the reference draft reads it: "is_causal" in the checkpoint
+ # config overrides the default of causal on sliding-window layers, bidirectional elsewhere
+ # (Kyojin's DFlashConfig only has the derived bidirectional_block flag)
+ self.is_causal = self.read_cfg(bool, ["is_causal", "dflash_config->is_causal"], None)
+ assert len(set(self.target_layer_ids)) == len(self.target_layer_ids), \
+ "DFlash2 target_layer_ids must be unique"
+ assert 0 < self.conv_kernel_size <= self.block_size, \
+ "DFlash2 conv_kernel_size must be positive and no larger than block_size"
+ assert self.conv_group_size > 0 and self.hidden_size % self.conv_group_size == 0, \
+ "DFlash2 hidden_size must be divisible by a positive conv_group_size"
+ assert self.selector_rank > 0, \
+ "DFlash2 selector_rank must be positive"
+ assert 0 < self.selector_top_k <= self.vocab_size, \
+ "DFlash2 selector_top_k must be between 1 and vocab_size"
+
+ def block_window(self, idx: int) -> tuple[int, int]:
+ """
+ (sliding_window, window_right) for draft layer idx. The reference masks q - k < sw,
+ i.e. self plus sw - 1 past keys; a layer that is not causal within the draft block sees
+ the same span ahead of the query
+ """
+ if self.layer_types[idx] != "sliding_attention":
+ return -1, 0
+ causal = True if self.is_causal is None else self.is_causal
+ return self.sliding_window - 1, 0 if causal else self.sliding_window - 1
+
+
+class DFlash2Model(Model):
+ config_class = DFlash2Config
+
+ # Encoder tensor keys
+ key_fc = "fc"
+ key_fc_norm = "hidden_norm"
+
+ def __init__(
+ self,
+ config: DFlash2Config,
+ **kwargs
+ ):
+ super().__init__(config, **kwargs)
+
+ self.input_layer = DFlashInputLayer(
+ config = config,
+ key = self.key_fc,
+ key_norm = self.key_fc_norm,
+ hidden_size = config.hidden_size,
+ target_state_size = config.hidden_size * len(config.target_layer_ids),
+ mask_token_id = config.mask_token_id,
+ rms_norm_eps = config.rms_norm_eps,
+ native_draft_len = config.block_size,
+ qmap = "target_hidden",
+ input_embedding_scale = config.input_embedding_scale,
+ )
+ self.modules += [self.input_layer]
+
+ self.first_block_idx = len(self.modules)
+ self.attn_modules = []
+
+ for idx in range(config.num_hidden_layers):
+ window_left, window_right = config.block_window(idx)
+
+ attn = Attention(
+ config = config,
+ key = f"layers.{idx}.self_attn",
+ layer_idx = idx,
+ hidden_size = config.hidden_size,
+ head_dim = config.head_dim,
+ num_q_heads = config.num_q_heads,
+ num_kv_heads = config.num_kv_heads,
+ rope_settings = config.rope_settings,
+ key_q = "q_proj",
+ key_k = "k_proj",
+ key_v = "v_proj",
+ key_o = "o_proj",
+ qmap = "block.attn",
+ sliding_window = window_left,
+ window_right = window_right,
+ q_norm = RMSNorm(
+ config = config,
+ key = f"layers.{idx}.self_attn.q_norm",
+ rms_norm_eps = config.rms_norm_eps,
+ ),
+ k_norm = RMSNorm(
+ config = config,
+ key = f"layers.{idx}.self_attn.k_norm",
+ rms_norm_eps = config.rms_norm_eps,
+ ),
+ out_dtype = torch.float,
+ )
+ self.attn_modules.append(attn)
+
+ def dynconv(name: str, qmap: str):
+ return DFlash2DynConv(
+ config = config,
+ key = f"layers.{idx}.{name}",
+ hidden_size = config.hidden_size,
+ kernel_size = config.conv_kernel_size,
+ group_size = config.conv_group_size,
+ qmap = qmap,
+ )
+
+ self.modules += [
+ DFlash2Block(
+ config = config,
+ key = f"layers.{idx}",
+ layer_idx = idx,
+ attn_norm = RMSNorm(
+ config = config,
+ key = f"layers.{idx}.input_layernorm",
+ rms_norm_eps = config.rms_norm_eps,
+ ),
+ attn = attn,
+ mlp_norm = RMSNorm(
+ config = config,
+ key = f"layers.{idx}.post_attention_layernorm",
+ rms_norm_eps = config.rms_norm_eps,
+ ),
+ mlp = GatedMLP(
+ config = config,
+ key = f"layers.{idx}.mlp",
+ hidden_size = config.hidden_size,
+ intermediate_size = config.intermediate_size,
+ key_up = "up_proj",
+ key_gate = "gate_proj",
+ key_down = "down_proj",
+ qmap = "block.mlp",
+ interm_dtype = torch.half,
+ out_dtype = torch.float,
+ ),
+ attn_conv = dynconv("attention_conv", "block.attn"),
+ mlp_conv = dynconv("mlp_conv", "block.mlp"),
+ )
+ ]
+
+ self.last_kv_module_idx = len(self.modules) - 1
+
+ self.selector = DFlash2Selector(
+ config = config,
+ key = "candidate_selector",
+ vocab_size = config.vocab_size,
+ hidden_size = config.hidden_size,
+ rank = config.selector_rank,
+ top_k = config.selector_top_k,
+ )
+
+ self.modules += [
+ RMSNorm(
+ config = config,
+ key = f"norm",
+ rms_norm_eps = config.rms_norm_eps,
+ out_dtype = torch.half,
+ ),
+ # Identity in the module walk; part of the list so loading, autosplit and compilation
+ # account for its tensors. sample_from_state runs its walk after the target's head
+ self.selector,
+ ]
+
+ # Logits come from the attached target's head
+ self.logit_layer_idx = None
+ self.caps.update({
+ "uncalibrated_quantize": True,
+ "supports_tp": False,
+ "attach_target": True,
+ "dflash_draft": True,
+ "default_draft_size": config.block_size - 1,
+ "autosplit_load_fwd": False,
+ })
+
+ self.attached_model = None
+
+ self.draft_verifier_params.update({
+ "export_state_layers": set(config.target_layer_ids),
+ })
+
+
+ def attach_to(self, target):
+ if target.loaded_tp:
+ raise NotImplementedError(
+ "DFlash2 does not support tensor-parallel targets because the selector needs top-k logits"
+ )
+ if target.config.vocab_size != self.config.vocab_size:
+ raise ValueError(
+ f"DFlash2 vocabulary size {self.config.vocab_size} does not match "
+ f"target vocabulary size {target.config.vocab_size}"
+ )
+ if target.config.hidden_size != self.config.hidden_size:
+ raise ValueError(
+ f"DFlash2 hidden size {self.config.hidden_size} does not match "
+ f"target hidden size {target.config.hidden_size}"
+ )
+ if not 0 <= self.config.mask_token_id < target.config.vocab_size:
+ raise ValueError("DFlash2 mask_token_id is outside the target vocabulary")
+ if target.logit_layer_idx is None:
+ raise ValueError("DFlash2 target has no compatible LM head")
+ if any(not 0 <= layer_id < target.config.num_hidden_layers
+ for layer_id in self.config.target_layer_ids):
+ raise ValueError("DFlash2 target_layer_ids contains a layer outside the target model")
+ self.attached_model = weakref.ref(target)
+ self.input_layer.attached_model = weakref.ref(target)
+
+
+ def update_kv_from_target(
+ self,
+ target_hidden: list,
+ cache: Cache,
+ params: dict,
+ lengths: list[int] = None,
+ ):
+ # Target states arrive in layer execution order. Reorder them only when the checkpoint's
+ # projection expects a different target_layer_ids order.
+ target_layer_ids = self.config.target_layer_ids
+ if target_layer_ids != sorted(target_layer_ids):
+ source_idx = {layer_id: idx for idx, layer_id in enumerate(sorted(target_layer_ids))}
+ target_hidden = [target_hidden[source_idx[layer_id]] for layer_id in target_layer_ids]
+ # Same encoder + K/V write as DFlash v1 (reads input_layer, attn_modules)
+ DFlashModel.update_kv_from_target(self, target_hidden, cache, params, lengths)
+
+
+ def sample_from_state(
+ self,
+ state: torch.Tensor,
+ params: dict
+ ) -> torch.Tensor:
+ """Target lm_head over all block rows, then the selector walk over
+ rows 1.. (rows predict their own position; row 0 is the anchor).
+ Returns (bsz, block) ids [anchor, path...]; the generator crops the
+ anchor. The selector is greedy; sampling remains lossless because the
+ target verifier still samples normally and accepts only exact matches."""
+ target = self.attached_model()
+ lm = target.modules[target.logit_layer_idx]
+ logits = lm.prepare_for_device(state.half(), params)
+ logits = lm.forward(logits, params)
+
+ dev = self.selector.device
+ # The generator stages the block ids in pinned memory: upload without a host sync
+ anchor = get_for_device(params, "dflash2_anchor_ids", dev)[:, -1]
+ export_conf = params.get("export_draft_conf", False)
+ # [anchor, path...] and [0, score...] straight from the selector, in the block layout
+ # the generator consumes. The head's padded width, the output multiplier and the
+ # softcap (Gemma-class targets) are handled inside the selector's top-k. The state
+ # (draft's last block) and the logits (target's head) may sit on other devices than
+ # the selector: to_device bounces pairs with a broken peer path through the host
+ out, confidence = self.selector.walk_block(
+ to_device(state[:, 1:], dev), to_device(logits[:, 1:], dev), anchor,
+ return_confidence = export_conf,
+ vocab_size = target.config.vocab_size,
+ scale = self.config.output_multiplier,
+ softcap = self.config.final_logit_softcapping,
+ )
+ if export_conf:
+ params["draft_conf"] = confidence
+ return out
+
+
+ def default_load_shape_dtype(self, chunk_size):
+ return (1, 1), torch.long
+
+
+ def default_load_params(self, max_chunk_size):
+ return {}
+
+
+ @override
+ def prepare_inputs(self, input_ids: torch.Tensor, params: dict) -> torch.Tensor:
+ assert input_ids.shape[-1] == 1, \
+ "DFlash2 expects one verified anchor token per draft block"
+ params["dflash2_anchor_ids"] = input_ids
+ # Block attention direction per the checkpoint (DFlashConfig.block_window): the kernel
+ # flag is only needed when every layer is causal; windowed layers carry their own bounds
+ params["causal"] = self.config.is_causal is True
+ return prepare_for_attn(input_ids, params)
+
+
+ @override
+ def default_chat_prompt(self, prompt: str, system_prompt: str = None) -> str:
+ raise NotImplementedError()
+
+
+ @classmethod
+ @override
+ def get_additional_compiled_tensors(cls, config: DFlash2Config) -> dict:
+ # Encoder norm (stored in DFlashInputLayer under a key that doesn't match the fc module
+ # prefix), conv base kernels and selector codebooks: raw tensors outside any Linear
+ tensors = dict(config.stc.list_tensors(prefix = cls.key_fc_norm))
+ tensors.update(config.stc.list_tensors(prefix = "candidate_selector."))
+ for idx in range(config.num_hidden_layers):
+ for conv in ("attention_conv", "mlp_conv"):
+ tensors.update(config.stc.list_tensors(
+ prefix = f"layers.{idx}.{conv}.base_kernel"))
+ return tensors
diff --git a/exllamav3/architecture/flint.py b/exllamav3/architecture/flint.py
new file mode 100644
index 0000000..4c093d2
--- /dev/null
+++ b/exllamav3/architecture/flint.py
@@ -0,0 +1,259 @@
+from __future__ import annotations
+from typing_extensions import override
+import torch
+from ..model.config import Config, no_default
+from ..model.model import Model
+from ..util.rope import RopeStyle
+from ..modules import (
+ RMSNorm, Embedding, TransformerBlock, Attention, SlidingAttention, SWAState,
+ GatedMLP, BlockSparseMLP, Linear,
+)
+from ..modules.attn import prepare_for_attn
+from ..cache.recurrent_util import prepare_for_recurrence
+
+
+class FlintConfig(Config):
+ arch_string = "FlintForCausalLM"
+
+ def __init__(
+ self,
+ directory: str,
+ **kwargs,
+ ):
+ super().__init__(
+ directory,
+ {"text": FlintModel},
+ **kwargs
+ )
+
+ self.hidden_size = self.read_cfg(int, "hidden_size", no_default)
+ self.num_hidden_layers = self.read_cfg(int, "num_hidden_layers", no_default)
+ self.tie_word_embeddings = self.read_cfg(bool, "tie_word_embeddings", False)
+
+ self.num_q_heads = self.read_cfg(int, "num_attention_heads", no_default)
+ self.num_kv_heads = self.read_cfg(int, "num_key_value_heads", self.num_q_heads)
+ self.head_dim = self.read_cfg(int, "head_dim", None) or self.hidden_size // self.num_q_heads
+
+ # layer_types: full_attention / sliding_attention. The config window counts the current token,
+ # the kernels' left window keeps window + 1 keys including the query
+ self.layer_types = self.read_cfg(list, "layer_types", no_default)
+ assert len(self.layer_types) == self.num_hidden_layers
+ self.sliding_window = self.read_cfg(int, "sliding_window", None)
+ if "sliding_attention" in self.layer_types:
+ assert self.sliding_window, "Flint: sliding_window must be set"
+ # Layers without positional encoding (all full-attention layers)
+ self.no_rope_layers = set(self.read_cfg(list, "no_rope_layer_indices", []))
+ self.assert_cfg(str, "softmax_type", "learnable", True)
+
+ # MLP / MoE: dense layers listed in mlp_only_layers, sigmoid top-k router renormalised over the picks,
+ # plus an ungated shared expert
+ self.assert_cfg(str, "hidden_act", "silu", True)
+ self.intermediate_size = self.read_cfg(int, "intermediate_size", no_default)
+ self.moe_intermediate_size = self.read_cfg(int, "moe_intermediate_size", no_default)
+ self.shared_expert_intermediate_size = self.read_cfg(int, "shared_expert_intermediate_size", 0)
+ self.num_experts = self.read_cfg(int, "num_experts", no_default)
+ self.num_experts_per_tok = self.read_cfg(int, "num_experts_per_tok", no_default)
+ self.mlp_only_layers = set(self.read_cfg(list, "mlp_only_layers", []))
+ self.assert_cfg(bool, "norm_topk_prob", True, True)
+ self.assert_cfg(str, "router_score_function", "sigmoid", True)
+
+ self.rms_norm_eps = self.read_cfg(float, "rms_norm_eps", no_default)
+
+ # fp16 overflow guard: the routed experts of layers 46 and 48 take act(gate) * up to ~1.6e5 / 2.3e5 on
+ # some tokens (BF16 reference, 15K mixed tokens), past the fp16 max. Their intermediates are divided by
+ # interm_div and the routing weights multiplied back (BlockSparseMLP.interm_div). Shared experts peak at 7e3.
+ self.interm_div_layers = {int(k): float(v) for k, v in
+ self.read_cfg(dict, "exl3_interm_div_layers", {"46": 16.0, "48": 16.0}).items()}
+
+ # RoPE only on sliding layers (NEOX)
+ self.rope_settings = self.read_rope_settings_default(RopeStyle.NEOX)
+
+
+class FlintModel(Model):
+ config_class = FlintConfig
+
+ def __init__(
+ self,
+ config: FlintConfig,
+ key_prefix: str = "model",
+ swa_full: bool = False,
+ **kwargs
+ ):
+ super().__init__(config, **kwargs)
+ # swa_full = True keeps every layer on the paged full-length cache (for A/B); the default routes the
+ # 35 sliding-window layers through SlidingAttention's per-slot window ring (513 slots, not full length)
+ self.swa_full = swa_full
+
+ self.modules += [
+ Embedding(
+ config = config,
+ key = f"{key_prefix}.embed_tokens",
+ vocab_size = config.vocab_size,
+ hidden_size = config.hidden_size,
+ )
+ ]
+
+ self.first_block_idx = len(self.modules)
+
+ for idx in range(config.num_hidden_layers):
+ swa = config.layer_types[idx] == "sliding_attention"
+ attn_kwargs = dict(
+ config = config,
+ key = f"{key_prefix}.layers.{idx}.self_attn",
+ layer_idx = idx,
+ hidden_size = config.hidden_size,
+ head_dim = config.head_dim,
+ num_q_heads = config.num_q_heads,
+ num_kv_heads = config.num_kv_heads,
+ rope_settings = None if idx in config.no_rope_layers else config.rope_settings,
+ sm_scale = None,
+ key_q = "q_proj",
+ key_k = "k_proj",
+ key_v = "v_proj",
+ key_o = "o_proj",
+ key_sinks = "softmax_offset",
+ qmap = "block.attn",
+ q_norm = RMSNorm(
+ config = config,
+ key = f"{key_prefix}.layers.{idx}.self_attn.q_norm",
+ rms_norm_eps = config.rms_norm_eps,
+ ),
+ k_norm = RMSNorm(
+ config = config,
+ key = f"{key_prefix}.layers.{idx}.self_attn.k_norm",
+ rms_norm_eps = config.rms_norm_eps,
+ ),
+ out_dtype = torch.float,
+ select_hq_bits = 2,
+ )
+ if swa and not swa_full:
+ attn = SlidingAttention(sliding_window = config.sliding_window - 1, **attn_kwargs)
+ else:
+ attn = Attention(sliding_window = config.sliding_window - 1 if swa else -1, **attn_kwargs)
+
+ if idx in config.mlp_only_layers:
+ mlp = GatedMLP(
+ config = config,
+ key = f"{key_prefix}.layers.{idx}.mlp",
+ hidden_size = config.hidden_size,
+ intermediate_size = config.intermediate_size,
+ key_up = "up_proj",
+ key_gate = "gate_proj",
+ key_down = "down_proj",
+ qmap = "block.mlp",
+ interm_dtype = torch.half,
+ out_dtype = torch.float,
+ select_hq_bits = 1,
+ )
+ else:
+ mlp = BlockSparseMLP(
+ config = config,
+ key = f"{key_prefix}.layers.{idx}.mlp",
+ hidden_size = config.hidden_size,
+ intermediate_size = config.moe_intermediate_size,
+ num_experts = config.num_experts,
+ num_experts_per_tok = config.num_experts_per_tok,
+ key_up = "experts.{expert_idx}.up_proj",
+ key_gate = "experts.{expert_idx}.gate_proj",
+ key_down = "experts.{expert_idx}.down_proj",
+ key_routing_gate = "gate",
+ qmap = "block.mlp",
+ interm_dtype = torch.half,
+ out_dtype = torch.float,
+ interm_div = config.interm_div_layers.get(idx, 1.0),
+ router_type = "dots",
+ routed_scaling_factor = 1.0,
+ shared_experts = GatedMLP(
+ config = config,
+ key = f"{key_prefix}.layers.{idx}.mlp.shared_expert",
+ hidden_size = config.hidden_size,
+ intermediate_size = config.shared_expert_intermediate_size,
+ key_up = "up_proj",
+ key_gate = "gate_proj",
+ key_down = "down_proj",
+ qmap = "block.mlp",
+ interm_dtype = torch.half,
+ out_dtype = torch.float,
+ select_hq_bits = 2,
+ ) if config.shared_expert_intermediate_size else None,
+ )
+
+ self.modules += [
+ TransformerBlock(
+ config = config,
+ key = f"{key_prefix}.layers.{idx}",
+ layer_idx = idx,
+ attn_norm = RMSNorm(
+ config = config,
+ key = f"{key_prefix}.layers.{idx}.input_layernorm",
+ rms_norm_eps = config.rms_norm_eps,
+ ),
+ attn = attn,
+ mlp_norm = RMSNorm(
+ config = config,
+ key = f"{key_prefix}.layers.{idx}.post_attention_layernorm",
+ rms_norm_eps = config.rms_norm_eps,
+ ),
+ mlp = mlp,
+ )
+ ]
+
+ self.last_kv_module_idx = len(self.modules) - 1
+
+ head_alt_key = None
+ if config.tie_word_embeddings and not self.config.stc.has_tensor("lm_head"):
+ head_alt_key = f"{key_prefix}.embed_tokens"
+
+ self.modules += [
+ RMSNorm(
+ config = config,
+ key = f"{key_prefix}.norm",
+ rms_norm_eps = config.rms_norm_eps,
+ out_dtype = torch.half,
+ ),
+ Linear(
+ config = config,
+ key = "lm_head",
+ qbits_key = "head_bits",
+ alt_key = head_alt_key,
+ in_features = config.hidden_size,
+ out_features = config.vocab_size,
+ qmap = "block",
+ caps = {"logits_output": True}
+ )
+ ]
+
+ self.logit_layer_idx = len(self.modules) - 1
+
+ # Activate all experts during H capture pass in quantization
+ self.calibration_all_experts = True
+
+ self.caps.update({
+ "supports_tp": False,
+ })
+
+ # SWA layers keep their KV in a per-slot window ring rather than the paged cache
+ self.recurrent_state_cls = None
+ if not self.swa_full:
+ self.caps.update({
+ "recurrent_states": True,
+ "default_recurrent_checkpoint_interval": 2048,
+ })
+ self.recurrent_state_cls = SWAState
+
+
+ @override
+ def prepare_inputs(self, input_ids: torch.Tensor, params: dict) -> torch.Tensor:
+ if not self.swa_full:
+ prepare_for_recurrence(input_ids, params, self)
+ input_ids = prepare_for_attn(input_ids, params)
+ return input_ids
+
+
+ @override
+ def default_chat_prompt(self, prompt: str, system_prompt: str = None) -> str:
+ p = ""
+ if system_prompt:
+ p += f"<|system|>{system_prompt}"
+ p += f"<|user|>{prompt}<|assistant|>"
+ return p
diff --git a/exllamav3/architecture/gemma3.py b/exllamav3/architecture/gemma3.py
index 15ce7e9..59fe953 100644
--- a/exllamav3/architecture/gemma3.py
+++ b/exllamav3/architecture/gemma3.py
@@ -13,6 +13,7 @@ from ..modules import (
Embedding,
TransformerBlock,
Attention,
+ SlidingAttention,
GatedMLP,
Linear,
Conv,
@@ -22,6 +23,8 @@ from ..modules import (
)
from ..modules.arch_specific.gemma3 import Gemma3MMPool
from ..modules.attn import prepare_for_attn
+from ..modules.sliding_attn import SWAState
+from ..cache.recurrent_util import prepare_for_recurrence
from ..tokenizer import Tokenizer, MMEmbedding
from types import SimpleNamespace
from PIL import Image
@@ -243,9 +246,11 @@ class Gemma3Model(Model):
self,
config: Gemma3Config | Gemma3TextConfig,
key_prefix = "language_model",
+ swa_full: bool = False,
**kwargs
):
super().__init__(config, **kwargs)
+ self.swa_full = swa_full
self.modules += [
Embedding(
@@ -270,7 +275,9 @@ class Gemma3Model(Model):
rms_norm_eps = config.rms_norm_eps,
constant_bias = 1.0,
),
- attn = Attention(
+ # Sliding-window layers keep their KV in a per-slot window ring (SlidingAttention) instead of
+ # full-length paged KV, so KV memory and decode traffic stop growing with context on them
+ attn = (SlidingAttention if (not swa_full and config.swa_pattern[idx] > 0) else Attention)(
config = config,
key = f"{key_prefix}.model.layers.{idx}.self_attn",
layer_idx = idx,
@@ -360,9 +367,20 @@ class Gemma3Model(Model):
self.logit_layer_idx = len(self.modules) - 1
+ # SWA layers are recurrent (window ring state), optionally
+ self.recurrent_state_cls = None
+ if not self.swa_full:
+ self.caps.update({
+ "recurrent_states": True,
+ "default_recurrent_checkpoint_interval": 6144,
+ })
+ self.recurrent_state_cls = SWAState
+
@override
def prepare_inputs(self, input_ids: torch.Tensor, params: dict) -> torch.Tensor:
+ if not self.swa_full:
+ prepare_for_recurrence(input_ids, params, self)
input_ids = prepare_for_attn(input_ids, params)
return input_ids
diff --git a/exllamav3/architecture/minicpm_v47.py b/exllamav3/architecture/minicpm_v47.py
new file mode 100644
index 0000000..c1b483a
--- /dev/null
+++ b/exllamav3/architecture/minicpm_v47.py
@@ -0,0 +1,394 @@
+"""MiniCPM-V-4.7-35B-A3B text path on GGUF as shipped.
+
+Same block family as Qwen3_5Moe (3x GDN linear + 1x full attention per 4,
+256-expert SwiGLU MoE + shared expert): reuses GatedDeltaNet, Attention,
+BlockSparseMLP and GatedMLP through ForeignLinear prebuilts over the raw
+GGUF payloads (no requant). Text-only; vision tower is not covered.
+
+GGUF tensor names (blk.{i}.*) are served by GGUFCollection; engine-style
+module keys map through collection.name_map, expert slices through the
+".e{idx}" protocol natively.
+"""
+from __future__ import annotations
+from typing_extensions import override
+import os
+
+import numpy as np
+import torch
+
+from ..loader.gguf_collection import GGUFCollection
+from ..model.config import Config, no_default
+from ..model.model import Model
+from ..util.rope import RopeStyle, RoPE
+from ..modules import (
+ RMSNorm,
+ Embedding,
+ TransformerBlock,
+ Attention,
+ BlockSparseMLP,
+ Linear,
+ GatedDeltaNet,
+ GatedMLP,
+ GDNState,
+)
+from ..modules.foreign_linear import ForeignLinear
+from ..modules.attn import prepare_for_attn
+from ..cache.recurrent_util import prepare_for_recurrence
+
+MCPM_ARCH = "MiniCPMV4_7ForConditionalGeneration"
+MCPM_GGUF_ENV = "MCPM_GGUF"
+MCPM_FOREIGN = os.environ.get("MCPM_FOREIGN", "1") != "0"
+
+_GGML_FMT = {12: "q4_k", 13: "q5_k", 14: "q6_k", 23: "iq4_xs", 0: "fp", 1: "fp"}
+
+P = "model.language_model"
+
+
+def _gguf_path() -> str:
+ p = os.environ.get(MCPM_GGUF_ENV)
+ assert p, f"{MCPM_GGUF_ENV} must point at the MiniCPM GGUF file"
+ return p
+
+
+def _map_layer(nm: dict, i: int):
+ L = f"{P}.layers.{i}"
+ G = f"blk.{i}"
+ nm.update({
+ f"{L}.input_layernorm.weight": f"{G}.attn_norm.weight",
+ f"{L}.post_attention_layernorm.weight": f"{G}.post_attention_norm.weight",
+ # GDN projs (ForeignLinear keys, no map needed for the module key
+ # itself: the map covers the ".weight" tensor key)
+ f"{L}.linear_attn.in_proj_qkv.weight": f"{G}.attn_qkv.weight",
+ f"{L}.linear_attn.in_proj_z.weight": f"{G}.attn_gate.weight",
+ f"{L}.linear_attn.in_proj_b.weight": f"{G}.ssm_beta.weight",
+ f"{L}.linear_attn.in_proj_a.weight": f"{G}.ssm_alpha.weight",
+ f"{L}.linear_attn.out_proj.weight": f"{G}.ssm_out.weight",
+ f"{L}.linear_attn.conv1d.weight": f"{G}.ssm_conv1d.weight",
+ f"{L}.linear_attn.A_log": f"{G}.ssm_a",
+ f"{L}.linear_attn.dt_bias": f"{G}.ssm_dt.bias",
+ f"{L}.linear_attn.norm.weight": f"{G}.ssm_norm.weight",
+ # Full attention
+ f"{L}.self_attn.q_proj.weight": f"{G}.attn_q.weight",
+ f"{L}.self_attn.k_proj.weight": f"{G}.attn_k.weight",
+ f"{L}.self_attn.v_proj.weight": f"{G}.attn_v.weight",
+ f"{L}.self_attn.o_proj.weight": f"{G}.attn_output.weight",
+ f"{L}.self_attn.q_norm.weight": f"{G}.attn_q_norm.weight",
+ f"{L}.self_attn.k_norm.weight": f"{G}.attn_k_norm.weight",
+ # MoE router + shared gate
+ f"{L}.mlp.gate.weight": f"{G}.ffn_gate_inp.weight",
+ f"{L}.mlp.shared_expert_gate.weight": f"{G}.ffn_gate_inp_shexp.weight",
+ })
+
+
+class MiniCPMV47Config(Config):
+ arch_string = MCPM_ARCH
+
+ def __init__(self, directory: str, **kwargs):
+ super().__init__(directory, {"text": MiniCPMV47TextModel}, **kwargs)
+ tc = "text_config"
+
+ def pfx(key):
+ return f"{tc}->{key}"
+
+ self.head_dim = self.read_cfg(int, pfx("head_dim"), None)
+ self.hidden_size = self.read_cfg(int, pfx("hidden_size"), no_default)
+ self.num_q_heads = self.read_cfg(int, pfx("num_attention_heads"), no_default)
+ self.num_kv_heads = self.read_cfg(int, pfx("num_key_value_heads"), self.num_q_heads)
+ self.full_attention_interval = self.read_cfg(int, pfx("full_attention_interval"), 4)
+ if not self.head_dim:
+ self.head_dim = self.hidden_size // self.num_q_heads
+ self.linear_conv_kernel_dim = self.read_cfg(int, pfx("linear_conv_kernel_dim"), 4)
+ self.linear_num_key_heads = self.read_cfg(int, pfx("linear_num_key_heads"), 16)
+ self.linear_num_value_heads = self.read_cfg(int, pfx("linear_num_value_heads"), 32)
+ self.linear_key_head_dim = self.read_cfg(int, pfx("linear_key_head_dim"), 128)
+ self.linear_value_head_dim = self.read_cfg(int, pfx("linear_value_head_dim"), 128)
+ self.assert_cfg(str, pfx("hidden_act"), "silu", True)
+ self.moe_intermediate_size = self.read_cfg(int, pfx("moe_intermediate_size"), no_default)
+ self.num_experts = self.read_cfg(int, pfx("num_experts"), no_default)
+ self.num_experts_per_tok = self.read_cfg(int, pfx("num_experts_per_tok"), no_default)
+ self.shared_expert_intermediate_size = self.read_cfg(
+ int, pfx("shared_expert_intermediate_size"), 512)
+ self.rms_norm_eps = self.read_cfg(float, pfx("rms_norm_eps"), no_default)
+ self.num_hidden_layers = self.read_cfg(int, pfx("num_hidden_layers"), no_default)
+ self.tie_word_embeddings = self.read_cfg(bool, "tie_word_embeddings", False)
+ self.vocab_size = self.read_cfg(int, pfx("vocab_size"), no_default)
+ self.max_position_embeddings = self.read_cfg(
+ int, pfx("max_position_embeddings"), 262144)
+ # layer_types from config when present (MiniCPM ships it)
+ lt = self.read_cfg(list, pfx("layer_types"), None)
+ if lt is not None:
+ assert len(lt) == self.num_hidden_layers
+ self.layer_types = [
+ "full_attention" if t == "full_attention" else "linear_attention" for t in lt]
+ else:
+ self.layer_types = [
+ "full_attention" if (idx + 1) % self.full_attention_interval == 0
+ else "linear_attention" for idx in range(self.num_hidden_layers)]
+ self.rope_settings = self.read_rope_settings_default(
+ RopeStyle.NEOX, default_rope_theta=10000000,
+ config_dict=self.read_cfg(dict, tc, no_default))
+ # MTP head and vision tower are separate concerns (draft file)
+ self.model_classes.pop("mtp", None)
+ self.model_classes.pop("vision", None)
+
+ # GGUF backing store + engine->gguf name map
+ self.gguf = GGUFCollection(_gguf_path())
+ nm: dict[str, str] = {}
+ for i in range(self.num_hidden_layers):
+ _map_layer(nm, i)
+ nm[f"{P}.norm.weight"] = "output_norm.weight"
+ nm["lm_head.weight"] = "output.weight"
+ self.gguf.name_map = nm
+ self.stc = self.gguf
+ self.gguf_formats = {
+ g: _GGML_FMT.get(ty, f"unk{ty}")
+ for g, (ty, _, _) in self.gguf.infos.items()}
+ # Embedding: dequant IQ4_XS token_embd to fp16 once (1 GB), served
+ # as an in-memory override (vectorized numpy, no per-block Python).
+ self._load_embedding_override()
+
+ def _load_embedding_override(self):
+ # token_embd dequantized to fp16 once (~1 GB) and served as an
+ # in-memory override under the engine key (vectorized numpy, no
+ # per-block Python). Format-generic (IQ4_XS / Q4_K).
+ from ..foreign_quant.k_quants import dequant_iq4_xs_bulk, dequant_q4_K_bulk
+ ty, dims, off = self.gguf.infos["token_embd.weight"]
+ bbs = {23: 136, 12: 144}
+ assert ty in bbs, f"token_embd type {ty}"
+ bb = bbs[ty]
+ K, N = dims[0], dims[1]
+ assert K % 256 == 0
+ raw = self.gguf._pread(off, N * (K // 256) * bb).reshape(N, (K // 256) * bb)
+ nb = N * (K // 256)
+ bulk = dequant_iq4_xs_bulk if ty == 23 else dequant_q4_K_bulk
+ w = bulk(raw.reshape(nb, bb)).reshape(N, K)
+ self.gguf.new_tensors = {
+ f"{P}.embed_tokens.weight": torch.from_numpy(np.ascontiguousarray(w))}
+
+ def get_tensor_name_fixes(self):
+ return {}
+
+
+def _fp_override(config, eng_weight_key: str, gguf_name: str):
+ """Dequantize a small GGUF tensor on CPU and register it as an fp32
+ in-memory override (Linear fp16 path picks it up with float2half).
+ For the tiny GDN b/a projs the fused kernels require fp16."""
+ from ..foreign_quant.k_quants import dequant_row
+ ty, dims, off = config.gguf.infos[gguf_name]
+ bbs = {12: 144, 13: 176, 14: 210, 23: 136}
+ fmts = {12: "q4_k", 13: "q5_k", 14: "q6_k", 23: "iq4_xs"}
+ assert ty in bbs, f"{gguf_name}: type {ty}"
+ bb, fmt = bbs[ty], fmts[ty]
+ K, N = dims[0], dims[1]
+ raw = config.gguf._pread(off, N * (K // 256) * bb)
+ blocks = [bytes(raw[i * bb:(i + 1) * bb]) for i in range(N * (K // 256))]
+ # dequant_row concatenates in GGUF row order ([N, K]); engine fp Linears
+ # keep (in, out) orientation, so transpose to [K, N] = [in, out].
+ w = dequant_row(blocks, fmt).reshape(N, K).T
+ if config.gguf.new_tensors is None:
+ config.gguf.new_tensors = {}
+ config.gguf.new_tensors[eng_weight_key] = torch.from_numpy(np.ascontiguousarray(w))
+
+
+def _alog_override(config, eng_weight_key: str, gguf_name: str):
+ """A_log override: the GGUF ssm_a tensor stores -exp(A_log) (llama.cpp
+ qwen35moe: gate = softplus(alpha + dt) * ssm_a), while the engine's GDN
+ (torch path and fused_op_2 alike) computes g = -exp(a_log) * softplus.
+ Register log(-ssm_a) under the engine A_log key."""
+ ty, dims, off = config.gguf.infos[gguf_name]
+ assert ty == 0 and len(dims) == 1, f"{gguf_name}: type {ty} dims {dims}"
+ raw = config.gguf._pread(off, dims[0] * 4)
+ a = np.frombuffer(raw, dtype=np.float32).astype(np.float64)
+ assert np.all(a < 0), f"{gguf_name}: expected all-negative -exp(A_log)"
+ w = np.log(-a).astype(np.float32)
+ if config.gguf.new_tensors is None:
+ config.gguf.new_tensors = {}
+ config.gguf.new_tensors[eng_weight_key] = torch.from_numpy(np.ascontiguousarray(w))
+
+
+def _fl(config, eng_key: str, in_features: int, out_features: int,
+ out_dtype=None):
+ # Resolve engine key -> gguf name, then the base tensor's format
+ # (expert-slice keys "....exps.e7" look up the base tensor).
+ gkey = config.gguf.name_map.get(eng_key + ".weight", eng_key + ".weight")
+ body = gkey[:-7] if gkey.endswith(".weight") else gkey
+ if "exps.e" in body:
+ body = body.rsplit(".e", 1)[0] + ".weight"
+ elif not body.endswith(".weight"):
+ body = body + ".weight"
+ fmt = config.gguf_formats[body]
+ assert fmt not in ("fp",) and not fmt.startswith("unk"), f"{eng_key}: {fmt}"
+ return ForeignLinear(config, eng_key, in_features, out_features, fmt,
+ out_dtype=out_dtype)
+
+
+class MiniCPMV47TextModel(Model):
+ config_class = MiniCPMV47Config
+
+ def __init__(self, config: MiniCPMV47Config, **kwargs):
+ super().__init__(config, **kwargs)
+ H = config.hidden_size
+ self.modules += [
+ Embedding(config=config, key=f"{P}.embed_tokens",
+ vocab_size=config.vocab_size, hidden_size=H)]
+ self.first_block_idx = len(self.modules)
+ for idx in range(config.num_hidden_layers):
+ L = f"{P}.layers.{idx}"
+ G = f"blk.{idx}"
+ is_full = config.layer_types[idx] == "full_attention"
+ if is_full:
+ attn = Attention(
+ config=config, key=f"{L}.self_attn", layer_idx=idx,
+ hidden_size=H, head_dim=config.head_dim,
+ num_q_heads=config.num_q_heads, num_kv_heads=config.num_kv_heads,
+ rope_settings=config.rope_settings, sm_scale=None,
+ q_norm=RMSNorm(config=config, key=f"{L}.self_attn.q_norm",
+ rms_norm_eps=config.rms_norm_eps),
+ k_norm=RMSNorm(config=config, key=f"{L}.self_attn.k_norm",
+ rms_norm_eps=config.rms_norm_eps),
+ out_dtype=torch.float, interleaved_gate=True,
+ select_hq_bits=2,
+ **self._attn_projs(config, L, G, H))
+ else:
+ attn = GatedDeltaNet(
+ config=config, key=f"{L}.linear_attn", layer_idx=idx,
+ hidden_size=H, k_head_dim=config.linear_key_head_dim,
+ v_head_dim=config.linear_value_head_dim,
+ num_k_heads=config.linear_num_key_heads,
+ num_v_heads=config.linear_num_value_heads,
+ rms_norm_eps=config.rms_norm_eps,
+ conv_kernel_size=config.linear_conv_kernel_dim,
+ key_a_log="A_log", key_dt_bias="dt_bias", key_conv1d="conv1d",
+ key_qkv="in_proj_qkv", key_z="in_proj_z",
+ key_b="in_proj_b", key_a="in_proj_a",
+ key_norm="norm", key_o="out_proj", qmap="block.attn",
+ out_dtype=torch.float, select_hq_bits=2,
+ # GGUF v-heads are even/odd grouped (llama blocked style);
+ # repeat pairing mis-pairs 30/32 heads (see NOTEBOOK).
+ blocked_gqa=True,
+ **self._gdn_projs(config, L, G, H, idx))
+ mlp = self._moe(config, L, G, H)
+ self.modules += [
+ TransformerBlock(
+ config=config, key=L, layer_idx=idx,
+ attn_norm=RMSNorm(config=config, key=f"{L}.input_layernorm",
+ rms_norm_eps=config.rms_norm_eps),
+ attn=attn,
+ mlp_norm=RMSNorm(config=config, key=f"{L}.post_attention_layernorm",
+ rms_norm_eps=config.rms_norm_eps),
+ mlp=mlp)]
+ self.last_kv_module_idx = len(self.modules) - 1
+ self.modules += [
+ RMSNorm(config=config, key=f"{P}.norm",
+ rms_norm_eps=config.rms_norm_eps,
+ out_dtype=torch.half),
+ _fl(config, "output", H, config.vocab_size)]
+ self.modules[-1].caps["logits_output"] = True # whole-forward CUDA graph tail marker
+ self.logit_layer_idx = len(self.modules) - 1
+ self.calibration_all_experts = True
+ self.caps.update({
+ "recurrent_states": True,
+ "default_recurrent_checkpoint_interval": 2048,
+ "linear_attn": True})
+ self.recurrent_state_cls = GDNState
+
+ @staticmethod
+ def _attn_projs(config, L, G, H):
+ if not MCPM_FOREIGN:
+ return {}
+ hd, nq, nkv = config.head_dim, config.num_q_heads, config.num_kv_heads
+ return dict(
+ q_proj=_fl(config, f"{L}.self_attn.q_proj", H, 2 * nq * hd),
+ k_proj=_fl(config, f"{L}.self_attn.k_proj", H, nkv * hd),
+ v_proj=_fl(config, f"{L}.self_attn.v_proj", H, nkv * hd),
+ o_proj=_fl(config, f"{L}.self_attn.o_proj", nq * hd, H,
+ out_dtype=torch.float))
+
+ @staticmethod
+ def _gdn_projs(config, L, G, H, idx):
+ if not MCPM_FOREIGN:
+ return {}
+ kd = config.linear_key_head_dim * config.linear_num_key_heads
+ vd = config.linear_value_head_dim * config.linear_num_value_heads
+ nb = config.linear_num_value_heads
+ # b/a are tiny ([2048, 32]) and the fused GDN kernels require fp16:
+ # dequantize once on CPU into in-memory overrides, plain Linears.
+ # b = beta (ssm_beta), a = alpha (ssm_alpha): swapped once, never again.
+ # MCPM_SWAP_BA=1 restores the original (alpha/beta) order for A/B.
+ if os.environ.get("MCPM_SWAP_BA", "0") == "1":
+ _fp_override(config, f"{L}.linear_attn.in_proj_b.weight", f"blk.{idx}.ssm_alpha.weight")
+ _fp_override(config, f"{L}.linear_attn.in_proj_a.weight", f"blk.{idx}.ssm_beta.weight")
+ else:
+ _fp_override(config, f"{L}.linear_attn.in_proj_b.weight", f"blk.{idx}.ssm_beta.weight")
+ _fp_override(config, f"{L}.linear_attn.in_proj_a.weight", f"blk.{idx}.ssm_alpha.weight")
+ # ssm_a stores -exp(A_log); the engine consumes A_log.
+ _alog_override(config, f"{L}.linear_attn.A_log", f"blk.{idx}.ssm_a")
+ return dict(
+ qkv_proj=_fl(config, f"{L}.linear_attn.in_proj_qkv", H, 2 * kd + vd,
+ out_dtype=torch.float),
+ z_proj=_fl(config, f"{L}.linear_attn.in_proj_z", H, vd,
+ out_dtype=torch.float),
+ b_proj=Linear(config, f"{L}.linear_attn.in_proj_b", H, nb,
+ out_dtype=torch.float, pad_to=1),
+ a_proj=Linear(config, f"{L}.linear_attn.in_proj_a", H, nb,
+ out_dtype=torch.float, pad_to=1),
+ o_proj=_fl(config, f"{L}.linear_attn.out_proj", vd, H,
+ out_dtype=torch.float))
+
+ @staticmethod
+ def _moe(config, L, G, H):
+ I = config.moe_intermediate_size
+ E = config.num_experts
+ if MCPM_FOREIGN:
+ gates = [_fl(config, f"{G}.ffn_gate_exps.e{e}", H, I) for e in range(E)]
+ ups = [_fl(config, f"{G}.ffn_up_exps.e{e}", H, I) for e in range(E)]
+ downs = [_fl(config, f"{G}.ffn_down_exps.e{e}", I, H,
+ out_dtype=torch.float) for e in range(E)]
+ SI = config.shared_expert_intermediate_size
+ sh = GatedMLP(
+ config=config, key=f"{L}.mlp.shared_expert",
+ hidden_size=H, intermediate_size=SI,
+ qmap="block.mlp", interm_dtype=torch.half, out_dtype=torch.float,
+ select_hq_bits=2,
+ gates=[_fl(config, f"{G}.ffn_gate_shexp", H, SI)],
+ ups=[_fl(config, f"{G}.ffn_up_shexp", H, SI)],
+ downs=[_fl(config, f"{G}.ffn_down_shexp", SI, H,
+ out_dtype=torch.float)])
+ mlp = BlockSparseMLP(
+ config=config, key=f"{L}.mlp", hidden_size=H,
+ intermediate_size=I, num_experts=E,
+ num_experts_per_tok=config.num_experts_per_tok,
+ key_up=None, key_gate=None, key_down=None,
+ key_routing_gate="gate", key_shared_gate="shared_expert_gate",
+ qmap="block.mlp", interm_dtype=torch.half, out_dtype=torch.float,
+ gates=gates, ups=ups, downs=downs, shared_experts=sh)
+ # Prebuilt lists bypass the internal builders, which are the only
+ # register_submodule call sites (Bolt precedent): register here so
+ # Module.load() recurses into them.
+ for m in gates + ups + downs + sh.gates + sh.ups + sh.downs:
+ mlp.register_submodule(m)
+ else:
+ mlp = BlockSparseMLP(
+ config=config, key=f"{L}.mlp", hidden_size=H,
+ intermediate_size=I, num_experts=E,
+ num_experts_per_tok=config.num_experts_per_tok,
+ key_up="experts.{expert_idx}.up_proj",
+ key_gate="experts.{expert_idx}.gate_proj",
+ key_down="experts.{expert_idx}.down_proj",
+ key_routing_gate="gate", key_shared_gate="shared_expert_gate",
+ qmap="block.mlp", interm_dtype=torch.half, out_dtype=torch.float)
+ return mlp
+
+ @override
+ def prepare_inputs(self, input_ids: torch.Tensor, params: dict) -> torch.Tensor:
+ input_ids = prepare_for_attn(input_ids, params)
+ prepare_for_recurrence(input_ids, params, self)
+ return input_ids
+
+ @override
+ def default_chat_prompt(self, prompt: str, system_prompt: str = None) -> str:
+ p = ""
+ if system_prompt:
+ p += "<|im_start|>system\n" + f"{system_prompt}<|im_end|>\n"
+ p += "<|im_start|>user\n" + f"{prompt}<|im_end|>\n" + "<|im_start|>assistant\n"
+ return p
diff --git a/exllamav3/architecture/nemotronh.py b/exllamav3/architecture/nemotronh.py
index f6371ba..6575aa4 100644
--- a/exllamav3/architecture/nemotronh.py
+++ b/exllamav3/architecture/nemotronh.py
@@ -18,6 +18,28 @@ from ..modules.attn import prepare_for_attn
from ..cache.recurrent_util import prepare_for_recurrence
from .nemotronh_mtp import NemotronHMTPModel
+# Bolt as-shipped port (feat/bolt1): BOLT_FOREIGN=1 builds the U8 checkpoint
+# tensors (ggml Q8_0 / IQ2_XXS, ModelOpt NVFP4) as ForeignLinear instead of
+# native Linear. Off by default; other Nemotron-H checkpoints are unaffected.
+try:
+ from ..modules.foreign_linear import ForeignLinear as _ForeignLinear
+ _FOREIGN_OK = True
+except ImportError: # pragma: no cover
+ _FOREIGN_OK = False
+
+
+def _norm_time_step_limit(ts):
+ """time_step_limit may carry JSON-encoded infinities
+ ({'__float__': 'Infinity'}) from the checkpoint config; the dt kernels
+ need real floats."""
+ out = []
+ for v in ts:
+ if isinstance(v, dict) and set(v) == {"__float__"}:
+ out.append(float(v["__float__"]))
+ else:
+ out.append(float(v))
+ return tuple(out)
+
class NemotronHConfig(Config):
arch_string = "NemotronHForCausalLM"
@@ -99,16 +121,32 @@ def nemotronh_block(
layer_idx: int,
block_type: str,
qbits_key: str = "bits",
+ foreign: bool = False,
) -> TransformerBlock:
"""One block of the hybrid pattern: M = Mamba2, * = attention, - = MLP, E = MoE. Shared by the
- trunk (backbone.layers.N) and the MTP head (mtp.layers.N, mtp_bits)"""
+ trunk (backbone.layers.N) and the MTP head (mtp.layers.N, mtp_bits)
+
+ foreign=True substitutes ForeignLinear for the U8 checkpoint tensors of
+ the Bolt QAT checkpoint (NVFP4 mamba in/out_proj, Q8_0 attention q/k/v/o);
+ every other tensor loads natively. Requires BOLT_FOREIGN wiring upstream.
+ """
+ if foreign and not _FOREIGN_OK:
+ raise ValueError("foreign=True needs exllamav3.modules.foreign_linear")
norm = RMSNorm(
config = config,
key = f"{key}.norm",
rms_norm_eps = config.layer_norm_epsilon,
)
+ if foreign:
+ _fl = lambda k, i, o, fmt, out_dtype = None: _ForeignLinear(
+ config, f"{key}.mixer.{k}", i, o, fmt, out_dtype = out_dtype)
+ else:
+ _fl = None
match block_type:
case "M":
+ m_v_dim = config.mamba_num_heads * config.mamba_head_dim
+ m_k_dim = config.n_groups * config.ssm_state_size
+ m_proj_dim = m_v_dim + (m_v_dim + 2 * m_k_dim) + config.mamba_num_heads
return TransformerBlock(
config = config,
key = key,
@@ -125,13 +163,19 @@ def nemotronh_block(
state_size = config.ssm_state_size,
rms_norm_eps = config.layer_norm_epsilon,
conv_kernel_size = config.conv_kernel,
- dt_limit = tuple(config.time_step_limit),
+ dt_limit = _norm_time_step_limit(config.time_step_limit),
qmap = "block.attn",
out_dtype = torch.float,
select_hq_bits = 2,
+ in_proj = _fl("in_proj", config.hidden_size, m_proj_dim, "nvfp4",
+ out_dtype = torch.float) if foreign else None,
+ o_proj = _fl("out_proj", m_v_dim, config.hidden_size, "nvfp4",
+ out_dtype = torch.float) if foreign else None,
),
)
case "*":
+ q_out = config.num_q_heads * config.head_dim
+ kv_out = config.num_kv_heads * config.head_dim
return TransformerBlock(
config = config,
key = key,
@@ -147,10 +191,14 @@ def nemotronh_block(
num_kv_heads = config.num_kv_heads,
rope_settings = None,
sm_scale = None,
- key_q = "q_proj",
- key_k = "k_proj",
- key_v = "v_proj",
- key_o = "o_proj",
+ key_q = None if foreign else "q_proj",
+ key_k = None if foreign else "k_proj",
+ key_v = None if foreign else "v_proj",
+ key_o = None if foreign else "o_proj",
+ q_proj = _fl("q_proj", config.hidden_size, q_out, "q8_0") if foreign else None,
+ k_proj = _fl("k_proj", config.hidden_size, kv_out, "q8_0") if foreign else None,
+ v_proj = _fl("v_proj", config.hidden_size, kv_out, "q8_0") if foreign else None,
+ o_proj = _fl("o_proj", q_out, config.hidden_size, "q8_0") if foreign else None,
qmap = "block.attn",
out_dtype = torch.float,
select_hq_bits = 2,
diff --git a/exllamav3/architecture/nemotronh_puzzle.py b/exllamav3/architecture/nemotronh_puzzle.py
new file mode 100644
index 0000000..39813bf
--- /dev/null
+++ b/exllamav3/architecture/nemotronh_puzzle.py
@@ -0,0 +1,678 @@
+"""Nemotron-H Puzzle config adapter (torch-free).
+
+Parses the per-layer ("Puzzle") block layout of NVIDIA Nemotron-H checkpoints
+such as ``nvidia/NVIDIA-Nemotron-3.5-Bolt-74B-A9B-24GB`` and builds a
+config-only module graph (no weights, no device tensors) that the engine's
+model builder can later materialize on meta/CUDA/HIP devices.
+
+Supported checkpoint shapes
+---------------------------
+* Raw Puzzle config: ``model_type == "nemotron_h_puzzle"``
+ (``NemotronHPuzzleForCausalLM``), tensor keys like
+ ``backbone.layers.0.mixer.in_proj``.
+* Omni wrapper: ``NemotronH_Omni_Reasoning_V3`` whose ``llm_config`` holds the
+ Puzzle config above. Checkpoint keys carry the ``language_model.`` prefix,
+ which this adapter strips. Vision keys (``vision_model.*``, ``mlp1.*``) are
+ recognized and skipped (text-only port; vision tower is deferred).
+
+Source: ``config.json`` + ``modeling_nemotron_h*.py`` of the Bolt checkpoint
+(model_type ``nemotron_h_puzzle``, 88 blocks: 40 Mamba2 / 40 latent-MoE /
+8 GQA-NoPE attention).
+
+This module deliberately imports only the standard library so the adapter and
+its unit test run anywhere (no torch, no compiled extension). The torch-based
+engine wiring (``NemotronHPuzzleConfig`` / model builder reusing the
+``Mamba2`` / ``Attention`` / ``BlockSparseMLP`` GENERIC blocks) lives in
+``nemotronh_puzzle_engine.py`` and is built from the spec produced here.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from dataclasses import dataclass, field
+
+# --------------------------------------------------------------------------
+# Constants
+# --------------------------------------------------------------------------
+
+#: Top-level architecture string of the shipped Omni checkpoint.
+OMNI_ARCHITECTURE = "NemotronH_Omni_Reasoning_V3"
+#: Architecture string of the raw Puzzle causal-LM config.
+PUZZLE_ARCHITECTURE = "NemotronHPuzzleForCausalLM"
+#: model_type of the LLM sub-config.
+PUZZLE_MODEL_TYPE = "nemotron_h_puzzle"
+
+#: Checkpoint key prefix of every LLM tensor inside the Omni wrapper.
+LLM_KEY_PREFIX = "language_model."
+#: Checkpoint key prefixes of the (currently skipped) vision tower + projector.
+VISION_KEY_PREFIXES = ("vision_model.", "mlp1.")
+
+#: Block types used in layers_block_type / block_configs.
+BLOCK_MAMBA = "mamba"
+BLOCK_MOE = "moe"
+BLOCK_ATTENTION = "attention"
+
+#: Bolt reference geometry (asserted by the CPU unit test).
+BOLT_NUM_LAYERS = 88
+BOLT_BLOCK_COUNTS = {BLOCK_MAMBA: 40, BLOCK_MOE: 40, BLOCK_ATTENTION: 8}
+BOLT_ATTENTION_INDICES = (7, 16, 25, 36, 47, 58, 69, 78)
+
+
+# --------------------------------------------------------------------------
+# Key mapping
+# --------------------------------------------------------------------------
+
+def is_vision_key(key: str) -> bool:
+ """True for checkpoint keys belonging to the skipped vision tower."""
+ return key.startswith(VISION_KEY_PREFIXES)
+
+
+def is_llm_key(key: str) -> bool:
+ """True for checkpoint keys belonging to the language model."""
+ return key.startswith(LLM_KEY_PREFIX)
+
+
+def strip_llm_prefix(key: str) -> str:
+ """Strip the Omni wrapper's ``language_model.`` prefix.
+
+ Vision keys raise (they are skipped, not mapped); keys without any known
+ prefix (bare Puzzle checkpoints) pass through unchanged.
+ """
+ if is_vision_key(key):
+ raise ValueError(f"Vision key has no LLM mapping (skipped): {key!r}")
+ if key.startswith(LLM_KEY_PREFIX):
+ return key[len(LLM_KEY_PREFIX):]
+ return key
+
+
+def map_checkpoint_key(key: str) -> str | None:
+ """Map a raw checkpoint key to the engine's (stripped) namespace.
+
+ Returns None for vision keys (skip), the stripped key otherwise.
+ """
+ if is_vision_key(key):
+ return None
+ return strip_llm_prefix(key)
+
+
+# --------------------------------------------------------------------------
+# Parsed spec
+# --------------------------------------------------------------------------
+
+@dataclass(frozen=True)
+class PuzzleBlockSpec:
+ """Per-layer block description from ``block_configs``."""
+ index: int
+ block_type: str
+ n_routed_experts: int = 0
+ moe_intermediate_size: int = 0
+ num_experts_per_tok: int = 0
+
+
+@dataclass
+class PuzzleSpec:
+ """Full parsed LLM config: globals + one spec per layer."""
+ model_type: str = PUZZLE_MODEL_TYPE
+ from_omni_wrapper: bool = False
+ hidden_size: int = 0
+ vocab_size: int = 0
+ num_hidden_layers: int = 0
+ max_position_embeddings: int = 0
+ layer_norm_epsilon: float = 1e-5
+ # Attention (NoPE GQA)
+ num_attention_heads: int = 0
+ num_key_value_heads: int = 0
+ head_dim: int = 0
+ # Mamba2
+ mamba_num_heads: int = 0
+ mamba_head_dim: int = 0
+ ssm_state_size: int = 0
+ n_groups: int = 0
+ conv_kernel: int = 4
+ # Latent MoE
+ moe_latent_size: int = 0
+ moe_shared_expert_intermediate_size: int = 0
+ routed_scaling_factor: float = 0.0
+ scoring_func: str = ""
+ norm_topk_prob: bool = False
+ blocks: list[PuzzleBlockSpec] = field(default_factory=list)
+
+ @property
+ def block_counts(self) -> dict[str, int]:
+ counts: dict[str, int] = {}
+ for b in self.blocks:
+ counts[b.block_type] = counts.get(b.block_type, 0) + 1
+ return counts
+
+ @property
+ def attention_indices(self) -> tuple[int, ...]:
+ return tuple(b.index for b in self.blocks if b.block_type == BLOCK_ATTENTION)
+
+ def block_at(self, index: int) -> PuzzleBlockSpec:
+ return self.blocks[index]
+
+ def moe_blocks(self) -> list[PuzzleBlockSpec]:
+ return [b for b in self.blocks if b.block_type == BLOCK_MOE]
+
+ def distinct_moe_specs(self) -> list[tuple[int, int]]:
+ return sorted({(b.n_routed_experts, b.moe_intermediate_size) for b in self.moe_blocks()})
+
+
+def load_llm_config_dict(config_dict: dict) -> tuple[dict, bool]:
+ """Unwrap the LLM sub-config.
+
+ Returns (llm_config_dict, from_omni_wrapper). Raises ValueError on
+ unknown architectures.
+ """
+ archs = config_dict.get("architectures", [])
+ model_type = config_dict.get("model_type", "")
+ if OMNI_ARCHITECTURE in archs or model_type == "nemotron_h_omni":
+ llm = config_dict.get("llm_config")
+ if not isinstance(llm, dict):
+ raise ValueError("Omni config has no llm_config dict")
+ return llm, True
+ if PUZZLE_ARCHITECTURE in archs or model_type == PUZZLE_MODEL_TYPE:
+ return config_dict, False
+ raise ValueError(f"Unsupported config architectures={archs} model_type={model_type!r}")
+
+
+def load_llm_config_file(path: str) -> tuple[dict, bool]:
+ """Read config.json (or a directory containing it) and unwrap it."""
+ if os.path.isdir(path):
+ path = os.path.join(path, "config.json")
+ with open(path, encoding="utf8") as f:
+ config_dict = json.load(f)
+ return load_llm_config_dict(config_dict)
+
+
+def parse_puzzle_spec(llm_config: dict, from_omni_wrapper: bool = False) -> PuzzleSpec:
+ """Parse + structurally validate a raw Puzzle LLM config dict."""
+ model_type = llm_config.get("model_type", "")
+ if model_type != PUZZLE_MODEL_TYPE:
+ raise ValueError(f"Expected model_type {PUZZLE_MODEL_TYPE!r}, got {model_type!r}")
+
+ layers_block_type = llm_config.get("layers_block_type")
+ block_configs = llm_config.get("block_configs")
+ if not isinstance(layers_block_type, list) or not isinstance(block_configs, list):
+ raise ValueError("Puzzle config needs layers_block_type + block_configs lists")
+ if len(layers_block_type) != len(block_configs):
+ raise ValueError(
+ f"layers_block_type ({len(layers_block_type)}) != "
+ f"block_configs ({len(block_configs)})"
+ )
+
+ blocks: list[PuzzleBlockSpec] = []
+ for i, (btype, bcfg) in enumerate(zip(layers_block_type, block_configs)):
+ if not isinstance(bcfg, dict) or bcfg.get("block_type") != btype:
+ raise ValueError(f"Layer {i}: block_configs entry does not match {btype!r}")
+ if btype not in (BLOCK_MAMBA, BLOCK_MOE, BLOCK_ATTENTION):
+ raise ValueError(f"Layer {i}: unknown block_type {btype!r}")
+ blocks.append(PuzzleBlockSpec(
+ index=i,
+ block_type=btype,
+ n_routed_experts=int(bcfg.get("n_routed_experts", 0) or 0),
+ moe_intermediate_size=int(bcfg.get("moe_intermediate_size", 0) or 0),
+ num_experts_per_tok=int(bcfg.get("num_experts_per_tok", 0) or 0),
+ ))
+
+ num_q = int(llm_config["num_attention_heads"])
+ hidden = int(llm_config["hidden_size"])
+ return PuzzleSpec(
+ model_type=model_type,
+ from_omni_wrapper=from_omni_wrapper,
+ hidden_size=hidden,
+ vocab_size=int(llm_config["vocab_size"]),
+ num_hidden_layers=len(blocks),
+ max_position_embeddings=int(llm_config.get("max_position_embeddings", 0) or 0),
+ layer_norm_epsilon=float(llm_config.get("layer_norm_epsilon", 1e-5)),
+ num_attention_heads=num_q,
+ num_key_value_heads=int(llm_config.get("num_key_value_heads", num_q)),
+ head_dim=int(llm_config.get("head_dim", 0) or hidden // num_q),
+ mamba_num_heads=int(llm_config.get("mamba_num_heads", 0) or 0),
+ mamba_head_dim=int(llm_config.get("mamba_head_dim", 0) or 0),
+ ssm_state_size=int(llm_config.get("ssm_state_size", 0) or 0),
+ n_groups=int(llm_config.get("n_groups", 0) or 0),
+ conv_kernel=int(llm_config.get("conv_kernel", 4)),
+ moe_latent_size=int(llm_config.get("moe_latent_size", 0) or 0),
+ moe_shared_expert_intermediate_size=int(
+ llm_config.get("moe_shared_expert_intermediate_size", 0) or 0),
+ routed_scaling_factor=float(llm_config.get("routed_scaling_factor", 0.0) or 0.0),
+ scoring_func=str(llm_config.get("scoring_func", "")),
+ norm_topk_prob=bool(llm_config.get("norm_topk_prob", False)),
+ blocks=blocks,
+ )
+
+
+def load_puzzle_spec(path: str) -> PuzzleSpec:
+ """Read config.json (file or directory) and return the validated spec."""
+ llm_config, wrapped = load_llm_config_file(path)
+ return parse_puzzle_spec(llm_config, from_omni_wrapper=wrapped)
+
+
+# --------------------------------------------------------------------------
+# Config-only module graph (no weights, no tensors)
+# --------------------------------------------------------------------------
+
+def block_key(index: int) -> str:
+ return f"backbone.layers.{index}"
+
+
+def iter_block_tensor_keys(node: PuzzleBlockSpec) -> "object":
+ """Yield the expected (stripped) weight keys of one block.
+
+ Names mirror both the HF reference (modeling_nemotron_h.py:
+ NemotronHBlock/NemotronHMoE) and the engine's GENERIC blocks
+ (Mamba2 in_proj/conv1d/A_log/dt_bias/D/norm/out_proj, Attention
+ q/k/v/o_proj, BlockSparseMLP experts.{i}.up/down + gate +
+ fc1/fc2_latent_proj + shared_experts), so the graph doubles as the
+ loader's key checklist. Generator: MoE layers enumerate per-expert keys.
+ """
+ base = block_key(node.index)
+ yield base + ".norm.weight"
+ mixer = base + ".mixer"
+ if node.block_type == BLOCK_MAMBA:
+ for name in ("in_proj.weight", "out_proj.weight",
+ "conv1d.weight", "conv1d.bias",
+ "A_log", "D", "dt_bias", "norm.weight"):
+ yield mixer + "." + name
+ elif node.block_type == BLOCK_ATTENTION:
+ for name in ("q_proj.weight", "k_proj.weight",
+ "v_proj.weight", "o_proj.weight"):
+ yield mixer + "." + name
+ elif node.block_type == BLOCK_MOE:
+ yield mixer + ".gate.weight"
+ yield mixer + ".gate.e_score_correction_bias"
+ yield mixer + ".fc1_latent_proj.weight"
+ yield mixer + ".fc2_latent_proj.weight"
+ yield mixer + ".shared_experts.up_proj.weight"
+ yield mixer + ".shared_experts.down_proj.weight"
+ for e in range(node.n_routed_experts):
+ yield f"{mixer}.experts.{e}.up_proj.weight"
+ yield f"{mixer}.experts.{e}.down_proj.weight"
+ else: # pragma: no cover - parse_puzzle_spec rejects these
+ raise ValueError(f"Unknown block_type {node.block_type!r}")
+
+
+TOP_LEVEL_TENSOR_KEYS = (
+ "backbone.embeddings.weight",
+ "backbone.norm_f.weight",
+ "lm_head.weight",
+)
+
+
+@dataclass
+class PuzzleGraph:
+ """Module graph from config only: one node per block + top-level keys.
+
+ No weights are loaded and no tensors are allocated; per-layer MoE dims
+ ride on the nodes so the engine builder can size each BlockSparseMLP.
+ """
+ spec: PuzzleSpec
+ nodes: list[PuzzleBlockSpec] = field(default_factory=list)
+
+ @property
+ def num_layers(self) -> int:
+ return len(self.nodes)
+
+ def find(self, key: str) -> PuzzleBlockSpec:
+ for n in self.nodes:
+ if block_key(n.index) == key:
+ return n
+ raise KeyError(key)
+
+ def count_tensors(self, materialize_moe_experts: bool = False) -> int:
+ """Number of expected weight tensors (top-level + blocks).
+
+ MoE expert keys are counted arithmetically unless materialized.
+ """
+ total = len(TOP_LEVEL_TENSOR_KEYS) + len(self.nodes) # block norms
+ for n in self.nodes:
+ if n.block_type == BLOCK_MAMBA:
+ total += 8
+ elif n.block_type == BLOCK_ATTENTION:
+ total += 4
+ else:
+ total += 6 + 2 * n.n_routed_experts
+ return total
+
+
+def build_puzzle_graph(spec: PuzzleSpec) -> PuzzleGraph:
+ """Build the config-only module graph for a parsed spec."""
+ return PuzzleGraph(spec=spec, nodes=list(spec.blocks))
+
+
+def summarize(spec: PuzzleSpec) -> str:
+ counts = spec.block_counts
+ return (
+ f"Nemotron-H Puzzle: {spec.num_hidden_layers} blocks "
+ f"({counts.get(BLOCK_MAMBA, 0)} mamba / "
+ f"{counts.get(BLOCK_MOE, 0)} moe / "
+ f"{counts.get(BLOCK_ATTENTION, 0)} attn), "
+ f"hidden={spec.hidden_size} vocab={spec.vocab_size} "
+ f"moe_latent={spec.moe_latent_size} "
+ f"{len(spec.distinct_moe_specs())} distinct MoE specs"
+ + (" [omni wrapper]" if spec.from_omni_wrapper else "")
+ )
+
+
+def strip_llm_prefix_from_maps(
+ tensor_file_map: dict,
+ file_headers: dict,
+) -> tuple[dict, dict]:
+ """Rewrite loader maps into the engine's (stripped) key namespace.
+
+ Pure-dict helper implementing the ``language_model.`` strip for the
+ engine's SafetensorsCollection: both ``tensor_file_map`` and every per-file
+ header (``get_tensor`` reads the tensor entry back out of the header).
+ Vision keys (``vision_model.*``, ``mlp1.*``) are dropped - the text-only
+ port does not load them. ``_header_offset`` entries are preserved.
+ """
+ new_map: dict = {}
+ for key, filename in tensor_file_map.items():
+ mapped = map_checkpoint_key(key)
+ if mapped is None:
+ continue
+ new_map[mapped] = filename
+ new_headers: dict = {}
+ for filename, header in file_headers.items():
+ renamed: dict = {}
+ for key, entry in header.items():
+ if key in ("__metadata__", "_header_offset"):
+ continue
+ mapped = map_checkpoint_key(key)
+ if mapped is None:
+ continue
+ renamed[mapped] = entry
+ if "_header_offset" in header:
+ renamed["_header_offset"] = header["_header_offset"]
+ new_headers[filename] = renamed
+ return new_map, new_headers
+
+
+# --------------------------------------------------------------------------
+# Engine wiring (torch required; skipped on torch-free imports so the spec
+# adapter above stays usable - and unit-testable - without torch)
+# --------------------------------------------------------------------------
+
+try:
+ import torch as _torch
+ from ..model.config import Config as _EngineConfig
+ from ..model.model import Model as _EngineModel
+ from ..modules import (
+ RMSNorm as _RMSNorm,
+ Embedding as _Embedding,
+ TransformerBlock as _TransformerBlock,
+ BlockSparseMLP as _BlockSparseMLP,
+ MLP as _MLP,
+ Linear as _Linear,
+ GDNState as _GDNState,
+ )
+ from ..modules.attn import prepare_for_attn as _prepare_for_attn
+ from ..cache.recurrent_util import (
+ prepare_for_recurrence as _prepare_for_recurrence,
+ )
+ from .nemotronh import nemotronh_block as _nemotronh_block
+ from ..modules.foreign_linear import ForeignLinear as _ForeignLinear
+ _ENGINE_AVAILABLE = True
+except ImportError: # pragma: no cover - no torch on CPU-only test hosts
+ _ENGINE_AVAILABLE = False
+
+#: BOLT_FOREIGN=1 runs the shipped QAT weights as-is (ForeignLinear over the
+#: U8 Q8_0 / IQ2_XXS / NVFP4 checkpoint tensors) instead of native Linear.
+BOLT_FOREIGN = os.environ.get("BOLT_FOREIGN", "0") != "0"
+
+
+def _fl(config, key: str, in_features: int, out_features: int, format: str,
+ out_dtype=None):
+ return _ForeignLinear(config, key, in_features, out_features, format,
+ out_dtype=out_dtype)
+
+
+if _ENGINE_AVAILABLE:
+
+ class NemotronHPuzzleConfig(_EngineConfig):
+ """Engine config for the Omni-wrapped Puzzle checkpoint.
+
+ Top-level architecture is ``NemotronH_Omni_Reasoning_V3``; the LLM
+ hyper-parameters live in the nested ``llm_config`` dict, which becomes
+ this config's ``config_dict`` after init. The loader maps are
+ rewritten into the stripped namespace (``language_model.`` removed,
+ vision keys dropped).
+ """
+
+ arch_string = OMNI_ARCHITECTURE
+
+ def __init__(self, directory: str, **kwargs):
+ super().__init__(directory, {"text": NemotronHPuzzleModel}, **kwargs)
+
+ llm_config, wrapped = load_llm_config_dict(self.config_dict)
+ if not wrapped:
+ raise ValueError(
+ "NemotronHPuzzleConfig expects the Omni wrapper config "
+ f"({OMNI_ARCHITECTURE}); got a bare Puzzle config."
+ )
+ self.config_dict = llm_config
+
+ # Re-read the base fields from the LLM dict (mirror Config).
+ self.bos_token_id = self.read_cfg(int, ["bos_token_id"], None)
+ self.eos_token_id = self.read_cfg([int, list], ["eos_token_id"], None)
+ self.pad_token_id = self.read_cfg(int, ["pad_token_id"], None)
+ self.vocab_size = self.read_cfg(int, ["vocab_size"], None)
+ if isinstance(self.eos_token_id, list):
+ self.eos_token_id_list = self.eos_token_id
+ self.eos_token_id = self.eos_token_id[0]
+ else:
+ self.eos_token_id_list = [self.eos_token_id]
+ self.eos_token_id_list = [e for e in self.eos_token_id_list if e is not None]
+ self.max_position_embeddings = self.read_cfg(
+ int, ["max_position_embeddings"],
+ self.default_max_position_embeddings(),
+ )
+
+ self.puzzle_spec = parse_puzzle_spec(llm_config, from_omni_wrapper=True)
+ spec = self.puzzle_spec
+
+ self.hidden_size = spec.hidden_size
+ self.num_q_heads = spec.num_attention_heads
+ self.num_kv_heads = spec.num_key_value_heads
+ self.head_dim = spec.head_dim
+ self.mamba_num_heads = spec.mamba_num_heads
+ self.mamba_head_dim = spec.mamba_head_dim
+ self.ssm_state_size = spec.ssm_state_size
+ self.n_groups = spec.n_groups
+ self.conv_kernel = spec.conv_kernel
+ self.time_step_limit = self.read_cfg(
+ list, "time_step_limit", [0.0, float("inf")])
+ self.intermediate_size = self.read_cfg(int, "intermediate_size", 0)
+ self.moe_latent_size = spec.moe_latent_size or None
+ self.shared_expert_intermediate_size = (
+ spec.moe_shared_expert_intermediate_size)
+ self.routed_scaling_factor = spec.routed_scaling_factor or 2.5
+ self.layer_norm_epsilon = spec.layer_norm_epsilon
+ self.num_hidden_layers = spec.num_hidden_layers
+ self.tie_word_embeddings = self.read_cfg(
+ bool, "tie_word_embeddings", False)
+
+ (self.stc.tensor_file_map, self.stc.file_headers) = (
+ strip_llm_prefix_from_maps(
+ self.stc.tensor_file_map, self.stc.file_headers))
+
+ def get_tensor_name_fixes(self):
+ return {}
+
+
+ def nemotronh_puzzle_block(config, key: str, layer_idx: int,
+ block_spec=None):
+ """One hybrid block with per-layer (Puzzle) MoE dims.
+
+ Mamba ("M") and attention ("*") reuse the GENERIC ``nemotronh_block``
+ builders; MoE ("E") sizes this layer's ``BlockSparseMLP`` from its own
+ ``block_configs`` entry instead of a global MoE size.
+ """
+ spec = block_spec or config.puzzle_spec.block_at(layer_idx)
+ if spec.block_type == BLOCK_MAMBA:
+ return _nemotronh_block(config, key, layer_idx, "M", foreign=BOLT_FOREIGN)
+ if spec.block_type == BLOCK_ATTENTION:
+ return _nemotronh_block(config, key, layer_idx, "*", foreign=BOLT_FOREIGN)
+ if spec.block_type != BLOCK_MOE:
+ raise ValueError(f"Unknown Puzzle block_type {spec.block_type!r}")
+ norm = _RMSNorm(
+ config=config,
+ key=f"{key}.norm",
+ rms_norm_eps=config.layer_norm_epsilon,
+ )
+ if BOLT_FOREIGN:
+ hid, lat = config.hidden_size, config.moe_latent_size
+ inter, sh_inter = spec.moe_intermediate_size, config.shared_expert_intermediate_size
+ n_exp = spec.n_routed_experts
+ fups = [_fl(config, f"{key}.mixer.experts.{i}.up_proj", lat, inter, "iq2_xxs")
+ for i in range(n_exp)]
+ fdowns = [_fl(config, f"{key}.mixer.experts.{i}.down_proj", inter, lat, "iq2_xxs",
+ out_dtype=_torch.float) for i in range(n_exp)]
+ flat_in = _fl(config, f"{key}.mixer.fc1_latent_proj", hid, lat, "q8_0")
+ flat_out = _fl(config, f"{key}.mixer.fc2_latent_proj", lat, hid, "q8_0",
+ out_dtype=_torch.float)
+ sh_up = _fl(config, f"{key}.mixer.shared_experts.up_proj", hid, sh_inter, "iq2_xxs")
+ sh_down = _fl(config, f"{key}.mixer.shared_experts.down_proj", sh_inter, hid, "iq2_xxs",
+ out_dtype=_torch.float)
+ else:
+ fups = fdowns = flat_in = flat_out = sh_up = sh_down = None
+ # Prebuilt foreign lists bypass the internal builders, which are also
+ # the only register_submodule call sites: register them here so
+ # Module.load() recurses into them (routing gate + latent projs
+ # register themselves; MLP prebuilts never do).
+ mlp = _BlockSparseMLP(
+ config=config,
+ key=f"{key}.mixer",
+ hidden_size=config.hidden_size,
+ intermediate_size=spec.moe_intermediate_size,
+ num_experts=spec.n_routed_experts,
+ num_experts_per_tok=spec.num_experts_per_tok,
+ latent_size=config.moe_latent_size,
+ key_latent_in=None if BOLT_FOREIGN else ("fc1_latent_proj" if config.moe_latent_size else None),
+ key_latent_out=None if BOLT_FOREIGN else ("fc2_latent_proj" if config.moe_latent_size else None),
+ latent_in=flat_in,
+ latent_out=flat_out,
+ latent_hq_bits=2,
+ key_up=None if BOLT_FOREIGN else "experts.{expert_idx}.up_proj",
+ key_down=None if BOLT_FOREIGN else "experts.{expert_idx}.down_proj",
+ gates=[] if BOLT_FOREIGN else None,
+ ups=fups,
+ downs=fdowns,
+ key_routing_gate="gate",
+ activation_fn="relu2",
+ router_type="dots",
+ routed_scaling_factor=config.routed_scaling_factor,
+ n_group=1,
+ topk_group=1,
+ qmap="block.mlp",
+ interm_dtype=_torch.half,
+ out_dtype=_torch.float,
+ shared_experts=_MLP(
+ config=config,
+ key=f"{key}.mixer.shared_experts",
+ hidden_size=config.hidden_size,
+ intermediate_size=config.shared_expert_intermediate_size,
+ key_up=None if BOLT_FOREIGN else "up_proj",
+ key_down=None if BOLT_FOREIGN else "down_proj",
+ ups=[sh_up] if BOLT_FOREIGN else None,
+ downs=[sh_down] if BOLT_FOREIGN else None,
+ activation_fn="relu2",
+ qmap="block.mlp",
+ out_dtype=_torch.float,
+ select_hq_bits=2,
+ ),
+ )
+ if BOLT_FOREIGN:
+ for m in fups + fdowns:
+ mlp.register_submodule(m)
+ mlp.shared_experts.register_submodule(sh_up)
+ mlp.shared_experts.register_submodule(sh_down)
+ return _TransformerBlock(
+ config=config,
+ key=key,
+ layer_idx=layer_idx,
+ mlp_norm=norm,
+ mlp=mlp,
+ )
+
+
+ class NemotronHPuzzleModel(_EngineModel):
+ """Text-only model over the stripped key namespace."""
+
+ config_class = NemotronHPuzzleConfig
+
+ def __init__(self, config: NemotronHPuzzleConfig, **kwargs):
+ super().__init__(config, **kwargs)
+
+ self.modules += [
+ _Embedding(
+ config=config,
+ key="backbone.embeddings",
+ vocab_size=config.vocab_size,
+ hidden_size=config.hidden_size,
+ )
+ ]
+
+ self.first_block_idx = len(self.modules)
+
+ for idx in range(config.num_hidden_layers):
+ self.modules.append(nemotronh_puzzle_block(
+ config, f"backbone.layers.{idx}", idx))
+
+ self.last_kv_module_idx = len(self.modules) - 1
+
+ head_alt_key = None
+ if config.tie_word_embeddings and not self.config.stc.has_tensor("lm_head"):
+ head_alt_key = "backbone.embeddings"
+
+ if BOLT_FOREIGN:
+ head = _fl(config, "lm_head", config.hidden_size, config.vocab_size, "q8_0")
+ head.caps["logits_output"] = True
+ else:
+ head = _Linear(
+ config=config,
+ key="lm_head",
+ qbits_key="head_bits",
+ alt_key=head_alt_key,
+ in_features=config.hidden_size,
+ out_features=config.vocab_size,
+ qmap="block",
+ caps={"logits_output": True},
+ )
+ self.modules += [
+ _RMSNorm(
+ config=config,
+ key="backbone.norm_f",
+ rms_norm_eps=config.layer_norm_epsilon,
+ out_dtype=_torch.half,
+ ),
+ head,
+ ]
+
+ self.logit_layer_idx = len(self.modules) - 1
+ self.calibration_all_experts = True
+
+ self.caps.update({
+ "recurrent_states": True,
+ "default_recurrent_checkpoint_interval": 2048,
+ "linear_attn": True,
+ })
+ self.recurrent_state_cls = _GDNState
+ self.caps.update({"supports_tp": True})
+
+ def prepare_inputs(self, input_ids, params):
+ input_ids = _prepare_for_attn(input_ids, params)
+ _prepare_for_recurrence(input_ids, params, self)
+ return input_ids
+
+ def default_chat_prompt(self, prompt: str, system_prompt: str = None) -> str:
+ p = ""
+ if system_prompt:
+ p += "<|im_start|>system\n"
+ p += f"{system_prompt}<|im_end|>\n"
+ p += "<|im_start|>user\n"
+ p += f"{prompt}<|im_end|>\n"
+ p += "<|im_start|>assistant\n"
+ return p
diff --git a/exllamav3/architecture/qwen3_5_mtp.py b/exllamav3/architecture/qwen3_5_mtp.py
index 104a554..6099784 100644
--- a/exllamav3/architecture/qwen3_5_mtp.py
+++ b/exllamav3/architecture/qwen3_5_mtp.py
@@ -1,5 +1,6 @@
from __future__ import annotations
from typing_extensions import override
+import os
import torch
import weakref
@@ -228,6 +229,29 @@ class Qwen3_5MTPModel(Model):
return {}
+ def _draft_subhead(self, lm):
+ """The draft head restricted to the first EXL3_DRAFT_VOCAB vocabulary rows (a multiple of 128: the head's output
+ Hadamard works on 128-row blocks, so a prefix of whole blocks is a self-contained EXL3 linear with the same
+ trellis tiles). None when off or when the head is not a plain integer-K EXL3 linear. Every draft is verified by the
+ target, so a draft that misses a rare id only costs an accept, never changes the text."""
+ n = int(os.environ.get("EXL3_DRAFT_VOCAB", "0") or 0) // 128 * 128
+ if n <= 0:
+ return None
+ cache = self.__dict__.setdefault("_dsub", {})
+ if n in cache:
+ return cache[n]
+ sub = None
+ inner = getattr(lm, "inner", None)
+ if inner is not None and type(inner).__name__ == "LinearEXL3" and isinstance(inner.K, int) \
+ and inner.bias is None and lm.pre_scale == 1.0 and lm.post_scale == 1.0 and lm.softcap == 0.0 \
+ and n < lm.out_features:
+ from ..modules.quant.exl3 import LinearEXL3
+ sub = LinearEXL3(None, inner.in_features, n, suh = inner.suh, svh = inner.svh[:n].contiguous(),
+ trellis = inner.trellis[:, :n // 16].contiguous(), mcg = inner.mcg_tensor,
+ mul1 = inner.mul1_tensor, out_dtype = inner.out_dtype)
+ cache[n] = sub
+ return sub
+
def sample_from_state(
self,
state: torch.Tensor,
@@ -237,6 +261,30 @@ class Qwen3_5MTPModel(Model):
ll = self.attached_model().logit_layer_idx
lm = self.attached_model().modules[ll]
logits = lm.prepare_for_device(state, params)
+ # EXL3_DRAFT_VOCAB=N: 1-row draft steps read only the first N vocabulary rows of the head (the common BPE ids).
+ # Every 8th step runs both heads and compares the argmax: a language whose tokens sit above N (French, CJK ...)
+ # switches the subset off until the probes agree again.
+ sub = self._draft_subhead(lm) if state.shape[0] * state.shape[1] == 1 and not params.get("export_draft_logits") else None
+ if sub is not None:
+ st = self.__dict__.setdefault("_dsub_st", {"calls": 0, "ema": 0.0, "on": True})
+ st["calls"] += 1
+ probe = st["calls"] % 8 == 0
+ if st["on"] or probe:
+ sl = sub.forward(logits, params)[..., :min(sub.out_features, self.attached_model().config.vocab_size)].float()
+ conf, ids = torch.max(sl, dim = -1)
+ pp = (1.0 / torch.exp(sl - conf.unsqueeze(-1)).sum(-1)).reshape(-1) # max probability over the subset
+ if probe:
+ fl = lm.forward(logits, params)[..., :self.attached_model().config.vocab_size].float()
+ fconf, fids = torch.max(fl, dim = -1)
+ miss = float((fids != ids).any().item())
+ st["ema"] = 0.9 * st["ema"] + 0.1 * miss
+ st["on"] = st["ema"] < (0.12 if st["on"] else 0.04) # hysteresis: ~1 % misses on English / code, ~20 % on French
+ conf, ids = fconf, fids
+ pp = (1.0 / torch.exp(fl - fconf.unsqueeze(-1)).sum(-1)).reshape(-1)
+ params["draft_p"] = pp
+ if params.get("export_draft_conf"):
+ params["draft_conf"] = conf
+ return ids
logits = lm.forward(logits, params)
if params.get("export_draft_conf"):
# Per-position confidence for the generator's draft truncation: the argmax logit
diff --git a/exllamav3/architecture/qwen4_exp.py b/exllamav3/architecture/qwen4_exp.py
index 331d6a3..0127efd 100644
--- a/exllamav3/architecture/qwen4_exp.py
+++ b/exllamav3/architecture/qwen4_exp.py
@@ -309,6 +309,7 @@ class Qwen4ExpModel(Model):
"recurrent_states": True,
"default_recurrent_checkpoint_interval": 2048,
"linear_attn": True,
+ "row_inv_groups": True,
})
self.recurrent_state_cls = GDNState
diff --git a/exllamav3/cache/recurrent.py b/exllamav3/cache/recurrent.py
index ddb2b0d..93e1236 100644
--- a/exllamav3/cache/recurrent.py
+++ b/exllamav3/cache/recurrent.py
@@ -39,6 +39,9 @@ class RecurrentCache(OrderedDict):
# EXL3_NC2_ASYNC_STASH: stashes whose D2H is still in flight (see settle)
self._pending = []
self._pin_pool = {} # (shape, dtype) -> pinned host tensors free for reuse
+ # page hash -> exactness tag of the checkpoint stashed under it (Job._stash_exact); outside the stash dict, whose
+ # asynchronous finisher thread is still writing to it
+ self.exact_meta = OrderedDict()
self._worker = None
self.metrics = {
"stash_evictions": 0, # checkpoints dropped by LRU pressure
@@ -149,17 +152,20 @@ class RecurrentCache(OrderedDict):
self.metrics["stash_evictions_live_kv"] += 1
self.metrics["stash_evictions"] += 1
+ self.exact_meta.pop(popped_key, None)
note_freed(popped["checkpoint_size"])
if self.model.loaded_tp:
self.model.tp_dispatch_all(mp_cache_recurrent_del, (id(self), popped["tp_handle"]))
self[key] = stashed_state
+ self.exact_meta.pop(key, None) # a tag belongs to the stash it was made for (Job._stash_exact sets it after put)
self.update_total_size()
def drop(self, key) -> None:
"""Remove one checkpoint (rolling-checkpoint cleanup)."""
popped = self.pop(key, None)
+ self.exact_meta.pop(key, None)
if popped is None:
return
note_freed(popped["checkpoint_size"])
@@ -180,6 +186,7 @@ class RecurrentCache(OrderedDict):
stranded = [k for k in self if not self.pagetable.is_resumable(k)]
for k in stranded:
popped = self.pop(k)
+ self.exact_meta.pop(k, None)
self.metrics["stash_pruned"] += 1
note_freed(popped["checkpoint_size"])
if self.model.loaded_tp:
diff --git a/exllamav3/conversion/convert_model.py b/exllamav3/conversion/convert_model.py
index 1f33108..f0ca51a 100644
--- a/exllamav3/conversion/convert_model.py
+++ b/exllamav3/conversion/convert_model.py
@@ -434,6 +434,48 @@ def print_quantized_linear(config, linear, quant_args, proxy_err, time_str = "")
)
+def build_rwh_blends(linears, capture_H):
+ """EXL3_RWH: per-expert Hessian = routed-weighted H (normalised) blended with the all-token H.
+ beta_e = max(beta0, 1 - n_eff/n_ref) with n_eff = (sum w^2)^2 / sum w^4 (effective routed sample size), so rarely
+ routed experts lean on the all-token Hessian. The blend keeps the all-token H's trace."""
+ beta0 = float(os.environ.get("EXL3_RWH_BETA0", "0.15"))
+ n_ref = float(os.environ.get("EXL3_RWH_NREF", "8192"))
+ done = {}
+ stats = []
+ neffs = []
+ for l in linears:
+ if not l.qmap_q or l.qmap_q in capture_H:
+ continue
+ base = capture_H[l.qmap]
+ hr = capture_H.get(l.cap_rkey)
+ if hr is None: # expert never routed in the calibration set: all-token H
+ capture_H[l.qmap_q] = base
+ stats.append(1.0)
+ continue
+ n_eff = (hr["sw2"] ** 2 / (hr["sw4"] + 1e-30)).item()
+ if l.cap_rkey.endswith(".input") and l.key.endswith("up_proj"):
+ neffs.append((n_eff, hr["count"]))
+ beta = max(beta0, 1.0 - n_eff / n_ref)
+ Ha, Hr = base["H"], hr["H"]
+ Ha = Ha.to(Hr.device) if Ha.device != Hr.device else Ha
+ ta, tr = Ha.diagonal().sum().clamp_min(1e-30), Hr.diagonal().sum().clamp_min(1e-30)
+ Hb = (1.0 - beta) * Hr * (ta / tr) + beta * Ha
+ d = dict(base)
+ d["H"] = Hb
+ d["finalized"] = False
+ capture_H[l.qmap_q] = d
+ stats.append(beta)
+ if stats:
+ import statistics
+ print(f" -- RWH: {len(stats)} expert Hessians blended, beta mean {statistics.mean(stats):.3f} "
+ f"max {max(stats):.3f} (beta0 {beta0}, n_ref {n_ref:.0f})")
+ if neffs:
+ ne = sorted(n for n, _ in neffs); cn = sorted(c for _, c in neffs)
+ q = lambda v, f: v[min(len(v) - 1, int(f * len(v)))]
+ print(f" -- RWH coverage per expert: routed tokens min {cn[0]} p5 {q(cn, .05)} median {q(cn, .5)}; "
+ f"n_eff min {ne[0]:.0f} p5 {q(ne, .05):.0f} median {q(ne, .5):.0f}")
+
+
def group_quant_linears(linears, strategy, capture_H, max_cat_cols = 32768, max_stack = 16):
"""
Partition linears into groups for batched quantization. Tensors sharing a Hessian (same qmap) at the same
@@ -526,7 +568,7 @@ def quantize_linears_single(args, linears, config, strategy, idx, devices, devic
with Timer() as t:
proxy_errs = convert_exl3_group(
group,
- [capture_H[l.qmap] for l in group],
+ [capture_H[l.qmap_q or l.qmap] for l in group],
quant_args_list,
progress_str = f" -- <step>: {group_label(group)}",
)
@@ -557,7 +599,7 @@ def quantize_linears_single(args, linears, config, strategy, idx, devices, devic
sr = os.path.join(args["work_dir"], f"images/{linear.key}.reg.jpg") \
if args["image_dump"] else None
proxy_err = linear.convert_exl3(
- capture_H[linear.qmap] if state else linear.init_H_data(False),
+ capture_H[linear.qmap_q or linear.qmap] if state else linear.init_H_data(False),
quant_args = quant_args,
progress_str = f" -- <step>: {linear.key}",
verbose = args["verbose"],
@@ -641,7 +683,7 @@ def quantize_linears_parallel(args, linears, config, strategy, idx, devices, dev
quant_args_list = [make_quant_args(args, idx, strategy[l.key], [device_idx]) for l in group]
proxy_errs = convert_exl3_group(
group,
- [capture_H[l.qmap] for l in group],
+ [capture_H[l.qmap_q or l.qmap] for l in group],
quant_args_list,
)
for linear, quant_args_local, proxy_err in zip(group, quant_args_list, proxy_errs):
@@ -656,7 +698,7 @@ def quantize_linears_parallel(args, linears, config, strategy, idx, devices, dev
quant_args_local = make_quant_args(args, idx, strategy[linear.key], [device_idx])
proxy_err = linear.convert_exl3(
- capture_H[linear.qmap] if state else linear.init_H_data(False),
+ capture_H[linear.qmap_q or linear.qmap] if state else linear.init_H_data(False),
quant_args = quant_args_local,
verbose = args["verbose"],
save_reg = False,
@@ -1367,6 +1409,8 @@ def main(args, job_state):
# Get submodules to quantize
linears = [m for m in module if isinstance(m, Linear) and m.qmap and m.device is not None]
+ if state is not None:
+ build_rwh_blends(linears, capture_H)
for linear in linears:
assert linear.key in strategy, \
f" ## Logic error, no quantization strategy for module {linear.key}"
diff --git a/exllamav3/exllamav3_ext/bindings.cpp b/exllamav3/exllamav3_ext/bindings.cpp
index 0cad98c..2bcf157 100644
--- a/exllamav3/exllamav3_ext/bindings.cpp
+++ b/exllamav3/exllamav3_ext/bindings.cpp
@@ -40,6 +40,7 @@
#include "quant/util.cuh"
#include "quant/exl3_devctx.cuh"
#include "quant/exl3_moe.cuh"
+#include "quant/exl3_moe_grouped.cuh"
#include "quant/exl3_moe_coop.cuh"
#include "generator/strings.h"
@@ -75,11 +76,14 @@
#include "dsv4_pool_quant.cuh"
#include "dsa_topk.cuh"
#include "ple.cuh"
+#include "dflash2.cuh"
#include "ngram.cuh"
#include "attention.cuh"
#include "sam.h"
+#include "quant/exl3_dec.cuh"
+#include "foreign_quant/fq_api.h"
#else
@@ -125,8 +129,74 @@ static inline bool hgemm_gil_free(const at::Tensor& a)
}
#endif
+#if defined(USE_ROCM) || defined(EXL3_PORT_DEC)
+// exl3_dec decode kernels (quant/exl3_dec.cu): always bound on ROCm; on CUDA only in an EXL3_PORT_DEC build
+// and only when EXL3_PORT_DEC=1 at import (Python switches them on by hasattr; default = the upstream CUDA path)
+static void bind_exl3_dec(py::module_& m)
+{
+ m.def("exl3_dec_gemv", &exl3_dec_gemv, "exl3_dec_gemv",
+ py::arg("x"), py::arg("trellis"), py::arg("suh"), py::arg("svh"), py::arg("out"),
+ py::arg("scratch"), py::arg("counters"), py::arg("K"), py::arg("mcg") = false);
+ m.def("exl3_dec_gemv_multi", &exl3_dec_gemv_multi, "exl3_dec_gemv_multi",
+ py::arg("x"), py::arg("trellis"), py::arg("suh"), py::arg("svh"), py::arg("out"),
+ py::arg("scratch"), py::arg("counters"), py::arg("K"), py::arg("mcg") = false);
+ m.def("exl3_dec_gemv_x", &exl3_dec_gemv_x, "exl3_dec_gemv_x",
+ py::arg("x"), py::arg("trellis"), py::arg("suh"), py::arg("svh"), py::arg("out"),
+ py::arg("scratch"), py::arg("counters"), py::arg("K"), py::arg("mcg") = false,
+ py::arg("x_job_stride") = 0, py::arg("strips_hint") = 0);
+ m.def("exl3_dec_moe", &exl3_dec_moe, "exl3_dec_moe",
+ py::arg("x"), py::arg("out"), py::arg("selected"), py::arg("weights"),
+ py::arg("gate_trellis"), py::arg("gate_suh"), py::arg("gate_svh"),
+ py::arg("up_trellis"), py::arg("up_suh"), py::arg("up_svh"),
+ py::arg("down_trellis"), py::arg("down_suh"), py::arg("down_svh"),
+ py::arg("act"), py::arg("scratch"), py::arg("counters"),
+ py::arg("intermediate"), py::arg("K_gu"), py::arg("K_down"),
+ py::arg("accumulate"), py::arg("act_limit") = 0.0, py::arg("mcg") = false);
+ m.def("exl3_dec_moe_shared", &exl3_dec_moe_shared, "exl3_dec_moe_shared",
+ py::arg("x"), py::arg("out"), py::arg("selected"), py::arg("weights"),
+ py::arg("gate_trellis"), py::arg("gate_suh"), py::arg("gate_svh"),
+ py::arg("up_trellis"), py::arg("up_suh"), py::arg("up_svh"),
+ py::arg("down_trellis"), py::arg("down_suh"), py::arg("down_svh"),
+ py::arg("sh_gate_trellis"), py::arg("sh_gate_suh"), py::arg("sh_gate_svh"),
+ py::arg("sh_up_trellis"), py::arg("sh_up_suh"), py::arg("sh_up_svh"),
+ py::arg("sh_down_trellis"), py::arg("sh_down_suh"), py::arg("sh_down_svh"),
+ py::arg("act"), py::arg("scratch"), py::arg("counters"),
+ py::arg("intermediate"), py::arg("K_gu"), py::arg("K_down"),
+ py::arg("K_sh_gu"), py::arg("K_sh_down"),
+ py::arg("accumulate"), py::arg("act_limit") = 0.0, py::arg("mcg") = false);
+ m.def("exl3_dec_moe_union", &exl3_dec_moe_union, "exl3_dec_moe_union",
+ py::arg("x"), py::arg("out"), py::arg("selected"), py::arg("weights"),
+ py::arg("gate_trellis"), py::arg("gate_suh"), py::arg("gate_svh"),
+ py::arg("up_trellis"), py::arg("up_suh"), py::arg("up_svh"),
+ py::arg("down_trellis"), py::arg("down_suh"), py::arg("down_svh"),
+ py::arg("act"), py::arg("down_part"), py::arg("scratch"), py::arg("counters"),
+ py::arg("intermediate"), py::arg("K_gu"), py::arg("K_down"),
+ py::arg("accumulate"), py::arg("act_limit") = 0.0, py::arg("mcg") = false,
+ py::arg("device_table") = false);
+ m.def("exl3_dec_gemv_strided", &exl3_dec_gemv_strided, "exl3_dec_gemv_strided",
+ py::arg("x"), py::arg("trellis"), py::arg("suh"), py::arg("svh"), py::arg("out"),
+ py::arg("scratch"), py::arg("counters"), py::arg("K"), py::arg("in_features"),
+ py::arg("x_gstride"), py::arg("mcg") = false);
+ m.def("exl3_dec_gemv_r", &exl3_dec_gemv_r, "exl3_dec_gemv_r",
+ py::arg("x"), py::arg("trellis"), py::arg("suh"), py::arg("svh"), py::arg("out"),
+ py::arg("scratch"), py::arg("counters"), py::arg("K"), py::arg("mcg") = false);
+ m.def("exl3_dec_gemv_r_multi", &exl3_dec_gemv_r_multi, "exl3_dec_gemv_r_multi",
+ py::arg("x"), py::arg("trellis"), py::arg("suh"), py::arg("svh"), py::arg("out"),
+ py::arg("scratch"), py::arg("counters"), py::arg("K"), py::arg("mcg") = false);
+ m.def("exl3_dec_router_norm", &exl3_dec_router_norm, "exl3_dec_router_norm");
+ m.def("exl3_dec_router", &exl3_dec_router, "exl3_dec_router");
+ m.def("exl3_dec_router_rows", &exl3_dec_router_rows, "exl3_dec_router_rows");
+ m.def("exl3_dec_rms_norm", &exl3_dec_rms_norm, "exl3_dec_rms_norm");
+}
+#endif
+
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
{
+#if !defined(USE_ROCM)
+ m.attr("HAS_DFLASH2") = true; // dflash2_dynconv, dflash2_selector_walk, dflash2_topk
+#else
+ m.attr("HAS_DFLASH2") = false; // dflash2.cu is excluded from ROCm builds
+#endif
m.def("stloader_read", &stloader_read, "stloader_read");
m.def("stloader_open_file", &stloader_open_file, "stloader_open_file");
m.def("stloader_close_file", &stloader_close_file, "stloader_close_file");
@@ -177,6 +247,9 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
m.def("dsa_topk_tile", &dsa_topk_tile, "dsa_topk_tile");
m.def("dsa_topk_merge_tiles", &dsa_topk_merge_tiles, "dsa_topk_merge_tiles");
m.def("ple_gate", &ple_gate, "ple_gate");
+ m.def("dflash2_dynconv", &dflash2_dynconv, "dflash2_dynconv");
+ m.def("dflash2_selector_walk", &dflash2_selector_walk, "dflash2_selector_walk");
+ m.def("dflash2_topk", &dflash2_topk, "dflash2_topk");
m.def("ple_forward_streams", &ple_forward_streams, "ple_forward_streams");
m.def("ngram_hash_cpu", &ngram_hash_cpu, "ngram_hash_cpu");
m.def("ngram_gather_cpu", &ngram_gather_cpu, "ngram_gather_cpu");
@@ -322,12 +395,17 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
m.def("exl3_moe_max_concurrency", &exl3_moe_max_concurrency, "exl3_moe_max_concurrency");
m.def("exl3_moe", &exl3_moe, "exl3_moe");
m.def("exl3_moe_gather", &exl3_moe_gather, "exl3_moe_gather");
+ m.def("exl3_moe_grouped", &exl3_moe_grouped, "exl3_moe_grouped");
+ m.def("exl3_moe_grouped_supported", &exl3_moe_grouped_supported, "exl3_moe_grouped_supported");
m.def("exl3_moe_coop", &exl3_moe_coop, "exl3_moe_coop");
m.def("bighead_attn", &bighead_attn, "bighead_attn");
m.def("bighead_attn_paged", &bighead_attn_paged, "bighead_attn_paged");
m.def("bighead_attn_workspace_size", &bighead_attn_workspace_size, "bighead_attn_workspace_size");
+#if defined(EXL3_PORT_DEC)
+ if (const char* e = getenv("EXL3_PORT_DEC"); e && atoi(e) > 0) bind_exl3_dec(m);
+#endif
#include "libtorch/linear_bc.h"
#include "libtorch/gated_delta_net_bc.h"
#include "libtorch/attention_bc.h"
@@ -376,59 +454,7 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
m.def("exl3_moe_fused_tile_test", &exl3_moe_fused_tile_test, "exl3_moe_fused_tile_test");
m.def("exl3_gemv_int8_max_k", &exl3_gemv_int8_max_k, "exl3_gemv_int8_max_k");
m.def("exl3_moe_gfx12_k3", &exl3_moe_gfx12_k3, "exl3_moe_gfx12_k3");
- m.def("exl3_dec_gemv", &exl3_dec_gemv, "exl3_dec_gemv",
- py::arg("x"), py::arg("trellis"), py::arg("suh"), py::arg("svh"), py::arg("out"),
- py::arg("scratch"), py::arg("counters"), py::arg("K"), py::arg("mcg") = false);
- m.def("exl3_dec_gemv_multi", &exl3_dec_gemv_multi, "exl3_dec_gemv_multi",
- py::arg("x"), py::arg("trellis"), py::arg("suh"), py::arg("svh"), py::arg("out"),
- py::arg("scratch"), py::arg("counters"), py::arg("K"), py::arg("mcg") = false);
- m.def("exl3_dec_gemv_x", &exl3_dec_gemv_x, "exl3_dec_gemv_x",
- py::arg("x"), py::arg("trellis"), py::arg("suh"), py::arg("svh"), py::arg("out"),
- py::arg("scratch"), py::arg("counters"), py::arg("K"), py::arg("mcg") = false,
- py::arg("x_job_stride") = 0, py::arg("strips_hint") = 0);
- m.def("exl3_dec_moe", &exl3_dec_moe, "exl3_dec_moe",
- py::arg("x"), py::arg("out"), py::arg("selected"), py::arg("weights"),
- py::arg("gate_trellis"), py::arg("gate_suh"), py::arg("gate_svh"),
- py::arg("up_trellis"), py::arg("up_suh"), py::arg("up_svh"),
- py::arg("down_trellis"), py::arg("down_suh"), py::arg("down_svh"),
- py::arg("act"), py::arg("scratch"), py::arg("counters"),
- py::arg("intermediate"), py::arg("K_gu"), py::arg("K_down"),
- py::arg("accumulate"), py::arg("act_limit") = 0.0, py::arg("mcg") = false);
- m.def("exl3_dec_moe_shared", &exl3_dec_moe_shared, "exl3_dec_moe_shared",
- py::arg("x"), py::arg("out"), py::arg("selected"), py::arg("weights"),
- py::arg("gate_trellis"), py::arg("gate_suh"), py::arg("gate_svh"),
- py::arg("up_trellis"), py::arg("up_suh"), py::arg("up_svh"),
- py::arg("down_trellis"), py::arg("down_suh"), py::arg("down_svh"),
- py::arg("sh_gate_trellis"), py::arg("sh_gate_suh"), py::arg("sh_gate_svh"),
- py::arg("sh_up_trellis"), py::arg("sh_up_suh"), py::arg("sh_up_svh"),
- py::arg("sh_down_trellis"), py::arg("sh_down_suh"), py::arg("sh_down_svh"),
- py::arg("act"), py::arg("scratch"), py::arg("counters"),
- py::arg("intermediate"), py::arg("K_gu"), py::arg("K_down"),
- py::arg("K_sh_gu"), py::arg("K_sh_down"),
- py::arg("accumulate"), py::arg("act_limit") = 0.0, py::arg("mcg") = false);
- m.def("exl3_dec_moe_union", &exl3_dec_moe_union, "exl3_dec_moe_union",
- py::arg("x"), py::arg("out"), py::arg("selected"), py::arg("weights"),
- py::arg("gate_trellis"), py::arg("gate_suh"), py::arg("gate_svh"),
- py::arg("up_trellis"), py::arg("up_suh"), py::arg("up_svh"),
- py::arg("down_trellis"), py::arg("down_suh"), py::arg("down_svh"),
- py::arg("act"), py::arg("down_part"), py::arg("scratch"), py::arg("counters"),
- py::arg("intermediate"), py::arg("K_gu"), py::arg("K_down"),
- py::arg("accumulate"), py::arg("act_limit") = 0.0, py::arg("mcg") = false,
- py::arg("device_table") = false);
- m.def("exl3_dec_gemv_strided", &exl3_dec_gemv_strided, "exl3_dec_gemv_strided",
- py::arg("x"), py::arg("trellis"), py::arg("suh"), py::arg("svh"), py::arg("out"),
- py::arg("scratch"), py::arg("counters"), py::arg("K"), py::arg("in_features"),
- py::arg("x_gstride"), py::arg("mcg") = false);
- m.def("exl3_dec_gemv_r", &exl3_dec_gemv_r, "exl3_dec_gemv_r",
- py::arg("x"), py::arg("trellis"), py::arg("suh"), py::arg("svh"), py::arg("out"),
- py::arg("scratch"), py::arg("counters"), py::arg("K"), py::arg("mcg") = false);
- m.def("exl3_dec_gemv_r_multi", &exl3_dec_gemv_r_multi, "exl3_dec_gemv_r_multi",
- py::arg("x"), py::arg("trellis"), py::arg("suh"), py::arg("svh"), py::arg("out"),
- py::arg("scratch"), py::arg("counters"), py::arg("K"), py::arg("mcg") = false);
- m.def("exl3_dec_router_norm", &exl3_dec_router_norm, "exl3_dec_router_norm");
- m.def("exl3_dec_router", &exl3_dec_router, "exl3_dec_router");
- m.def("exl3_dec_router_rows", &exl3_dec_router_rows, "exl3_dec_router_rows");
- m.def("exl3_dec_rms_norm", &exl3_dec_rms_norm, "exl3_dec_rms_norm");
+ bind_exl3_dec(m);
m.def("fused_gated_rms_norm", &fused_gated_rms_norm, "fused_gated_rms_norm");
m.def("mul_sigmoid_pad", &mul_sigmoid_pad, "mul_sigmoid_pad");
m.def("pad_copy", &pad_copy, "pad_copy");
@@ -526,4 +552,82 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
m.def("ngram_gather_cpu", &ngram_gather_cpu, "ngram_gather_cpu");
m.def("ngram_dequant", &ngram_dequant, "ngram_dequant");
#endif
+
+#if !defined(USE_ROCM)
+ // Foreign-quant kernels (foreign_quant/*.cu): CUDA builds only (the ROCm build does not compile them).
+ // No env switch: they are additive (nothing upstream is replaced); Python falls back to torch when the ext
+ // predates them.
+ m.def("fq_dequant_q8_0", &fq_dequant_q8_0, "fq_dequant_q8_0",
+ py::arg("packed"), py::arg("out"));
+ m.def("fq_dequant_iq2_xxs", &fq_dequant_iq2_xxs, "fq_dequant_iq2_xxs",
+ py::arg("packed"), py::arg("out"));
+ m.def("fq_dequant_nvfp4", &fq_dequant_nvfp4, "fq_dequant_nvfp4",
+ py::arg("packed"), py::arg("scales"), py::arg("global_scale"), py::arg("out"));
+ m.def("fq_dequant_q4_k", &fq_dequant_q4_k, "fq_dequant_q4_k",
+ py::arg("packed"), py::arg("out"));
+ m.def("fq_dequant_q5_k", &fq_dequant_q5_k, "fq_dequant_q5_k",
+ py::arg("packed"), py::arg("out"));
+ m.def("fq_dequant_q6_k", &fq_dequant_q6_k, "fq_dequant_q6_k",
+ py::arg("packed"), py::arg("out"));
+ m.def("fq_dequant_iq4_xs", &fq_dequant_iq4_xs, "fq_dequant_iq4_xs",
+ py::arg("packed"), py::arg("out"));
+ m.def("fq_gemm_q8_0", &fq_gemm_q8_0, "fq_gemm_q8_0",
+ py::arg("x"), py::arg("packed"), py::arg("out"));
+ m.def("fq_gemm_iq2_xxs", &fq_gemm_iq2_xxs, "fq_gemm_iq2_xxs",
+ py::arg("x"), py::arg("packed"), py::arg("out"));
+ m.def("fq_gemm_nvfp4", &fq_gemm_nvfp4, "fq_gemm_nvfp4",
+ py::arg("x"), py::arg("packed"), py::arg("scales"), py::arg("global_scale"), py::arg("out"));
+ m.def("fq_gemv_q8_0", &fq_gemv_q8_0, "fq_gemv_q8_0",
+ py::arg("x"), py::arg("packed"), py::arg("out"));
+ m.def("fq_gemv_iq2_xxs", &fq_gemv_iq2_xxs, "fq_gemv_iq2_xxs",
+ py::arg("x"), py::arg("packed"), py::arg("out"));
+ m.def("fq_gemv_nvfp4", &fq_gemv_nvfp4, "fq_gemv_nvfp4",
+ py::arg("x"), py::arg("packed"), py::arg("scales"), py::arg("global_scale"), py::arg("out"),
+ py::arg("pair") = true);
+ m.def("fq_moe_iq2xxs_grouped", &fq_moe_iq2xxs_grouped, "fq_moe_iq2xxs_grouped",
+ py::arg("h"), py::arg("sel"), py::arg("wts"),
+ py::arg("up_ptrs"), py::arg("down_ptrs"),
+ py::arg("up_stride"), py::arg("down_stride"),
+ py::arg("partial"), py::arg("out"));
+ m.def("fq_mlp_shared_iq2xxs", &fq_mlp_shared_iq2xxs, "fq_mlp_shared_iq2xxs",
+ py::arg("x"), py::arg("up_packed"), py::arg("h"));
+ m.def("fq_q8_scratch", &fq_q8_scratch, "fq_q8_scratch",
+ py::arg("dev"), py::arg("M"), py::arg("K"));
+ m.def("fq_quant_q8_1_rows", &fq_quant_q8_1_rows, "fq_quant_q8_1_rows",
+ py::arg("x"), py::arg("qb"));
+ m.def("fq_gemv_iq2_xxs_q8", &fq_gemv_iq2_xxs_q8, "fq_gemv_iq2_xxs_q8",
+ py::arg("qb"), py::arg("packed"), py::arg("out"));
+ m.def("fq_gemv_nvfp4_q8", &fq_gemv_nvfp4_q8, "fq_gemv_nvfp4_q8",
+ py::arg("qb"), py::arg("packed"), py::arg("scales"), py::arg("global_scale"), py::arg("out"));
+ m.def("fq_gemv_q8_0_q8", &fq_gemv_q8_0_q8, "fq_gemv_q8_0_q8",
+ py::arg("qb"), py::arg("packed"), py::arg("out"));
+ m.def("fq_gemv_q4_k_q8", &fq_gemv_q4_k_q8, "fq_gemv_q4_k_q8",
+ py::arg("qb"), py::arg("packed"), py::arg("out"));
+ m.def("fq_gemv_q5_k_q8", &fq_gemv_q5_k_q8, "fq_gemv_q5_k_q8",
+ py::arg("qb"), py::arg("packed"), py::arg("out"));
+ m.def("fq_gemv_q6_k_q8", &fq_gemv_q6_k_q8, "fq_gemv_q6_k_q8",
+ py::arg("qb"), py::arg("packed"), py::arg("out"));
+ m.def("fq_gemv_iq4_xs_q8", &fq_gemv_iq4_xs_q8, "fq_gemv_iq4_xs_q8",
+ py::arg("qb"), py::arg("packed"), py::arg("out"));
+ m.def("fq_moe_q4k_grouped_q8", &fq_moe_q4k_grouped_q8, "fq_moe_q4k_grouped_q8",
+ py::arg("h"), py::arg("sel"), py::arg("wts"),
+ py::arg("gate_ptrs"), py::arg("up_ptrs"), py::arg("down_ptrs"),
+ py::arg("gate_stride"), py::arg("up_stride"), py::arg("down_stride"),
+ py::arg("partial"), py::arg("out"));
+ m.def("fq_moe_q5k_grouped_q8", &fq_moe_q5k_grouped_q8, "fq_moe_q5k_grouped_q8",
+ py::arg("h"), py::arg("sel"), py::arg("wts"),
+ py::arg("gate_ptrs"), py::arg("up_ptrs"), py::arg("down_ptrs"),
+ py::arg("gate_stride"), py::arg("up_stride"), py::arg("down_stride"),
+ py::arg("partial"), py::arg("out"));
+ m.def("fq_moe_q6k_grouped_q8", &fq_moe_q6k_grouped_q8, "fq_moe_q6k_grouped_q8",
+ py::arg("h"), py::arg("sel"), py::arg("wts"),
+ py::arg("gate_ptrs"), py::arg("up_ptrs"), py::arg("down_ptrs"),
+ py::arg("gate_stride"), py::arg("up_stride"), py::arg("down_stride"),
+ py::arg("partial"), py::arg("out"));
+ m.def("fq_moe_iq4xs_grouped_q8", &fq_moe_iq4xs_grouped_q8, "fq_moe_iq4xs_grouped_q8",
+ py::arg("h"), py::arg("sel"), py::arg("wts"),
+ py::arg("gate_ptrs"), py::arg("up_ptrs"), py::arg("down_ptrs"),
+ py::arg("gate_stride"), py::arg("up_stride"), py::arg("down_stride"),
+ py::arg("partial"), py::arg("out"));
+#endif
}
diff --git a/exllamav3/exllamav3_ext/build_config.py b/exllamav3/exllamav3_ext/build_config.py
index 571e8c2..8b4430a 100644
--- a/exllamav3/exllamav3_ext/build_config.py
+++ b/exllamav3/exllamav3_ext/build_config.py
@@ -5,7 +5,7 @@ the ROCm source exclusion logic.
"""
import os
-ROCM_EXCLUDE_DIRS = {'parallel', 'comp_units'}
+ROCM_EXCLUDE_DIRS = {'parallel', 'comp_units', 'foreign_quant'}
# Files inside an excluded dir that DO build on ROCm (checked before the dir exclusion). The int8
# GEMV instances and EXL3 tile-quantizer K1..K8 instances are required by the HIP runtime/converter.
@@ -20,14 +20,14 @@ ROCM_EXCLUDE_FILES = {
'softcap.cu', 'histogram.cu', 'sam.cpp',
'cache/q_cache.cu',
'quant/exl3_gemm.cu',
- 'quant/exl3_moe.cu', 'quant/exl3_moe_coop.cu', 'quant/exl3_kernel_map.cu',
+ 'quant/exl3_moe.cu', 'quant/exl3_moe_grouped.cu', 'quant/exl3_moe_coop.cu', 'quant/exl3_kernel_map.cu',
'quant/coop_autotune.cu',
'generator/sampling_fused.cu',
'libtorch/gated_delta_net.cpp', 'libtorch/blocksparse_mlp.cpp',
'libtorch/mlp.cpp', 'libtorch/attention.cpp', 'libtorch/gated_rmsnorm.cpp',
'libtorch/linear.cpp', 'libtorch/dsv4_attn.cpp', 'libtorch/dsv4_compressor.cpp',
'libtorch/mla_attention.cpp',
- 'dsv4_compress.cu', 'dsa_topk.cu', 'ple.cu',
+ 'dsv4_compress.cu', 'dsa_topk.cu', 'ple.cu', 'dflash2.cu',
'cpu/moe_handoff.cu',
}
diff --git a/exllamav3/exllamav3_ext/dflash2.cu b/exllamav3/exllamav3_ext/dflash2.cu
new file mode 100644
index 0000000..6e9da7d
--- /dev/null
+++ b/exllamav3/exllamav3_ext/dflash2.cu
@@ -0,0 +1,550 @@
+// ported from exllamav3 1.6.0, MIT, (c) turboderp
+#include <cuda_fp16.h>
+#include <cuda_bf16.h>
+#include "dflash2.cuh"
+#include <ATen/ATen.h>
+#include <c10/cuda/CUDAGuard.h>
+#include <ATen/cuda/CUDAContext.h>
+#include "util.h"
+#include "util.cuh"
+
+// DFlash2 grouped dynamic causal convolution over a draft block (dflash.model
+// _grouped_dynamic_convolve):
+//
+// out[b, t, c] = sum_k (base[k, c] + dyn[b, t, k, c / group_size]) * x[b, t - k, c]
+//
+// Taps reach back within the block only (t - k < 0 contributes nothing), so the kernel is
+// stateless across rounds. dyn is the kernel projection's output viewed as [b, l, K, groups]
+// with arbitrary strides (the projection emits both the prepare and the finish deltas in one
+// tensor). accumulate: out (fp32 residual stream) += conv(x), fusing the block's residual add
+// into the finish() variant; otherwise out = conv(x)
+
+#define NUM_THREADS 256
+
+template <typename T> __device__ __forceinline__ float to_f(T v) { return (float) v; }
+template <> __device__ __forceinline__ float to_f(half v) { return __half2float(v); }
+template <> __device__ __forceinline__ float to_f(__nv_bfloat16 v) { return __bfloat162float(v); }
+template <typename T> __device__ __forceinline__ T from_f(float v) { return (T) v; }
+template <> __device__ __forceinline__ half from_f(float v) { return __float2half(v); }
+
+template <typename TX, typename TB, typename TO, bool accumulate>
+__global__ __launch_bounds__(NUM_THREADS)
+void dflash2_dynconv_kernel
+(
+ const TX* __restrict__ x,
+ const half* __restrict__ dyn,
+ const TB* __restrict__ base,
+ TO* __restrict__ out,
+ const int seqlen,
+ const int hidden,
+ const int group_size,
+ const int taps,
+ const int64_t ds_b,
+ const int64_t ds_t,
+ const int64_t ds_k,
+ const int64_t ds_g
+)
+{
+ int c = blockIdx.x * NUM_THREADS + threadIdx.x;
+ if (c >= hidden) return;
+ int t = blockIdx.y;
+ int b = blockIdx.z;
+ int g = c / group_size;
+
+ const half* dyn_bt = dyn + b * ds_b + t * ds_t + g * ds_g;
+ const TX* x_bt = x + ((int64_t) b * seqlen + t) * hidden + c;
+
+ float acc = 0.0f;
+ #pragma unroll 4
+ for (int k = 0; k < taps; ++k)
+ {
+ if (k > t) break;
+ float w = to_f(base[k * hidden + c]) + __half2float(dyn_bt[k * ds_k]);
+ acc += w * to_f(x_bt[-(int64_t) k * hidden]);
+ }
+
+ TO* o = out + ((int64_t) b * seqlen + t) * hidden + c;
+ if constexpr (accumulate)
+ *o = from_f<TO>(to_f(*o) + acc);
+ else
+ *o = from_f<TO>(acc);
+}
+
+template <typename TX, typename TB, typename TO, bool accumulate>
+void launch
+(
+ const at::Tensor& x, const at::Tensor& dyn, const at::Tensor& base, at::Tensor& out,
+ int seqlen, int hidden, int group_size, int taps, int bsz, cudaStream_t stream
+)
+{
+ dim3 grid(CEIL_DIVIDE(hidden, NUM_THREADS), seqlen, bsz);
+ dflash2_dynconv_kernel<TX, TB, TO, accumulate><<<grid, NUM_THREADS, 0, stream>>>
+ (
+ (const TX*) x.data_ptr(),
+ (const half*) dyn.data_ptr(),
+ (const TB*) base.data_ptr(),
+ (TO*) out.data_ptr(),
+ seqlen, hidden, group_size, taps,
+ dyn.stride(0), dyn.stride(1), dyn.stride(2), dyn.stride(3)
+ );
+}
+
+/*
+x: (bsz, seqlen, hidden), fp16 or fp32, contiguous
+dyn: (bsz, seqlen, taps, hidden / group_size), fp16, any strides
+base: (taps, hidden), fp16 or bf16, contiguous
+out: (bsz, seqlen, hidden), fp16 or fp32, contiguous; accumulated into when accumulate
+*/
+
+void dflash2_dynconv
+(
+ const at::Tensor& x,
+ const at::Tensor& dyn,
+ const at::Tensor& base,
+ at::Tensor& out,
+ int64_t group_size,
+ bool accumulate
+)
+{
+ const at::cuda::OptionalCUDAGuard device_guard(x.device());
+ cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream();
+
+ TORCH_CHECK_DIM(x, 3);
+ TORCH_CHECK_DIM(dyn, 4);
+ TORCH_CHECK_DIM(base, 2);
+ TORCH_CHECK(x.is_contiguous() && out.is_contiguous() && base.is_contiguous(), "dflash2_dynconv: x, out and base must be contiguous");
+ TORCH_CHECK_SHAPES_FULL(x, out);
+ TORCH_CHECK_DTYPE(dyn, kHalf);
+ TORCH_CHECK(x.dtype() == at::kHalf || x.dtype() == at::kFloat, "dflash2_dynconv: x must be fp16 or fp32");
+ TORCH_CHECK(out.dtype() == at::kHalf || out.dtype() == at::kFloat, "dflash2_dynconv: out must be fp16 or fp32");
+ TORCH_CHECK(base.dtype() == at::kHalf || base.dtype() == at::kBFloat16, "dflash2_dynconv: base must be fp16 or bf16");
+ TORCH_CHECK(!accumulate || out.dtype() == at::kFloat, "dflash2_dynconv: accumulate needs an fp32 residual");
+
+ int bsz = x.size(0);
+ int seqlen = x.size(1);
+ int hidden = x.size(2);
+ int taps = base.size(0);
+ TORCH_CHECK(group_size > 0 && hidden % group_size == 0, "dflash2_dynconv: hidden must be a multiple of group_size");
+ TORCH_CHECK(base.size(1) == hidden, "dflash2_dynconv: base width mismatch");
+ TORCH_CHECK(dyn.size(0) == bsz && dyn.size(1) == seqlen && dyn.size(2) == taps && dyn.size(3) == hidden / group_size,
+ "dflash2_dynconv: dyn must be (bsz, seqlen, taps, hidden / group_size)");
+ if (!bsz || !seqlen || !hidden) return;
+
+ #define DISPATCH(TX, TB, TO) \
+ if (accumulate) launch<TX, TB, TO, true>(x, dyn, base, out, seqlen, hidden, (int) group_size, taps, bsz, stream); \
+ else launch<TX, TB, TO, false>(x, dyn, base, out, seqlen, hidden, (int) group_size, taps, bsz, stream);
+ #define DISPATCH_TO(TX, TB) \
+ if (out.dtype() == at::kHalf) { DISPATCH(TX, TB, half) } else { DISPATCH(TX, TB, float) }
+ #define DISPATCH_TB(TX) \
+ if (base.dtype() == at::kHalf) { DISPATCH_TO(TX, half) } else { DISPATCH_TO(TX, __nv_bfloat16) }
+
+ if (x.dtype() == at::kHalf) { DISPATCH_TB(half) } else { DISPATCH_TB(float) }
+
+ #undef DISPATCH_TB
+ #undef DISPATCH_TO
+ #undef DISPATCH
+ cuda_check(cudaPeekAtLastError());
+}
+
+
+// DFlash2 candidate selector walk (dflash.model CandidateSelector, greedy). Per batch row, over
+// the block's draft rows i = 0..rows-1, conditioned on the previously chosen token a (the
+// verified anchor for row 0):
+//
+// score[c] = unary[i, c] + < A[a] * gate[i], B[cands[i, c]] > (dot over rank)
+// a = cands[i, argmax_c score[c]] (first max on ties)
+//
+// One block per batch row runs the whole chain: the per-row work (k dots of length rank) is far
+// too small to spread over the grid, and keeping it in one block removes the per-row host round
+// trip and the ~6 launches per row of the torch formulation. out[:, 0] gets the anchor and
+// out[:, 1:] the path, matching the module's [anchor, path...] layout; conf (optional) gets the
+// winning score per row with a leading zero
+
+#define WALK_THREADS 256
+
+template <typename TG, typename TC>
+__global__ __launch_bounds__(WALK_THREADS)
+void dflash2_selector_walk_kernel
+(
+ const float* __restrict__ unary, // [bsz, rows, k]
+ const int64_t* __restrict__ cands, // [bsz, rows, k]
+ const TG* __restrict__ gate, // [bsz, rows, rank]
+ const TC* __restrict__ pred_cb, // [vocab, rank]
+ const TC* __restrict__ succ_cb, // [vocab, rank]
+ const int64_t* __restrict__ anchor, // [bsz]
+ int64_t* __restrict__ out, // [bsz, rows + 1]
+ float* __restrict__ conf, // [bsz, rows + 1] or nullptr
+ const int rows,
+ const int k,
+ const int rank
+)
+{
+ extern __shared__ float smem[];
+ float* a_g = smem; // [rank]: A[pred] * gate[i]
+ float* scores = smem + rank; // [k]
+ __shared__ int64_t s_pred;
+
+ const int b = blockIdx.x;
+ const int t = threadIdx.x;
+ const int warp = t / 32, lane = t % 32;
+
+ if (t == 0)
+ {
+ s_pred = anchor[b];
+ out[(int64_t) b * (rows + 1)] = s_pred;
+ if (conf) conf[(int64_t) b * (rows + 1)] = 0.0f;
+ }
+ __syncthreads();
+
+ for (int i = 0; i < rows; ++i)
+ {
+ const int64_t pred = s_pred;
+ const TC* a_row = pred_cb + pred * rank;
+ const TG* g_row = gate + ((int64_t) b * rows + i) * rank;
+ for (int r = t; r < rank; r += WALK_THREADS)
+ a_g[r] = to_f(a_row[r]) * to_f(g_row[r]);
+ __syncthreads();
+
+ const int64_t* c_row = cands + ((int64_t) b * rows + i) * k;
+ const float* u_row = unary + ((int64_t) b * rows + i) * k;
+ for (int c = warp; c < k; c += WALK_THREADS / 32)
+ {
+ const TC* b_row = succ_cb + c_row[c] * rank;
+ float dot = 0.0f;
+ for (int r = lane; r < rank; r += 32)
+ dot += a_g[r] * to_f(b_row[r]);
+ for (int offset = 16; offset > 0; offset /= 2)
+ dot += __shfl_xor_sync(0xffffffff, dot, offset);
+ if (lane == 0) scores[c] = u_row[c] + dot;
+ }
+ __syncthreads();
+
+ if (t == 0)
+ {
+ int best = 0;
+ float best_score = scores[0];
+ for (int c = 1; c < k; ++c)
+ if (scores[c] > best_score) { best_score = scores[c]; best = c; }
+ s_pred = c_row[best];
+ out[(int64_t) b * (rows + 1) + i + 1] = s_pred;
+ if (conf) conf[(int64_t) b * (rows + 1) + i + 1] = best_score;
+ }
+ __syncthreads();
+ }
+}
+
+/*
+unary: (bsz, rows, k) fp32 top-k draft logits per row, contiguous
+cands: (bsz, rows, k) int64 token ids of those logits, contiguous
+gate: (bsz, rows, rank) fp16 or fp32 projected draft states, contiguous
+pred_cb, succ_cb: (vocab, rank) fp16 or bf16 codebooks, contiguous (same dtype)
+anchor: (bsz,) int64 verified anchor token per row
+out: (bsz, rows + 1) int64 -> [anchor, path...]
+conf: (bsz, rows + 1) fp32 -> [0, winning score...] (optional)
+*/
+
+void dflash2_selector_walk
+(
+ const at::Tensor& unary,
+ const at::Tensor& cands,
+ const at::Tensor& gate,
+ const at::Tensor& pred_cb,
+ const at::Tensor& succ_cb,
+ const at::Tensor& anchor,
+ at::Tensor& out,
+ const c10::optional<at::Tensor>& conf
+)
+{
+ const at::cuda::OptionalCUDAGuard device_guard(unary.device());
+ cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream();
+
+ TORCH_CHECK_DIM(unary, 3);
+ TORCH_CHECK_DIM(cands, 3);
+ TORCH_CHECK_DIM(gate, 3);
+ TORCH_CHECK_DIM(pred_cb, 2);
+ TORCH_CHECK_DIM(succ_cb, 2);
+ TORCH_CHECK_DIM(anchor, 1);
+ TORCH_CHECK_DIM(out, 2);
+ TORCH_CHECK_DTYPE(unary, kFloat);
+ TORCH_CHECK_DTYPE(cands, kLong);
+ TORCH_CHECK_DTYPE(anchor, kLong);
+ TORCH_CHECK_DTYPE(out, kLong);
+ TORCH_CHECK_DTYPE_OPT(conf, kFloat);
+ TORCH_CHECK(gate.dtype() == at::kHalf || gate.dtype() == at::kFloat, "dflash2_selector_walk: gate must be fp16 or fp32");
+ TORCH_CHECK(pred_cb.dtype() == succ_cb.dtype() && (pred_cb.dtype() == at::kHalf || pred_cb.dtype() == at::kBFloat16),
+ "dflash2_selector_walk: codebooks must both be fp16 or both bf16");
+ TORCH_CHECK(unary.is_contiguous() && cands.is_contiguous() && gate.is_contiguous() && pred_cb.is_contiguous() &&
+ succ_cb.is_contiguous() && anchor.is_contiguous() && out.is_contiguous(), "dflash2_selector_walk: inputs must be contiguous");
+
+ int bsz = unary.size(0);
+ int rows = unary.size(1);
+ int k = unary.size(2);
+ int rank = gate.size(2);
+ TORCH_CHECK_SHAPES_FULL(unary, cands);
+ TORCH_CHECK(gate.size(0) == bsz && gate.size(1) == rows, "dflash2_selector_walk: gate must be (bsz, rows, rank)");
+ TORCH_CHECK(pred_cb.size(1) == rank && succ_cb.sizes() == pred_cb.sizes(), "dflash2_selector_walk: codebooks must be (vocab, rank)");
+ TORCH_CHECK(anchor.size(0) == bsz, "dflash2_selector_walk: anchor must be (bsz,)");
+ TORCH_CHECK(out.size(0) == bsz && out.size(1) == rows + 1, "dflash2_selector_walk: out must be (bsz, rows + 1)");
+ TORCH_CHECK(!conf.has_value() || (conf.value().is_contiguous() && conf.value().sizes() == out.sizes()),
+ "dflash2_selector_walk: conf must be (bsz, rows + 1), contiguous");
+ TORCH_CHECK(k >= 1 && rank >= 1, "dflash2_selector_walk: empty candidate list or rank");
+ if (!bsz || !rows) return;
+
+ size_t smem = (rank + k) * sizeof(float);
+ float* conf_ptr = conf.has_value() ? (float*) conf.value().data_ptr() : nullptr;
+
+ #define LAUNCH(TG, TC) \
+ dflash2_selector_walk_kernel<TG, TC><<<bsz, WALK_THREADS, smem, stream>>> \
+ ( \
+ (const float*) unary.data_ptr(), (const int64_t*) cands.data_ptr(), (const TG*) gate.data_ptr(), \
+ (const TC*) pred_cb.data_ptr(), (const TC*) succ_cb.data_ptr(), (const int64_t*) anchor.data_ptr(), \
+ (int64_t*) out.data_ptr(), conf_ptr, rows, k, rank \
+ );
+ if (gate.dtype() == at::kHalf) { if (pred_cb.dtype() == at::kHalf) { LAUNCH(half, half) } else { LAUNCH(half, __nv_bfloat16) } }
+ else { if (pred_cb.dtype() == at::kHalf) { LAUNCH(float, half) } else { LAUNCH(float, __nv_bfloat16) } }
+ #undef LAUNCH
+ cuda_check(cudaPeekAtLastError());
+}
+
+
+// Top-k over the draft block's logits for the selector, one launch for all rows (torch.topk
+// spends ~18 launches on its radix select). Each row is split over blocks of 256 threads x E
+// elements; every thread holds its E elements in registers and tracks its running maximum,
+// and a warp produces its top-K in K rounds of warp argmax where only the winning lane drops
+// its element and rescans (E predicated compares). Warp 0 merges the 8 warp lists the same
+// way, and the last-arriving block of a row merges the block partials. Per-thread sorted lists
+// were tried first and cost ~4x the instructions (a 16-deep shift per insert). scale and
+// softcap (Gemma-class heads) are applied on the fly: both are monotonic, so the selection
+// equals transforming the whole row first, and only the kept values transform. Output order is
+// descending; ties resolve to the lowest lane / earliest element
+
+#define TOPK_THREADS 256
+
+// x[N] per lane, ids id[N]; K rounds; lane 0 writes round k's winner to out_v[k] / out_ix[k].
+// Consumes the lanes' elements (winners are replaced by -inf)
+template <int N, int K>
+__device__ __forceinline__ void warp_topk(float (&x)[N], int (&id)[N], float* out_v, int* out_ix)
+{
+ const int lane = threadIdx.x % 32;
+ float cur = -INFINITY; int arg = 0;
+ #pragma unroll
+ for (int i = 0; i < N; ++i) if (x[i] > cur) { cur = x[i]; arg = i; }
+ for (int k = 0; k < K; ++k)
+ {
+ float best = cur; int best_lane = lane;
+ for (int offset = 16; offset > 0; offset /= 2)
+ {
+ float o_best = __shfl_xor_sync(0xffffffff, best, offset);
+ int o_lane = __shfl_xor_sync(0xffffffff, best_lane, offset);
+ if (o_best > best || (o_best == best && o_lane < best_lane)) { best = o_best; best_lane = o_lane; }
+ }
+ int best_id = -1;
+ #pragma unroll
+ for (int i = 0; i < N; ++i) if (i == arg) best_id = id[i];
+ best_id = __shfl_sync(0xffffffff, best_id, best_lane);
+ if (lane == 0) { out_v[k] = best; out_ix[k] = best_id; }
+ if (lane == best_lane)
+ {
+ #pragma unroll
+ for (int i = 0; i < N; ++i) if (i == arg) x[i] = -INFINITY;
+ cur = -INFINITY; arg = 0;
+ #pragma unroll
+ for (int i = 0; i < N; ++i) if (x[i] > cur) { cur = x[i]; arg = i; }
+ }
+ }
+}
+
+// Block top-K: warp lists into shared memory, warp 0 merges them (8 * K entries, K / 4 per
+// lane). Two barriers
+template <int N, int K>
+__device__ __forceinline__ void block_topk(float (&x)[N], int (&id)[N], float* out_v, int* out_ix, float* s_wv, int* s_wix)
+{
+ constexpr int M = K / 4; // (TOPK_THREADS / 32) * K / 32 entries per lane in the second stage
+ const int t = threadIdx.x, warp = t / 32, lane = t % 32;
+ warp_topk<N, K>(x, id, s_wv + warp * K, s_wix + warp * K);
+ __syncthreads();
+ if (warp == 0)
+ {
+ float y[M]; int yid[M];
+ #pragma unroll
+ for (int i = 0; i < M; ++i) { y[i] = s_wv[lane * M + i]; yid[i] = s_wix[lane * M + i]; }
+ warp_topk<M, K>(y, yid, out_v, out_ix);
+ }
+ __syncthreads();
+}
+
+template <typename T, int K, int E>
+__global__ __launch_bounds__(TOPK_THREADS)
+void dflash2_topk_kernel
+(
+ const T* __restrict__ logits,
+ const int64_t stride_b,
+ const int64_t stride_r,
+ const int rows,
+ const int splits,
+ const int vocab,
+ const float scale,
+ const float softcap,
+ float* __restrict__ part_v, // [bsz * rows, splits, K] scratch
+ int* __restrict__ part_ix, // [bsz * rows, splits, K] scratch
+ int* __restrict__ counters, // [bsz * rows], zero on entry, zero on exit
+ float* __restrict__ values, // [bsz, rows, K]
+ int64_t* __restrict__ indices // [bsz, rows, K]
+)
+{
+ constexpr int VEC = 16 / sizeof(T); // elements per 16-byte load
+ constexpr int LOADS = E / VEC; // vector loads per thread
+ constexpr int SPAN = TOPK_THREADS * VEC; // elements covered by one load across the block
+ static_assert(E % VEC == 0, "E must be a multiple of the vector width");
+
+ __shared__ float s_wv[(TOPK_THREADS / 32) * K];
+ __shared__ int s_wix[(TOPK_THREADS / 32) * K];
+ __shared__ bool s_last;
+
+ const int row_id = blockIdx.x / splits; // b * rows + r
+ const int split = blockIdx.x % splits;
+ const int b = row_id / rows, r = row_id % rows;
+ const int t = threadIdx.x;
+ const T* row = logits + b * stride_b + r * stride_r;
+ const int c0 = split * (TOPK_THREADS * E);
+
+ // This thread's E elements: LOADS coalesced 16-byte loads, each covering SPAN elements
+ // across the block. Out-of-range elements read as -inf
+ float x[E]; int id[E];
+ #pragma unroll
+ for (int l = 0; l < LOADS; ++l)
+ {
+ const int c = c0 + l * SPAN + t * VEC;
+ if (c + VEC <= vocab)
+ {
+ int4 raw = *((const int4*) (row + c));
+ const T* xs = (const T*) &raw;
+ #pragma unroll
+ for (int i = 0; i < VEC; ++i)
+ {
+ float xv = to_f(xs[i]) * scale;
+ if (softcap > 0.0f) xv = tanhf(xv / softcap) * softcap;
+ x[l * VEC + i] = xv; id[l * VEC + i] = c + i;
+ }
+ }
+ else
+ {
+ #pragma unroll
+ for (int i = 0; i < VEC; ++i)
+ {
+ float xv = -INFINITY;
+ if (c + i < vocab)
+ {
+ xv = to_f(row[c + i]) * scale;
+ if (softcap > 0.0f) xv = tanhf(xv / softcap) * softcap;
+ }
+ x[l * VEC + i] = xv; id[l * VEC + i] = c + i;
+ }
+ }
+ }
+
+ // Block partial -> scratch
+ float* pv = part_v + ((int64_t) row_id * splits + split) * K;
+ int* pix = part_ix + ((int64_t) row_id * splits + split) * K;
+ block_topk<E, K>(x, id, pv, pix, s_wv, s_wix);
+
+ // Last-arriving block of the row merges the partials (splits * K entries, M per thread)
+ __threadfence();
+ if (t == 0)
+ {
+ int arrived = atomicAdd(&counters[row_id], 1);
+ s_last = arrived == splits - 1;
+ }
+ __syncthreads();
+ if (!s_last) return;
+ __threadfence();
+
+ constexpr int M = K / 4; // holds splits * K entries when splits <= 64
+ float y[M]; int yid[M];
+ const float* rv = part_v + (int64_t) row_id * splits * K;
+ const int* rix = part_ix + (int64_t) row_id * splits * K;
+ #pragma unroll
+ for (int i = 0; i < M; ++i)
+ {
+ int j = t * M + i;
+ bool ok = j < splits * K;
+ y[i] = ok ? __ldcg(rv + j) : -INFINITY;
+ yid[i] = ok ? __ldcg(rix + j) : -1;
+ }
+ __shared__ float o_v[K];
+ __shared__ int o_ix[K];
+ block_topk<M, K>(y, yid, o_v, o_ix, s_wv, s_wix);
+ if (t < K)
+ {
+ int64_t o = (int64_t) row_id * K + t;
+ values[o] = o_v[t];
+ indices[o] = o_ix[t];
+ }
+ if (t == 0) counters[row_id] = 0;
+}
+
+/*
+logits: (bsz, rows, >= vocab) fp16 or fp32, unit stride along the vocab dim (views allowed)
+vocab: number of valid columns
+values: (bsz, rows, K) fp32, indices: (bsz, rows, K) int64; K in {8, 16, 32}
+*/
+
+void dflash2_topk
+(
+ const at::Tensor& logits,
+ int64_t vocab,
+ double scale,
+ double softcap,
+ at::Tensor& values,
+ at::Tensor& indices
+)
+{
+ const at::cuda::OptionalCUDAGuard device_guard(logits.device());
+ cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream();
+
+ TORCH_CHECK_DIM(logits, 3);
+ TORCH_CHECK_DIM(values, 3);
+ TORCH_CHECK_DIM(indices, 3);
+ TORCH_CHECK_DTYPE(values, kFloat);
+ TORCH_CHECK_DTYPE(indices, kLong);
+ TORCH_CHECK(logits.dtype() == at::kHalf || logits.dtype() == at::kFloat, "dflash2_topk: logits must be fp16 or fp32");
+ TORCH_CHECK(logits.stride(2) == 1, "dflash2_topk: logits must have unit stride along the vocab dim");
+ TORCH_CHECK(values.is_contiguous() && indices.is_contiguous(), "dflash2_topk: outputs must be contiguous");
+ TORCH_CHECK_SHAPES_FULL(values, indices);
+
+ int bsz = logits.size(0);
+ int rows = logits.size(1);
+ int k = values.size(2);
+ TORCH_CHECK(values.size(0) == bsz && values.size(1) == rows, "dflash2_topk: output shape mismatch");
+ TORCH_CHECK(vocab >= k && vocab <= logits.size(2), "dflash2_topk: vocab out of range");
+ TORCH_CHECK(k == 8 || k == 16 || k == 32, "dflash2_topk: k must be 8, 16 or 32");
+ if (!bsz || !rows) return;
+
+ // Elements per thread: 16 covers rows up to 64 splits * 4096 = 262144 columns (the final
+ // merge holds splits * K entries at K / 4 per thread), 32 up to 524288
+ int E = vocab <= 64 * TOPK_THREADS * 16 ? 16 : 32;
+ TORCH_CHECK(vocab <= 64 * TOPK_THREADS * 32, "dflash2_topk: vocab too large (max 524288)");
+ TORCH_CHECK(((uintptr_t) logits.data_ptr() & 15) == 0 && (logits.stride(0) * logits.element_size()) % 16 == 0 &&
+ (logits.stride(1) * logits.element_size()) % 16 == 0, "dflash2_topk: logits rows must be 16-byte aligned");
+ int splits = CEIL_DIVIDE(vocab, TOPK_THREADS * E);
+ int num_rows = bsz * rows;
+ auto opts_f = at::TensorOptions().dtype(at::kFloat).device(logits.device());
+ auto opts_i = at::TensorOptions().dtype(at::kInt).device(logits.device());
+ at::Tensor part_v = at::empty({(int64_t) num_rows * splits * k}, opts_f);
+ at::Tensor part_ix = at::empty({(int64_t) num_rows * splits * k}, opts_i);
+ at::Tensor counters = at::zeros({num_rows}, opts_i);
+
+ #define LAUNCH(T, K, E) \
+ dflash2_topk_kernel<T, K, E><<<num_rows * splits, TOPK_THREADS, 0, stream>>> \
+ ((const T*) logits.data_ptr(), logits.stride(0), logits.stride(1), rows, splits, (int) vocab, (float) scale, (float) softcap, \
+ (float*) part_v.data_ptr(), (int*) part_ix.data_ptr(), (int*) counters.data_ptr(), \
+ (float*) values.data_ptr(), (int64_t*) indices.data_ptr());
+ #define LAUNCH_E(T, K) if (E == 16) { LAUNCH(T, K, 16) } else { LAUNCH(T, K, 32) }
+ #define LAUNCH_K(T) \
+ if (k == 8) { LAUNCH_E(T, 8) } else if (k == 16) { LAUNCH_E(T, 16) } else { LAUNCH_E(T, 32) }
+ if (logits.dtype() == at::kHalf) { LAUNCH_K(half) } else { LAUNCH_K(float) }
+ #undef LAUNCH_K
+ #undef LAUNCH_E
+ #undef LAUNCH
+ cuda_check(cudaPeekAtLastError());
+}
diff --git a/exllamav3/exllamav3_ext/dflash2.cuh b/exllamav3/exllamav3_ext/dflash2.cuh
new file mode 100644
index 0000000..deb981e
--- /dev/null
+++ b/exllamav3/exllamav3_ext/dflash2.cuh
@@ -0,0 +1,36 @@
+// ported from exllamav3 1.6.0, MIT, (c) turboderp
+#pragma once
+
+#include <ATen/Tensor.h>
+
+void dflash2_dynconv
+(
+ const at::Tensor& x,
+ const at::Tensor& dyn,
+ const at::Tensor& base,
+ at::Tensor& out,
+ int64_t group_size,
+ bool accumulate
+);
+
+void dflash2_selector_walk
+(
+ const at::Tensor& unary,
+ const at::Tensor& cands,
+ const at::Tensor& gate,
+ const at::Tensor& pred_cb,
+ const at::Tensor& succ_cb,
+ const at::Tensor& anchor,
+ at::Tensor& out,
+ const c10::optional<at::Tensor>& conf
+);
+
+void dflash2_topk
+(
+ const at::Tensor& logits,
+ int64_t vocab,
+ double scale,
+ double softcap,
+ at::Tensor& values,
+ at::Tensor& indices
+);
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_api.h b/exllamav3/exllamav3_ext/foreign_quant/fq_api.h
new file mode 100644
index 0000000..11b0f41
--- /dev/null
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_api.h
@@ -0,0 +1,73 @@
+// Host entry points of the foreign-quant kernels (defined in fq_dequant.cu /
+// fq_gemm.cu, bound in bindings.cpp). Portable CUDA/HIP.
+#pragma once
+
+#include <torch/extension.h>
+
+void fq_dequant_q8_0(torch::Tensor packed, torch::Tensor out);
+void fq_dequant_iq2_xxs(torch::Tensor packed, torch::Tensor out);
+void fq_dequant_nvfp4(torch::Tensor packed, torch::Tensor scales, double global_scale, torch::Tensor out);
+void fq_gemm_q8_0(torch::Tensor x, torch::Tensor packed, torch::Tensor out);
+void fq_gemm_iq2_xxs(torch::Tensor x, torch::Tensor packed, torch::Tensor out);
+void fq_gemm_nvfp4(torch::Tensor x, torch::Tensor packed, torch::Tensor scales, double global_scale,
+ torch::Tensor out);
+void fq_gemv_q8_0(torch::Tensor x, torch::Tensor packed, torch::Tensor out);
+void fq_gemv_iq2_xxs(torch::Tensor x, torch::Tensor packed, torch::Tensor out);
+void fq_gemv_nvfp4(torch::Tensor x, torch::Tensor packed, torch::Tensor scales, double global_scale,
+ torch::Tensor out, bool pair = true);
+void fq_moe_iq2xxs_grouped(torch::Tensor h, torch::Tensor sel, torch::Tensor wts,
+ torch::Tensor up_ptrs, torch::Tensor down_ptrs,
+ int64_t up_stride, int64_t down_stride,
+ torch::Tensor partial, torch::Tensor out);
+void fq_mlp_shared_iq2xxs(torch::Tensor x, torch::Tensor up_packed, torch::Tensor h);
+// q8_1-activation path (fq_gemv_q8.cu): quantize + integer-dp4a dots.
+torch::Tensor fq_q8_scratch(int dev, int M, int K);
+void fq_quant_q8_1_rows(torch::Tensor x, torch::Tensor qb);
+void fq_gemv_iq2_xxs_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);
+void fq_gemv_nvfp4_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor scales,
+ double global_scale, torch::Tensor out);
+void fq_gemv_q8_0_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);
+// q8_1-activation grouped MoE (fq_moe_q8.cu), same args/contract as above.
+bool fq_use_q8moe();
+void fq_moe_iq2xxs_grouped_q8(torch::Tensor h, torch::Tensor sel, torch::Tensor wts,
+ torch::Tensor up_ptrs, torch::Tensor down_ptrs,
+ int64_t up_stride, int64_t down_stride,
+ torch::Tensor partial, torch::Tensor out);
+// Unfused dequant-to-fp16 for the K-quants + IQ4_XS (fq_dequant_kq.cu):
+// packed = raw GGUF bytes [N, Kb*bb] (bb = 144/176/210/136 B per
+// 256-block), out = fp16 [N, K] with K = Kb*256. Bitwise-identical to
+// dequant_row(blocks, fmt).astype(np.float16) in foreign_quant/k_quants.py.
+void fq_dequant_q4_k(torch::Tensor packed, torch::Tensor out);
+void fq_dequant_q5_k(torch::Tensor packed, torch::Tensor out);
+void fq_dequant_q6_k(torch::Tensor packed, torch::Tensor out);
+void fq_dequant_iq4_xs(torch::Tensor packed, torch::Tensor out);
+// q8_1-activation K-quant + IQ4_XS decode GEMV (fq_gemv_kq.cu).
+// qb = caller-quantized activations (fq_quant_q8_1_rows); packed = raw GGUF
+// bytes [N, nb256*block_bytes] (144/176/210/136 B per 256-block).
+void fq_gemv_q4_k_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);
+void fq_gemv_q5_k_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);
+void fq_gemv_q6_k_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);
+void fq_gemv_iq4_xs_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);
+// q8_1-activation grouped MoE for KQ/IQ4_XS SwiGLU experts (fq_moe_kq.cu):
+// gate/up/down_ptrs = per-expert base addresses (E int64);
+// strides are per-row bytes; partial = [S, K] float scratch.
+void fq_moe_q4k_grouped_q8(torch::Tensor h, torch::Tensor sel, torch::Tensor wts,
+ torch::Tensor gate_ptrs, torch::Tensor up_ptrs,
+ torch::Tensor down_ptrs,
+ int64_t gate_stride, int64_t up_stride, int64_t down_stride,
+ torch::Tensor partial, torch::Tensor out);
+void fq_moe_q5k_grouped_q8(torch::Tensor h, torch::Tensor sel, torch::Tensor wts,
+ torch::Tensor gate_ptrs, torch::Tensor up_ptrs,
+ torch::Tensor down_ptrs,
+ int64_t gate_stride, int64_t up_stride, int64_t down_stride,
+ torch::Tensor partial, torch::Tensor out);
+void fq_moe_q6k_grouped_q8(torch::Tensor h, torch::Tensor sel, torch::Tensor wts,
+ torch::Tensor gate_ptrs, torch::Tensor up_ptrs,
+ torch::Tensor down_ptrs,
+ int64_t gate_stride, int64_t up_stride, int64_t down_stride,
+ torch::Tensor partial, torch::Tensor out);
+void fq_moe_iq4xs_grouped_q8(torch::Tensor h, torch::Tensor sel, torch::Tensor wts,
+ torch::Tensor gate_ptrs, torch::Tensor up_ptrs,
+ torch::Tensor down_ptrs,
+ int64_t gate_stride, int64_t up_stride, int64_t down_stride,
+ torch::Tensor partial, torch::Tensor out);
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_dequant.cu b/exllamav3/exllamav3_ext/foreign_quant/fq_dequant.cu
new file mode 100644
index 0000000..24b5712
--- /dev/null
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_dequant.cu
@@ -0,0 +1,277 @@
+// Foreign-quant dequant kernels: Q8_0 / IQ2_XXS / NVFP4 -> fp16.
+// Portable CUDA/HIP (no PTX, no wave-size assumptions). v1: one thread
+// per output value, grid-stride loop, scalar loads. v2 (default,
+// BOLT_FQ_DQV2=0 restores v1): streaming 2D grids over (block, row) --
+// no index division, direct u16 header pairs, inline sign unpack, and a
+// 3 KB global table pair for NVFP4 -- same per-element fp32 op order,
+// bitwise-identical output. Bit-exact vs
+// exllamav3/foreign_quant/*.py (see fq_dequant.cuh contract).
+#include <cuda_fp16.h>
+#include <torch/extension.h>
+#include <c10/cuda/CUDAGuard.h>
+#include <ATen/cuda/CUDAContext.h>
+#include "../util.h"
+#include "fq_dequant.cuh"
+#include "fq_gemv.cuh"
+#include "fq_api.h"
+
+namespace {
+
+// 3 KB global NVFP4 tables for the streaming v2 kernel: e2m1p[256] as
+// float2 (lo,hi) + e4m3f[256] as float, both bit-exact copies of
+// FQ_E2M1_LUT / FQ_E4M3_BITS (exact floats / exact bits, no arithmetic).
+// Built once per device on first use (input-independent constants).
+__global__ void fq_dq_tables_build(float* __restrict__ e2m1p, float* __restrict__ e4m3f)
+{
+ int i = blockIdx.x * blockDim.x + threadIdx.x;
+ if (i >= 256)
+ return;
+ e2m1p[2 * i] = FQ_E2M1_LUT[i & 15];
+ e2m1p[2 * i + 1] = FQ_E2M1_LUT[i >> 4];
+ e4m3f[i] = __uint_as_float(FQ_E4M3_BITS[i]);
+}
+
+torch::Tensor fq_dq_e2m1p_cache;
+torch::Tensor fq_dq_e4m3f_cache;
+c10::DeviceIndex fq_dq_tab_dev = -1;
+
+void fq_dq_ensure_tables(torch::Tensor like)
+{
+ c10::DeviceIndex dev = like.get_device();
+ if (fq_dq_tab_dev == dev && fq_dq_e2m1p_cache.defined())
+ return;
+ at::cuda::CUDAGuard guard(dev);
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ fq_dq_e2m1p_cache = torch::empty({256, 2}, torch::dtype(torch::kFloat32).device(like.device()));
+ fq_dq_e4m3f_cache = torch::empty({256}, torch::dtype(torch::kFloat32).device(like.device()));
+ fq_dq_tables_build<<<1, 256, 0, stream>>>(
+ fq_dq_e2m1p_cache.data_ptr<float>(), fq_dq_e4m3f_cache.data_ptr<float>());
+ fq_dq_tab_dev = dev;
+}
+
+// IQ2_XXS streaming dequant v2: 2D grid (Kb, N), 256 threads = one 66B
+// input block -> 256 fp16 outputs. No index division (block IS the
+// block), headers via direct u16 pairs, signs via inline unpack (no
+// divergent const LUT), grid via global LDG. Same per-element fp32 op
+// order as fq_dq_kernel<IQ2> (db = d*(0.5+(a1>>28))*0.25 left-assoc,
+// v = (db*mag)*sgn), hence bitwise-identical.
+__global__ void fq_dq_iq2_kernel_v2(const uint8_t* __restrict__ packed, __half* __restrict__ out,
+ int64_t kb)
+{
+ int b = blockIdx.x;
+ int n = blockIdx.y;
+ int tid = threadIdx.x; // 0..255
+ const uint8_t* blk = packed + ((int64_t)n * kb + b) * FQ_IQ2_XXS_BYTES;
+ __half dh;
+ memcpy(&dh, blk, 2);
+ float d = __half2float(dh);
+ int ib = tid >> 5; // sub-block 0..7
+ int elle = (tid >> 3) & 3; // grid entry 0..3
+ int j = tid & 7; // lane 0..7
+ const uint16_t* h16 = reinterpret_cast<const uint16_t*>(blk + 2 + ib * 8);
+ uint32_t a0 = (uint32_t)h16[0] | ((uint32_t)h16[1] << 16);
+ uint32_t a1 = (uint32_t)h16[2] | ((uint32_t)h16[3] << 16);
+ float db = __fmul_rn(__fmul_rn(d, 0.5f + (float)(a1 >> 28)), 0.25f);
+ uint64_t grid = FQ_IQ2XXS_GRID[(a0 >> (8 * elle)) & 0xFF];
+ float mag = (float)((grid >> (8 * j)) & 0xFF);
+ uint32_t s4 = fq_unpack_ksigns((uint8_t)((a1 >> (7 * elle)) & 127));
+ // s4 replicates the 8 sign bits (KSIGNS entry) across 4 bytes;
+ // 0x01010101<<j selects bit j in every byte (== old KSIGNS&KMASK).
+ float sgn = (s4 & (0x01010101u << j)) ? -1.0f : 1.0f;
+ float v = __fmul_rn(__fmul_rn(db, mag), sgn);
+ out[((int64_t)n * kb + b) * FQ_IQ2_XXS_GROUP + tid] = __float2half_rn(v);
+}
+
+// NVFP4 streaming dequant v2: 2D grid (K/256, N), 256 threads = 256
+// consecutive outputs of row n. Per thread: packed byte + scale byte +
+// global table loads, 2 FMUL. Same op order as fq_nvfp4_group
+// (w = (e2m1*gscale)*global left-assoc), hence bitwise-identical.
+__global__ void fq_dq_nvfp4_kernel_v2(const uint8_t* __restrict__ packed, const uint8_t* __restrict__ scales,
+ const float* __restrict__ e2m1p, const float* __restrict__ e4m3f,
+ __half* __restrict__ out, int64_t nrows, int64_t khalf,
+ int64_t K, float global)
+{
+ int n = blockIdx.y;
+ int64_t k = (int64_t)blockIdx.x * 256 + threadIdx.x;
+ if (k >= K)
+ return;
+ (void)nrows;
+ uint8_t byte = packed[(int64_t)n * khalf + (k >> 1)];
+ const float* p = e2m1p + (size_t)byte * 2;
+ float e = (k & 1) ? p[1] : p[0];
+ float gs = e4m3f[scales[(int64_t)n * (khalf / 8) + (k >> 4)]];
+ float w = __fmul_rn(__fmul_rn(e, gs), global);
+ out[(int64_t)n * K + k] = __float2half_rn(w);
+}
+
+// Q8_0 streaming dequant v2: 2D grid (Kb*8, N), 256 threads = 8 blocks
+// -> 256 outputs. Vectorization-friendly scalar (one qs byte + one FMUL
+// per thread, d broadcast per 32). Same op order as v1 (v = qs*d),
+// hence bitwise-identical.
+__global__ void fq_dq_q8_kernel_v2(const uint8_t* __restrict__ packed, __half* __restrict__ out,
+ int64_t kb)
+{
+ int bb = blockIdx.x; // 8-block group
+ int n = blockIdx.y;
+ int tid = threadIdx.x; // 0..255
+ int64_t b = (int64_t)bb * 8 + (tid >> 5);
+ int j = tid & 31;
+ if (b >= kb)
+ return;
+ const uint8_t* blk = packed + ((int64_t)n * kb + b) * FQ_Q8_0_BYTES;
+ __half dh;
+ memcpy(&dh, blk, 2);
+ float v = __fmul_rn((float)((int8_t)blk[2 + j]), __half2float(dh));
+ out[((int64_t)n * kb + b) * FQ_Q8_0_GROUP + j] = __float2half_rn(v);
+}
+
+// out[n * K + k] for packed[n * Kb, B]; G = group size, B = block bytes.
+template <int G, int B>
+__global__ void fq_dq_kernel(const uint8_t* __restrict__ packed, __half* __restrict__ out,
+ int64_t rows, int64_t kb, float* tmp)
+{
+ (void)tmp;
+ int64_t total = rows * kb * G;
+ for (int64_t t = blockIdx.x * blockDim.x + threadIdx.x; t < total; t += (int64_t)gridDim.x * blockDim.x)
+ {
+ int64_t g = t % G;
+ int64_t b = (t / G) % kb;
+ int64_t n = t / (G * kb);
+ const uint8_t* blk = packed + (n * kb + b) * B;
+ float v;
+ if constexpr (G == FQ_Q8_0_GROUP)
+ {
+ __half dh;
+ memcpy(&dh, blk, 2);
+ v = __fmul_rn((float)((int8_t)blk[2 + g]), __half2float(dh));
+ }
+ else
+ {
+ // IQ2_XXS: decode the value's own (sub-block, grid entry, lane).
+ // The 66-byte block is tiny; every lane recomputes its sub-block's
+ // db from the shared header (L1-cached), keeping the kernel
+ // wave-size agnostic with no cross-lane traffic.
+ int ib = (int)(g >> 5); // sub-block 0..7 (32 values each)
+ int elle = (int)((g >> 3) & 3); // grid entry 0..3 within sub-block
+ int j = (int)(g & 7); // lane 0..7 within grid entry
+ const uint8_t* q = blk + 2 + 8 * ib;
+ uint32_t q0 = (uint32_t)q[0] | ((uint32_t)q[1] << 8);
+ uint32_t q1 = (uint32_t)q[2] | ((uint32_t)q[3] << 8);
+ uint32_t q2 = (uint32_t)q[4] | ((uint32_t)q[5] << 8);
+ uint32_t q3 = (uint32_t)q[6] | ((uint32_t)q[7] << 8);
+ uint32_t a0 = q0 | (q1 << 16);
+ uint32_t a1 = q2 | (q3 << 16);
+ __half dh;
+ memcpy(&dh, blk, 2);
+ float db = __fmul_rn(__fmul_rn(__half2float(dh), 0.5f + (float)(a1 >> 28)), 0.25f);
+ uint64_t grid = FQ_IQ2XXS_GRID[(a0 >> (8 * elle)) & 0xFF];
+ uint8_t signs = FQ_KSIGNS_IQ2XS[(a1 >> (7 * elle)) & 127];
+ float mag = (float)((grid >> (8 * j)) & 0xFF);
+ float sgn = (signs & FQ_KMASK_IQ2XS[j]) ? -1.0f : 1.0f;
+ v = __fmul_rn(__fmul_rn(db, mag), sgn);
+ }
+ out[t] = __float2half_rn(v);
+ }
+}
+
+__global__ void fq_dq_nvfp4_kernel(const uint8_t* __restrict__ packed, const uint8_t* __restrict__ scales,
+ __half* __restrict__ out, int64_t rows, int64_t k_half, float global)
+{
+ // packed [rows, K/2], scales [rows, K/16]; one thread per output value.
+ int64_t total = rows * k_half * 2;
+ for (int64_t t = blockIdx.x * blockDim.x + threadIdx.x; t < total; t += (int64_t)gridDim.x * blockDim.x)
+ {
+ int64_t k = t % (k_half * 2);
+ int64_t n = t / (k_half * 2);
+ uint8_t byte = packed[n * k_half + (k >> 1)];
+ uint8_t nib = (k & 1) ? (byte >> 4) & 0xF : byte & 0xF;
+ float gs = fq_e4m3(scales[n * (k_half / 8) + (k >> 4)]);
+ float w = __fmul_rn(__fmul_rn(FQ_E2M1_LUT[nib], gs), global);
+ out[t] = __float2half_rn(w);
+ }
+}
+
+} // namespace
+
+void fq_dequant_q8_0(torch::Tensor packed, torch::Tensor out)
+{
+ TORCH_CHECK_DTYPE(packed, kByte);
+ TORCH_CHECK_DTYPE(out, kHalf);
+ TORCH_CHECK(packed.is_cuda() && out.is_cuda(), "tensors must be CUDA");
+ TORCH_CHECK(packed.is_contiguous() && out.is_contiguous(), "tensors must be contiguous");
+ TORCH_CHECK_DIM(packed, 3);
+ TORCH_CHECK_DIM(out, 2);
+ TORCH_CHECK_SIZE(packed, 2, FQ_Q8_0_BYTES);
+ int64_t n = packed.size(0), kb = packed.size(1);
+ TORCH_CHECK(out.size(0) == n && out.size(1) == kb * FQ_Q8_0_GROUP, "out must be [N, Kb*32]");
+ at::cuda::CUDAGuard guard(packed.device());
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ int64_t total = n * kb * FQ_Q8_0_GROUP;
+ if (fq_use_dqv2())
+ {
+ dim3 grid((unsigned)CEIL_DIVIDE(kb, 8), (unsigned)n);
+ fq_dq_q8_kernel_v2<<<grid, 256, 0, stream>>>(
+ packed.data_ptr<uint8_t>(), reinterpret_cast<__half*>(out.data_ptr<at::Half>()), kb);
+ return;
+ }
+ fq_dq_kernel<FQ_Q8_0_GROUP, FQ_Q8_0_BYTES>
+ <<<CEIL_DIVIDE(total, 256), 256, 0, stream>>>(
+ packed.data_ptr<uint8_t>(), reinterpret_cast<__half*>(out.data_ptr<at::Half>()), n, kb, nullptr);
+}
+
+void fq_dequant_iq2_xxs(torch::Tensor packed, torch::Tensor out)
+{
+ TORCH_CHECK_DTYPE(packed, kByte);
+ TORCH_CHECK_DTYPE(out, kHalf);
+ TORCH_CHECK(packed.is_cuda() && out.is_cuda(), "tensors must be CUDA");
+ TORCH_CHECK(packed.is_contiguous() && out.is_contiguous(), "tensors must be contiguous");
+ TORCH_CHECK_DIM(packed, 3);
+ TORCH_CHECK_DIM(out, 2);
+ TORCH_CHECK_SIZE(packed, 2, FQ_IQ2_XXS_BYTES);
+ int64_t n = packed.size(0), kb = packed.size(1);
+ TORCH_CHECK(out.size(0) == n && out.size(1) == kb * FQ_IQ2_XXS_GROUP, "out must be [N, Kb*256]");
+ at::cuda::CUDAGuard guard(packed.device());
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ int64_t total = n * kb * FQ_IQ2_XXS_GROUP;
+ if (fq_use_dqv2())
+ {
+ dim3 grid((unsigned)kb, (unsigned)n);
+ fq_dq_iq2_kernel_v2<<<grid, 256, 0, stream>>>(
+ packed.data_ptr<uint8_t>(), reinterpret_cast<__half*>(out.data_ptr<at::Half>()), kb);
+ return;
+ }
+ fq_dq_kernel<FQ_IQ2_XXS_GROUP, FQ_IQ2_XXS_BYTES>
+ <<<CEIL_DIVIDE(total, 256), 256, 0, stream>>>(
+ packed.data_ptr<uint8_t>(), reinterpret_cast<__half*>(out.data_ptr<at::Half>()), n, kb, nullptr);
+}
+
+void fq_dequant_nvfp4(torch::Tensor packed, torch::Tensor scales, double global_scale, torch::Tensor out)
+{
+ TORCH_CHECK_DTYPE(packed, kByte);
+ TORCH_CHECK_DTYPE(scales, kByte);
+ TORCH_CHECK_DTYPE(out, kHalf);
+ TORCH_CHECK(packed.is_cuda() && scales.is_cuda() && out.is_cuda(), "tensors must be CUDA");
+ TORCH_CHECK(packed.is_contiguous() && scales.is_contiguous() && out.is_contiguous(), "tensors must be contiguous");
+ TORCH_CHECK_DIM(packed, 2);
+ TORCH_CHECK_DIM(scales, 2);
+ TORCH_CHECK_DIM(out, 2);
+ int64_t n = packed.size(0), kh = packed.size(1);
+ TORCH_CHECK(scales.size(0) == n && scales.size(1) == kh / 8, "scales must be [N, K/16]");
+ TORCH_CHECK(out.size(0) == n && out.size(1) == kh * 2, "out must be [N, K]");
+ at::cuda::CUDAGuard guard(packed.device());
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ int64_t total = n * kh * 2;
+ if (fq_use_dqv2())
+ {
+ fq_dq_ensure_tables(packed);
+ dim3 grid((unsigned)CEIL_DIVIDE(kh * 2, 256), (unsigned)n);
+ fq_dq_nvfp4_kernel_v2<<<grid, 256, 0, stream>>>(
+ packed.data_ptr<uint8_t>(), scales.data_ptr<uint8_t>(),
+ fq_dq_e2m1p_cache.data_ptr<float>(), fq_dq_e4m3f_cache.data_ptr<float>(),
+ reinterpret_cast<__half*>(out.data_ptr<at::Half>()), n, kh, kh * 2, (float)global_scale);
+ return;
+ }
+ fq_dq_nvfp4_kernel<<<CEIL_DIVIDE(total, 256), 256, 0, stream>>>(
+ packed.data_ptr<uint8_t>(), scales.data_ptr<uint8_t>(),
+ reinterpret_cast<__half*>(out.data_ptr<at::Half>()), n, kh, (float)global_scale);
+}
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_dequant.cuh b/exllamav3/exllamav3_ext/foreign_quant/fq_dequant.cuh
new file mode 100644
index 0000000..9ec7a49
--- /dev/null
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_dequant.cuh
@@ -0,0 +1,112 @@
+// Foreign-quant on-the-fly dequant (device-inline, shared by the dequant and
+// fused dequant-GEMM kernels). Portable CUDA/HIP: no inline PTX, no warp
+// shuffles or wave-size assumptions (every thread decodes its own values from
+// global/constant memory with plain scalar ops), only <cuda_fp16.h> half
+// intrinsics (supported by HIP) plus __fmul_rn/__fadd_rn.
+//
+// Bit-exactness contract: fq_*_block() must reproduce
+// exllamav3/foreign_quant/*.py in float32 op-for-op (same order, single
+// roundings), so a final __float2half_rn matches numpy .astype(fp16).
+// __fmul_rn/__fadd_rn are explicit IEEE round-to-nearest ops the compiler may
+// not fuse or reorder, which keeps this true under --use_fast_math. (HIP
+// provides the same intrinsics.)
+#pragma once
+
+#include <cstdlib>
+#include <cuda_fp16.h>
+#include "fq_tables.cuh"
+
+#define FQ_Q8_0_GROUP 32
+#define FQ_Q8_0_BYTES 34
+#define FQ_IQ2_XXS_GROUP 256
+#define FQ_IQ2_XXS_BYTES 66
+#define FQ_NVFP4_GROUP 16
+
+// Streaming dequant v2 (cooperative-by-construction, no shared/sync):
+// 2D grids over (block, row) so no thread does index division; headers
+// load direct as u16 pairs (ggml get_int_b2 pattern); IQ2 signs unpack
+// inline (ggml unpack_ksigns, no divergent const LUT); NVFP4 reads a
+// 3 KB global table pair (E2M1 float2 + E4M3 float, built once on device
+// by fq_dq_tables_build) instead of branchy fq_e4m3 + divergent LDC.
+// Same per-element float32 op order as the v1 kernels below, hence
+// bitwise-identical output. Default on; BOLT_FQ_DQV2=0 restores v1.
+inline bool fq_use_dqv2()
+{
+ const char* e = std::getenv("BOLT_FQ_DQV2");
+ return !e || e[0] != '0';
+}
+
+// One 34-byte Q8_0 block -> 32 float32 values. Matches q8_0.py dequant_q8_0:
+// y[j] = (float)(int8_t)qs[j] * (float)(fp16)d, single fp32 rounding.
+__forceinline__ __device__ void fq_q8_0_block(const uint8_t* blk, float* out32)
+{
+ __half dh;
+ memcpy(&dh, blk, 2);
+ float d = __half2float(dh);
+ for (int j = 0; j < 32; j++)
+ out32[j] = __fmul_rn((float)((int8_t)blk[2 + j]), d);
+}
+
+// One 66-byte IQ2_XXS block -> 256 float32 values. Port of llama.cpp
+// dequantize_row_iq2_xxs in the same op order as iq2_xxs.py _dequant_block:
+// db = d * (0.5 + (a1 >> 28)) * 0.25 (fp32, left-assoc)
+// out = (db * grid_mag) * sign (fp32, left-assoc)
+__forceinline__ __device__ void fq_iq2_xxs_block(const uint8_t* blk, float* out256)
+{
+ __half dh;
+ memcpy(&dh, blk, 2);
+ float d = __half2float(dh);
+ int pos = 0;
+ for (int ib = 0; ib < 8; ib++)
+ {
+ uint32_t q0 = (uint32_t)blk[2 + 8 * ib] | ((uint32_t)blk[2 + 8 * ib + 1] << 8);
+ uint32_t q1 = (uint32_t)blk[2 + 8 * ib + 2] | ((uint32_t)blk[2 + 8 * ib + 3] << 8);
+ uint32_t q2 = (uint32_t)blk[2 + 8 * ib + 4] | ((uint32_t)blk[2 + 8 * ib + 5] << 8);
+ uint32_t q3 = (uint32_t)blk[2 + 8 * ib + 6] | ((uint32_t)blk[2 + 8 * ib + 7] << 8);
+ uint32_t a0 = q0 | (q1 << 16);
+ uint32_t a1 = q2 | (q3 << 16);
+ float db = __fmul_rn(__fmul_rn(d, 0.5f + (float)(a1 >> 28)), 0.25f);
+ for (int elle = 0; elle < 4; elle++)
+ {
+ uint64_t grid = FQ_IQ2XXS_GRID[(a0 >> (8 * elle)) & 0xFF];
+ uint8_t signs = FQ_KSIGNS_IQ2XS[(a1 >> (7 * elle)) & 127];
+ for (int j = 0; j < 8; j++)
+ {
+ float mag = (float)((grid >> (8 * j)) & 0xFF);
+ float sgn = (signs & FQ_KMASK_IQ2XS[j]) ? -1.0f : 1.0f;
+ out256[pos++] = __fmul_rn(__fmul_rn(db, mag), sgn);
+ }
+ }
+ }
+}
+
+// OCP fp8 E4M3 byte -> float32. Matches nvfp4.py e4m3_to_float32 bit-exactly:
+// normal (incl. e==15, m!=7): scalbn(1 + m/8, e-7); subnormal: m * 2^-9;
+// zero -> signed zero; 0x7F/0xFF -> NaN. All intermediate values are exact
+// (power-of-two scalings, 1 + m/8 representable), so plain ops suffice.
+__forceinline__ __device__ float fq_e4m3(uint8_t b)
+{
+ int e = (b >> 3) & 0xF;
+ int m = b & 0x7;
+ if (e == 15 && m == 7) return nanf("");
+ float v;
+ if (e == 0)
+ v = (m == 0) ? 0.0f : (float)m * 0.001953125f; // m * 2^-9, exact
+ else
+ v = scalbnf(1.0f + (float)m * 0.125f, e - 7); // exact
+ return (b & 0x80) ? -v : v;
+}
+
+// One NVFP4 group (8 packed E2M1 bytes + 1 E4M3 scale + fp32 global) ->
+// 16 float32 values. Matches nvfp4.py dequant_nvfp4: (e2m1 * gscale) * global,
+// left-assoc fp32. Low nibble = even index (ModelOpt packing).
+__forceinline__ __device__ void fq_nvfp4_group(const uint8_t* packed8, float gscale, float global, float* out16)
+{
+ for (int i = 0; i < 8; i++)
+ {
+ float lo = FQ_E2M1_LUT[packed8[i] & 0xF];
+ float hi = FQ_E2M1_LUT[(packed8[i] >> 4) & 0xF];
+ out16[2 * i] = __fmul_rn(__fmul_rn(lo, gscale), global);
+ out16[2 * i + 1] = __fmul_rn(__fmul_rn(hi, gscale), global);
+ }
+}
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_dequant_kq.cu b/exllamav3/exllamav3_ext/foreign_quant/fq_dequant_kq.cu
new file mode 100644
index 0000000..3375c01
--- /dev/null
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_dequant_kq.cu
@@ -0,0 +1,272 @@
+// Foreign-quant dequant to fp16 for the GGUF K-quants (Q4_K / Q5_K / Q6_K)
+// and IQ4_XS: the unfused weight path for batched prefill. One dequant pass
+// over the raw packed bytes writes the [N, K] fp16 weight, then cuBLAS fp16
+// GEMM does the math (foreign_linear._dequant_rows serves these formats;
+// rows >= 16 run the unfused dequant + cuBLAS fp16 GEMM prefill path).
+//
+// Same launch shape as the v2 kernels in fq_dequant.cu: 2D grid (Kb, N),
+// 256 threads = one 256-element super-block, threadIdx.x = element index
+// inside the block, one fp16 store per thread. gridDim.y caps at 65535 rows
+// (the lm_head is N = 248144), so the launchers chunk the rows in groups of
+// at most 65535 with pointer offsets -- kernels themselves are unchanged.
+// No shared memory, no __syncthreads, no index division. Each thread re-parses the few header
+// bytes its own value needs (L1-resident), which keeps the kernels free of
+// cross-lane traffic and of any wave-size assumption.
+//
+// Bit-exactness contract (see fq_dequant.cuh): float32 op-for-op in the same
+// order as exllamav3/foreign_quant/k_quants.py dequant_{q4_K,q5_K,q6_K,
+// iq4_xs}_block, one rounding per op. Every float op is an explicit
+// __fmul_rn/__fsub_rn (never a bare a*b, which --use_fast_math would contract
+// into an FMA), then a single __float2half_rn, so the output is
+// bitwise-identical to dequant_row(blocks, fmt).astype(np.float16).
+//
+// Portable CUDA/HIP: no inline PTX, no warp shuffles, no wave-size
+// assumptions, only <cuda_fp16.h> intrinsics and the __fmul_rn family. The
+// Q4_K/Q5_K 6-bit scale bytes go through the shared fq_q4k_scales()
+// (fq_gemv.cuh, verbatim ggml get_scale_min_k4) and IQ4_XS reads the shared
+// FQ_KVALUES_IQ4NL codebook; neither bit twiddling is re-implemented here.
+#include <cuda_fp16.h>
+#include <torch/extension.h>
+#include <c10/cuda/CUDAGuard.h>
+#include <ATen/cuda/CUDAContext.h>
+#include "../util.h"
+#include "fq_dequant.cuh"
+#include "fq_gemv.cuh"
+#include "fq_api.h"
+
+namespace {
+
+// Q4_K: 144 B per 256-block (d half @0, dmin half @2, scales[12] @4,
+// qs[128] @16). 256 elements = 4 groups of 64 = 8 sub-groups of 32; the
+// numpy loop walks those 64-groups (j = 0, 64, 128, 192) and pulls the scale
+// pair (is_+0, is_+1) per group, i.e. sub-group s = e >> 5 gets the pair
+// decoded by fq_q4k_scales(..., s >> 1) at index s & 1. First 32 elements of
+// a 64-group take the low nibble (d1, m1), next 32 the high nibble (d2, m2):
+// y = (d*sc) * nib - (dmin*m) (left-assoc, two roundings).
+__global__ void fq_dq_q4_k_kernel(const uint8_t* __restrict__ packed, __half* __restrict__ out,
+ int64_t kb)
+{
+ int b = blockIdx.x; // 256-block index within the row
+ int n = blockIdx.y; // row
+ int e = threadIdx.x; // 0..255, element index inside the block
+ const uint8_t* blk = packed + ((int64_t)n * kb + b) * FQ_Q4_K_BYTES;
+ __half dh, dmh;
+ memcpy(&dh, blk, 2);
+ memcpy(&dmh, blk + 2, 2);
+ float d = __half2float(dh);
+ float dmin = __half2float(dmh);
+ int c = e >> 6; // 64-element group 0..3
+ int s = e >> 5; // 32-element sub-group 0..7 == 2*c + (nib. hi)
+ int l = e & 31; // lane inside the sub-group
+ int hi = s & 1; // 0: low nibble of qs, 1: high nibble
+ uint8_t sc[2], m[2];
+ fq_q4k_scales(blk + 4, s >> 1, sc, m);
+ uint8_t q = blk[16 + 32 * c + l];
+ int nib = hi ? (q >> 4) : (q & 0xF);
+ float d1 = __fmul_rn(d, (float)sc[hi]);
+ float m1 = __fmul_rn(dmin, (float)m[hi]);
+ float v = __fsub_rn(__fmul_rn(d1, (float)nib), m1);
+ out[((int64_t)n * kb + b) * FQ_Q4_K_GROUP + e] = __float2half_rn(v);
+}
+
+// Q5_K: 176 B per 256-block (d @0, dmin @2, scales[12] @4, qh[32] @16,
+// qs[128] @48). Identical to Q4_K plus the 5th bit, and the bit plane is the
+// trap: the numpy loop shifts the masks per 64-group (u1 = 1<<(2*c),
+// u2 = 2<<(2*c)) while the qh byte index restarts at 0 in every group, so the
+// mask is 1 << (2*c + hi) == 1 << s and the qh byte is l, NOT l + 32*c.
+// y = (d*sc) * (nib + 16*(qh[l] >> s & 1)) - (dmin*m)
+__global__ void fq_dq_q5_k_kernel(const uint8_t* __restrict__ packed, __half* __restrict__ out,
+ int64_t kb)
+{
+ int b = blockIdx.x;
+ int n = blockIdx.y;
+ int e = threadIdx.x;
+ const uint8_t* blk = packed + ((int64_t)n * kb + b) * FQ_Q5_K_BYTES;
+ __half dh, dmh;
+ memcpy(&dh, blk, 2);
+ memcpy(&dmh, blk + 2, 2);
+ float d = __half2float(dh);
+ float dmin = __half2float(dmh);
+ int c = e >> 6;
+ int s = e >> 5;
+ int l = e & 31;
+ int hi = s & 1;
+ uint8_t sc[2], m[2];
+ fq_q4k_scales(blk + 4, s >> 1, sc, m);
+ uint8_t q = blk[48 + 32 * c + l];
+ int nib = hi ? (q >> 4) : (q & 0xF);
+ int bit = (blk[16 + l] >> s) & 1; // qh index is l only; mask is 1 << s
+ int q5 = nib + (bit << 4);
+ float d1 = __fmul_rn(d, (float)sc[hi]);
+ float m1 = __fmul_rn(dmin, (float)m[hi]);
+ float v = __fsub_rn(__fmul_rn(d1, (float)q5), m1);
+ out[((int64_t)n * kb + b) * FQ_Q5_K_GROUP + e] = __float2half_rn(v);
+}
+
+// Q6_K: 210 B per 256-block (ql[128] @0, qh[64] @128, 16 int8 scales @192,
+// d half @208). Two 128-element halves; inside a half the 32 lanes of loop
+// iteration l are laid out as 4 interleaved groups of 32 outputs, group
+// (q1..q4) writing y[p], y[p+32], y[p+64], y[p+96] and taking the scales
+// sc[is_+0], sc[is_+2], sc[is_+4], sc[is_+6] with is_ = l/16. So the output
+// index alone gives group = (e & 127) >> 5, and the scale index is
+// 8*half + 2*group + (l >> 4) -- the +2*group term is the second trap. The
+// numpy ql/qh/sc slices advance per half by 64/32/8 RELATIVE to their own
+// planes, so the global byte offsets are 64*half, 128 + 32*half and 192 +
+// 8*half -- dropping the 128 would silently read the wrong qh plane.
+// y = (d * sc) * q (left-assoc: d*sc first, then *q, q already -32)
+__global__ void fq_dq_q6_k_kernel(const uint8_t* __restrict__ packed, __half* __restrict__ out,
+ int64_t kb)
+{
+ int b = blockIdx.x;
+ int n = blockIdx.y;
+ int e = threadIdx.x;
+ const uint8_t* blk = packed + ((int64_t)n * kb + b) * FQ_Q6_K_BYTES;
+ int half = e >> 7; // 128-element half 0..1
+ int t = e & 127; // index inside the half
+ int grp = t >> 5; // 0..3 -> q1..q4, output offset 32*grp
+ int l = t & 31; // numpy loop index l
+ __half dh;
+ memcpy(&dh, blk + 208, 2);
+ float d = __half2float(dh);
+ uint8_t ql = blk[64 * half + l + 32 * (grp & 1)];
+ uint8_t qh = blk[128 + 32 * half + l]; // qh plane starts at byte 128
+ // q1/q2 take the LOW nibble (ql[l], ql[l+32]), q3/q4 the HIGH nibble
+ // (ql[l], ql[l+32]) -- so the nibble follows grp >= 2, not grp & 1, while
+ // the ql byte follows grp & 1.
+ int q = (grp >> 1) ? (ql >> 4) : (ql & 0xF);
+ q = q | (((qh >> (2 * grp)) & 3) << 4);
+ q -= 32;
+ float s = (float)(int8_t)blk[192 + 8 * half + 2 * grp + (l >> 4)];
+ float v = __fmul_rn(__fmul_rn(d, s), (float)q);
+ out[((int64_t)n * kb + b) * FQ_Q6_K_GROUP + e] = __float2half_rn(v);
+}
+
+// IQ4_XS: 136 B per 256-block (d half @0, scales_h u16 @2, scales_l[4] @4,
+// qs[128] @8). 8 sub-blocks of 32, each with its own 6-bit-ish scale
+// ls = (scales_l[ib/2] >> 4*(ib%2) & 0xF) | ((scales_h >> 2*ib & 3) << 4)
+// and dl = d * (ls - 32); the first 16 lanes take the low nibble of 16 qs
+// bytes, the next 16 the high nibble of the same bytes.
+// y = (d * (ls-32)) * kvalues[nib]
+__global__ void fq_dq_iq4_xs_kernel(const uint8_t* __restrict__ packed, __half* __restrict__ out,
+ int64_t kb)
+{
+ int b = blockIdx.x;
+ int n = blockIdx.y;
+ int e = threadIdx.x;
+ const uint8_t* blk = packed + ((int64_t)n * kb + b) * FQ_IQ4_XS_BYTES;
+ __half dh;
+ memcpy(&dh, blk, 2);
+ float d = __half2float(dh);
+ uint16_t sh;
+ memcpy(&sh, blk + 2, 2);
+ int ib = e >> 5; // sub-block 0..7
+ int j = e & 31; // lane inside the sub-block
+ uint8_t sl = blk[4 + (ib >> 1)];
+ int ls = (int)((sl >> (4 * (ib & 1))) & 0xF) | (int)(((uint32_t)sh >> (2 * ib)) & 3u) << 4;
+ uint8_t q = blk[8 + 16 * ib + (j & 15)];
+ int nib = (j & 16) ? (q >> 4) : (q & 0xF);
+ float dl = __fmul_rn(d, (float)(ls - 32));
+ float v = __fmul_rn(dl, (float)FQ_KVALUES_IQ4NL[nib]);
+ out[((int64_t)n * kb + b) * FQ_IQ4_XS_GROUP + e] = __float2half_rn(v);
+}
+
+// Shared validation + geometry for the four launchers. packed is [N, Kb*bb]
+// (a [N, Kb, bb] view is accepted too, like the fq_dequant_q8_0 caller shape);
+// out is [N, Kb*256]. All four formats have 256 values per block.
+static bool fq_dq_kq_check(torch::Tensor& packed, torch::Tensor& out, int64_t block_bytes,
+ int64_t& n, int64_t& kb)
+{
+ TORCH_CHECK_DTYPE(packed, kByte);
+ TORCH_CHECK_DTYPE(out, kHalf);
+ TORCH_CHECK(packed.is_cuda() && out.is_cuda(), "tensors must be CUDA");
+ TORCH_CHECK(packed.is_contiguous() && out.is_contiguous(), "tensors must be contiguous");
+ TORCH_CHECK(packed.dim() == 2 || packed.dim() == 3, "packed must be [N, Kb*bb] or [N, Kb, bb]");
+ TORCH_CHECK_DIM(out, 2);
+ n = packed.size(0);
+ if (packed.dim() == 3)
+ {
+ TORCH_CHECK_SIZE(packed, 2, block_bytes);
+ kb = packed.size(1);
+ }
+ else
+ {
+ TORCH_CHECK(packed.size(1) % block_bytes == 0, "packed row bytes must be a multiple of the block size");
+ kb = packed.size(1) / block_bytes;
+ }
+ TORCH_CHECK(out.size(0) == n && out.size(1) == kb * FQ_Q4_K_GROUP, "out must be [N, Kb*256]");
+ return n > 0 && kb > 0; // empty input: nothing to launch
+}
+
+} // namespace
+
+// gridDim.y caps at 65535: the lm_head dequant is N = 248144 rows, so every
+// launcher below chunks the rows (pointer offsets, kernels unchanged).
+static const int64_t FQ_DQ_KQ_MAX_ROWS = 65535;
+
+void fq_dequant_q4_k(torch::Tensor packed, torch::Tensor out)
+{
+ int64_t n, kb;
+ if (!fq_dq_kq_check(packed, out, FQ_Q4_K_BYTES, n, kb)) return;
+ at::cuda::CUDAGuard guard(packed.device());
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ const uint8_t* p = packed.data_ptr<uint8_t>();
+ __half* o = reinterpret_cast<__half*>(out.data_ptr<at::Half>());
+ for (int64_t n0 = 0; n0 < n; n0 += FQ_DQ_KQ_MAX_ROWS)
+ {
+ int64_t nc = (n - n0 < FQ_DQ_KQ_MAX_ROWS) ? n - n0 : FQ_DQ_KQ_MAX_ROWS;
+ dim3 grid((unsigned)kb, (unsigned)nc);
+ fq_dq_q4_k_kernel<<<grid, 256, 0, stream>>>(
+ p + n0 * kb * FQ_Q4_K_BYTES, o + n0 * kb * FQ_Q4_K_GROUP, kb);
+ }
+}
+
+void fq_dequant_q5_k(torch::Tensor packed, torch::Tensor out)
+{
+ int64_t n, kb;
+ if (!fq_dq_kq_check(packed, out, FQ_Q5_K_BYTES, n, kb)) return;
+ at::cuda::CUDAGuard guard(packed.device());
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ const uint8_t* p = packed.data_ptr<uint8_t>();
+ __half* o = reinterpret_cast<__half*>(out.data_ptr<at::Half>());
+ for (int64_t n0 = 0; n0 < n; n0 += FQ_DQ_KQ_MAX_ROWS)
+ {
+ int64_t nc = (n - n0 < FQ_DQ_KQ_MAX_ROWS) ? n - n0 : FQ_DQ_KQ_MAX_ROWS;
+ dim3 grid((unsigned)kb, (unsigned)nc);
+ fq_dq_q5_k_kernel<<<grid, 256, 0, stream>>>(
+ p + n0 * kb * FQ_Q5_K_BYTES, o + n0 * kb * FQ_Q5_K_GROUP, kb);
+ }
+}
+
+void fq_dequant_q6_k(torch::Tensor packed, torch::Tensor out)
+{
+ int64_t n, kb;
+ if (!fq_dq_kq_check(packed, out, FQ_Q6_K_BYTES, n, kb)) return;
+ at::cuda::CUDAGuard guard(packed.device());
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ const uint8_t* p = packed.data_ptr<uint8_t>();
+ __half* o = reinterpret_cast<__half*>(out.data_ptr<at::Half>());
+ for (int64_t n0 = 0; n0 < n; n0 += FQ_DQ_KQ_MAX_ROWS)
+ {
+ int64_t nc = (n - n0 < FQ_DQ_KQ_MAX_ROWS) ? n - n0 : FQ_DQ_KQ_MAX_ROWS;
+ dim3 grid((unsigned)kb, (unsigned)nc);
+ fq_dq_q6_k_kernel<<<grid, 256, 0, stream>>>(
+ p + n0 * kb * FQ_Q6_K_BYTES, o + n0 * kb * FQ_Q6_K_GROUP, kb);
+ }
+}
+
+void fq_dequant_iq4_xs(torch::Tensor packed, torch::Tensor out)
+{
+ int64_t n, kb;
+ if (!fq_dq_kq_check(packed, out, FQ_IQ4_XS_BYTES, n, kb)) return;
+ at::cuda::CUDAGuard guard(packed.device());
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ const uint8_t* p = packed.data_ptr<uint8_t>();
+ __half* o = reinterpret_cast<__half*>(out.data_ptr<at::Half>());
+ for (int64_t n0 = 0; n0 < n; n0 += FQ_DQ_KQ_MAX_ROWS)
+ {
+ int64_t nc = (n - n0 < FQ_DQ_KQ_MAX_ROWS) ? n - n0 : FQ_DQ_KQ_MAX_ROWS;
+ dim3 grid((unsigned)kb, (unsigned)nc);
+ fq_dq_iq4_xs_kernel<<<grid, 256, 0, stream>>>(
+ p + n0 * kb * FQ_IQ4_XS_BYTES, o + n0 * kb * FQ_IQ4_XS_GROUP, kb);
+ }
+}
\ No newline at end of file
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_gemm.cu b/exllamav3/exllamav3_ext/foreign_quant/fq_gemm.cu
new file mode 100644
index 0000000..26fb714
--- /dev/null
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_gemm.cu
@@ -0,0 +1,176 @@
+// Fused dequant-GEMV/GEMM for foreign-quant weights (decode path, M = 1..16).
+// out[m, n] = sum_k x[m, k] * W[n, k], fp32 accumulate, fp16 out. Weights are
+// dequanted on the fly with the bit-exact fq_*_block() arithmetic, so versus
+// dequant()+matmul only the accumulation order differs (fp16 tolerance).
+// Portable CUDA/HIP: one thread per (row, out-col), sequential K loop, no
+// cross-lane traffic, no wave-size assumptions.
+#include <cuda_fp16.h>
+#include <torch/extension.h>
+#include <c10/cuda/CUDAGuard.h>
+#include <ATen/cuda/CUDAContext.h>
+#include "../util.h"
+#include "fq_dequant.cuh"
+#include "fq_api.h"
+
+namespace {
+
+// W layout [N, Kb, B] with group G (Q8_0: G=32/B=34, IQ2_XXS: G=256/B=66).
+template <int G, int B>
+__global__ void fq_gemm_kernel(const __half* __restrict__ x, const uint8_t* __restrict__ packed,
+ __half* __restrict__ out, int M, int N, int K)
+{
+ int64_t total = (int64_t)M * N;
+ for (int64_t t = blockIdx.x * blockDim.x + threadIdx.x; t < total; t += (int64_t)gridDim.x * blockDim.x)
+ {
+ int n = (int)(t % N);
+ int m = (int)(t / N);
+ const __half* xr = x + (int64_t)m * K;
+ const uint8_t* wr = packed + (int64_t)n * (K / G) * B;
+ float acc = 0.0f;
+ if constexpr (G == FQ_Q8_0_GROUP)
+ {
+ for (int k0 = 0; k0 < K; k0 += 32)
+ {
+ const uint8_t* blk = wr + (k0 / 32) * 34;
+ __half dh;
+ memcpy(&dh, blk, 2);
+ float d = __half2float(dh);
+ for (int j = 0; j < 32; j++)
+ {
+ float w = __fmul_rn((float)((int8_t)blk[2 + j]), d);
+ acc = __fadd_rn(acc, __fmul_rn(__half2float(xr[k0 + j]), w));
+ }
+ }
+ }
+ else
+ {
+ for (int k0 = 0; k0 < K; k0 += 256)
+ {
+ const uint8_t* blk = wr + (k0 / 256) * 66;
+ for (int ib = 0; ib < 8; ib++)
+ {
+ const uint8_t* q = blk + 2 + 8 * ib;
+ uint32_t q0 = (uint32_t)q[0] | ((uint32_t)q[1] << 8);
+ uint32_t q1 = (uint32_t)q[2] | ((uint32_t)q[3] << 8);
+ uint32_t q2 = (uint32_t)q[4] | ((uint32_t)q[5] << 8);
+ uint32_t q3 = (uint32_t)q[6] | ((uint32_t)q[7] << 8);
+ uint32_t a0 = q0 | (q1 << 16);
+ uint32_t a1 = q2 | (q3 << 16);
+ __half dh;
+ memcpy(&dh, blk, 2);
+ float db = __fmul_rn(__fmul_rn(__half2float(dh), 0.5f + (float)(a1 >> 28)), 0.25f);
+ for (int elle = 0; elle < 4; elle++)
+ {
+ uint64_t grid = FQ_IQ2XXS_GRID[(a0 >> (8 * elle)) & 0xFF];
+ uint8_t signs = FQ_KSIGNS_IQ2XS[(a1 >> (7 * elle)) & 127];
+ int kb = k0 + 32 * ib + 8 * elle;
+ for (int j = 0; j < 8; j++)
+ {
+ float mag = (float)((grid >> (8 * j)) & 0xFF);
+ float sgn = (signs & FQ_KMASK_IQ2XS[j]) ? -1.0f : 1.0f;
+ float w = __fmul_rn(__fmul_rn(db, mag), sgn);
+ acc = __fadd_rn(acc, __fmul_rn(__half2float(xr[kb + j]), w));
+ }
+ }
+ }
+ }
+ }
+ out[t] = __float2half_rn(acc);
+ }
+}
+
+__global__ void fq_gemm_nvfp4_kernel(const __half* __restrict__ x, const uint8_t* __restrict__ packed,
+ const uint8_t* __restrict__ scales, __half* __restrict__ out,
+ int M, int N, int K, float global)
+{
+ // packed [N, K/2], scales [N, K/16].
+ int64_t total = (int64_t)M * N;
+ for (int64_t t = blockIdx.x * blockDim.x + threadIdx.x; t < total; t += (int64_t)gridDim.x * blockDim.x)
+ {
+ int n = (int)(t % N);
+ int m = (int)(t / N);
+ const __half* xr = x + (int64_t)m * K;
+ const uint8_t* pr = packed + (int64_t)n * (K / 2);
+ const uint8_t* sr = scales + (int64_t)n * (K / 16);
+ float acc = 0.0f;
+ for (int k0 = 0; k0 < K; k0 += 16)
+ {
+ float gs = fq_e4m3(sr[k0 / 16]);
+ for (int j = 0; j < 16; j += 2)
+ {
+ uint8_t byte = pr[(k0 + j) / 2];
+ float w0 = __fmul_rn(__fmul_rn(FQ_E2M1_LUT[byte & 0xF], gs), global);
+ float w1 = __fmul_rn(__fmul_rn(FQ_E2M1_LUT[(byte >> 4) & 0xF], gs), global);
+ acc = __fadd_rn(acc, __fmul_rn(__half2float(xr[k0 + j]), w0));
+ acc = __fadd_rn(acc, __fmul_rn(__half2float(xr[k0 + j + 1]), w1));
+ }
+ }
+ out[t] = __float2half_rn(acc);
+ }
+}
+
+template <int G, int B>
+static void fq_gemm_q(torch::Tensor x, torch::Tensor packed, torch::Tensor out)
+{
+ TORCH_CHECK_DTYPE(x, kHalf);
+ TORCH_CHECK_DTYPE(packed, kByte);
+ TORCH_CHECK_DTYPE(out, kHalf);
+ TORCH_CHECK(x.is_cuda() && packed.is_cuda() && out.is_cuda(), "tensors must be CUDA");
+ TORCH_CHECK(x.is_contiguous() && packed.is_contiguous() && out.is_contiguous(), "tensors must be contiguous");
+ TORCH_CHECK_DIM(x, 2);
+ TORCH_CHECK_DIM(packed, 3);
+ TORCH_CHECK_DIM(out, 2);
+ TORCH_CHECK_SIZE(packed, 2, B);
+ int M = (int)x.size(0), K = (int)x.size(1), N = (int)out.size(1);
+ TORCH_CHECK((int)out.size(0) == M, "out rows must match x rows");
+ TORCH_CHECK(K % G == 0, "K must be a multiple of the quant group");
+ TORCH_CHECK((int)packed.size(0) == N && (int)packed.size(1) == K / G, "packed must be [N, K/G, B]");
+ TORCH_CHECK(M >= 1 && M <= 16, "fused path covers M = 1..16; larger rows take dequant+matmul");
+ at::cuda::CUDAGuard guard(x.device());
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ int64_t total = (int64_t)M * N;
+ fq_gemm_kernel<G, B><<<CEIL_DIVIDE(total, 256), 256, 0, stream>>>(
+ reinterpret_cast<const __half*>(x.data_ptr<at::Half>()), packed.data_ptr<uint8_t>(),
+ reinterpret_cast<__half*>(out.data_ptr<at::Half>()), M, N, K);
+}
+
+} // namespace
+
+void fq_gemm_q8_0(torch::Tensor x, torch::Tensor packed, torch::Tensor out)
+{
+ fq_gemm_q<FQ_Q8_0_GROUP, FQ_Q8_0_BYTES>(x, packed, out);
+}
+
+void fq_gemm_iq2_xxs(torch::Tensor x, torch::Tensor packed, torch::Tensor out)
+{
+ fq_gemm_q<FQ_IQ2_XXS_GROUP, FQ_IQ2_XXS_BYTES>(x, packed, out);
+}
+
+void fq_gemm_nvfp4(torch::Tensor x, torch::Tensor packed, torch::Tensor scales, double global_scale,
+ torch::Tensor out)
+{
+ TORCH_CHECK_DTYPE(x, kHalf);
+ TORCH_CHECK_DTYPE(packed, kByte);
+ TORCH_CHECK_DTYPE(scales, kByte);
+ TORCH_CHECK_DTYPE(out, kHalf);
+ TORCH_CHECK(x.is_cuda() && packed.is_cuda() && scales.is_cuda() && out.is_cuda(), "tensors must be CUDA");
+ TORCH_CHECK(x.is_contiguous() && packed.is_contiguous() && scales.is_contiguous() && out.is_contiguous(),
+ "tensors must be contiguous");
+ TORCH_CHECK_DIM(x, 2);
+ TORCH_CHECK_DIM(packed, 2);
+ TORCH_CHECK_DIM(scales, 2);
+ TORCH_CHECK_DIM(out, 2);
+ int M = (int)x.size(0), K = (int)x.size(1), N = (int)out.size(1);
+ TORCH_CHECK((int)out.size(0) == M, "out rows must match x rows");
+ TORCH_CHECK(K % FQ_NVFP4_GROUP == 0, "K must be a multiple of 16");
+ TORCH_CHECK((int)packed.size(0) == N && (int)packed.size(1) == K / 2, "packed must be [N, K/2]");
+ TORCH_CHECK((int)scales.size(0) == N && (int)scales.size(1) == K / 16, "scales must be [N, K/16]");
+ TORCH_CHECK(M >= 1 && M <= 16, "fused path covers M = 1..16; larger rows take dequant+matmul");
+ at::cuda::CUDAGuard guard(x.device());
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ int64_t total = (int64_t)M * N;
+ fq_gemm_nvfp4_kernel<<<CEIL_DIVIDE(total, 256), 256, 0, stream>>>(
+ reinterpret_cast<const __half*>(x.data_ptr<at::Half>()), packed.data_ptr<uint8_t>(),
+ scales.data_ptr<uint8_t>(), reinterpret_cast<__half*>(out.data_ptr<at::Half>()),
+ M, N, K, (float)global_scale);
+}
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_gemv.cu b/exllamav3/exllamav3_ext/foreign_quant/fq_gemv.cu
new file mode 100644
index 0000000..71f2851
--- /dev/null
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_gemv.cu
@@ -0,0 +1,285 @@
+// Fast decode GEMV for foreign-quant weights (M = 1..16 rows).
+// out[m, n] = sum_k x[m, k] * W[n, k], fp32 accumulate, fp16 or fp32 out.
+//
+// Why this beats fq_gemm.cu at decode: the old kernel gives one thread a
+// whole (row, col) dot product, so every output re-reads the full x row from
+// global memory (N x traffic) and small-N layers launch only M*N threads
+// (e.g. 4 blocks for a 1024-wide latent proj: most SMs idle). This kernel
+// instead cooperates: a block stages one x row in shared memory once, 8
+// lane-groups of 32 lanes each take one output, lanes split K and reduce in
+// shared memory. Weight traffic is unchanged (one pass, the roofline floor);
+// x traffic drops from M*N*K to M*K; occupancy is full for any N >= 8.
+//
+// Portable CUDA/HIP: no PTX, no warp shuffles (the 32-lane groups reduce
+// through shared memory + __syncthreads, so wave32 and wave64 both work),
+// only cuda_fp16.h half ops plus __fmul_rn/__fadd_rn (HIP has both).
+// Accuracy: same per-element fp32 arithmetic as fq_dequant.cuh, but the K
+// summation is lane-strided and the 32 partials reduce sequentially, so vs
+// fq_gemm the fp32 accumulation ORDER differs (fp16 tolerance, same contract
+// as the existing fused-vs-unfused path).
+#include <cuda_fp16.h>
+#include <torch/extension.h>
+#include <c10/cuda/CUDAGuard.h>
+#include <ATen/cuda/CUDAContext.h>
+#include "../util.h"
+#include "fq_gemv.cuh"
+#include "fq_api.h"
+
+namespace {
+
+// Cooperative GEMV core. FMT selects the format: 0 = Q8_0, 1 = IQ2_XXS,
+// 2 = NVFP4. IN/OUT select the x/out dtypes (half/float). PAIR selects the
+// NVFP4 E2M1 pair-table dot (meaningful for FMT == 2 only).
+// packed/sr point at output row n's data (strides applied by the caller).
+template <int FMT, typename IN, typename OUT, bool PAIR = false>
+__global__ void fq_gemv_kernel(const IN* __restrict__ x, const uint8_t* __restrict__ packed,
+ const uint8_t* __restrict__ scales, float global,
+ OUT* __restrict__ out, int M, int N, int K,
+ int64_t packed_stride, int64_t scales_stride, bool use_aux)
+{
+ int tile = blockIdx.x;
+ int ntiles = (N + FQ_GEMV_OUT_PER_BLOCK - 1) / FQ_GEMV_OUT_PER_BLOCK;
+ int m = tile / ntiles;
+ int t = tile % ntiles;
+ int grp = threadIdx.x / FQ_GEMV_LANES; // 0..7 output slot in this block
+ int lane = threadIdx.x % FQ_GEMV_LANES; // 0..31 K-split lane
+ int n = t * FQ_GEMV_OUT_PER_BLOCK + grp;
+
+ extern __shared__ __half sh[];
+ __half* xs = sh; // K halves
+ // IQ2 header scratch (8 groups x nb*16 u32) lives between xs and red.
+ // NVFP4 pair table (256 float2, PAIR arm only) likewise, with the
+ // scaled-e4m3 table (256 floats, use_stab arm) after it.
+ uint32_t* hdrs = nullptr;
+ float2* e2m1p = nullptr;
+ float* stab = nullptr;
+ float* red;
+ int nb1 = K / FQ_IQ2_XXS_GROUP;
+ // use_aux (block-uniform kernel arg): scaled-e4m3 table arm for FMT==2
+ // (from BOLT_FQ_STAB). FMT==1 ignores it.
+ bool use_stab = false;
+ if constexpr (FMT == 1)
+ {
+ hdrs = reinterpret_cast<uint32_t*>(xs + K);
+ red = reinterpret_cast<float*>(hdrs + 8 * nb1 * 16);
+ }
+ else if constexpr (FMT == 2)
+ {
+ use_stab = use_aux;
+ if constexpr (PAIR)
+ {
+ e2m1p = reinterpret_cast<float2*>(xs + K);
+ if (use_stab)
+ {
+ stab = reinterpret_cast<float*>(e2m1p + 256);
+ red = reinterpret_cast<float*>(stab + 256);
+ }
+ else
+ red = reinterpret_cast<float*>(e2m1p + 256);
+ }
+ else if (use_stab)
+ {
+ stab = reinterpret_cast<float*>(xs + K);
+ red = reinterpret_cast<float*>(stab + 256);
+ }
+ else
+ red = reinterpret_cast<float*>(xs + K);
+ }
+ else
+ red = reinterpret_cast<float*>(xs + K); // 8*32 floats
+
+ __shared__ fq_tables_sh tab;
+ fq_tables_load(&tab, FMT == 2, FMT == 1);
+ fq_stage_x<IN>(x + (int64_t)m * K, xs, K);
+ if constexpr (FMT == 1)
+ fq_stage_iq2_hdrs(packed, packed_stride, hdrs, nb1,
+ t * FQ_GEMV_OUT_PER_BLOCK, N);
+ if constexpr (FMT == 2 && PAIR)
+ fq_e2m1p_build(e2m1p);
+ if (use_stab)
+ fq_e2m1s_build(stab, global);
+ __syncthreads();
+
+ float acc = 0.0f;
+ if (n < N)
+ {
+ if constexpr (FMT == 0)
+ acc = fq_dot_q8_0(packed + (int64_t)n * packed_stride, xs, K, lane);
+ else if constexpr (FMT == 1)
+ acc = fq_dot_iq2_xxs(packed + (int64_t)n * packed_stride, xs, &tab,
+ hdrs + (int64_t)grp * nb1 * 16, K, lane);
+ else
+ {
+ const uint8_t* row = packed + (int64_t)n * packed_stride;
+ const uint8_t* srow = scales + (int64_t)n * scales_stride;
+ if (use_stab)
+ acc = fq_dot_nvfp4<PAIR, true>(row, srow, xs, &tab, e2m1p,
+ stab, K, lane, global);
+ else
+ acc = fq_dot_nvfp4<PAIR, false>(row, srow, xs, &tab, e2m1p,
+ nullptr, K, lane, global);
+ }
+ }
+ red[threadIdx.x] = acc;
+ __syncthreads();
+ // Lane 0 of each group sums its 32 partials (sequential, portable).
+ if (n < N && lane == 0)
+ {
+ float s = 0.0f;
+ #pragma unroll
+ for (int l = 0; l < 32; l++)
+ s = __fadd_rn(s, red[grp * 32 + l]);
+ if constexpr (std::is_same<OUT, __half>::value)
+ out[(int64_t)m * N + n] = __float2half_rn(s);
+ else
+ out[(int64_t)m * N + n] = s;
+ }
+}
+
+template <int FMT>
+static void fq_gemv_q(torch::Tensor x, torch::Tensor packed, torch::Tensor scales,
+ double global_scale, torch::Tensor out, bool pair = false)
+{
+ TORCH_CHECK(x.is_cuda() && packed.is_cuda() && out.is_cuda(), "tensors must be CUDA");
+ TORCH_CHECK(x.is_contiguous() && packed.is_contiguous() && out.is_contiguous(),
+ "tensors must be contiguous");
+ TORCH_CHECK(x.dtype() == torch::kHalf || x.dtype() == torch::kFloat, "x must be half or float");
+ TORCH_CHECK(out.dtype() == torch::kHalf || out.dtype() == torch::kFloat,
+ "out must be half or float");
+ TORCH_CHECK_DIM(x, 2);
+ TORCH_CHECK_DIM(out, 2);
+ int M = (int)x.size(0), K = (int)x.size(1), N = (int)out.size(1);
+ TORCH_CHECK((int)out.size(0) == M, "out rows must match x rows");
+ TORCH_CHECK(M >= 1 && M <= 16, "fast GEMV covers M = 1..16");
+ int64_t pstride = 0, sstride = 0;
+ if constexpr (FMT == 0)
+ {
+ TORCH_CHECK_DIM(packed, 3);
+ TORCH_CHECK(K % FQ_Q8_0_GROUP == 0, "K must be a multiple of 32");
+ TORCH_CHECK_SIZE(packed, 2, FQ_Q8_0_BYTES);
+ TORCH_CHECK((int)packed.size(0) == N && (int)packed.size(1) == K / FQ_Q8_0_GROUP,
+ "packed must be [N, K/32, 34]");
+ pstride = (int64_t)(K / FQ_Q8_0_GROUP) * FQ_Q8_0_BYTES;
+ }
+ else if constexpr (FMT == 1)
+ {
+ TORCH_CHECK_DIM(packed, 3);
+ TORCH_CHECK(K % FQ_IQ2_XXS_GROUP == 0, "K must be a multiple of 256");
+ TORCH_CHECK(K <= 8192, "IQ2 header scratch covers K <= 8192");
+ TORCH_CHECK_SIZE(packed, 2, FQ_IQ2_XXS_BYTES);
+ TORCH_CHECK((int)packed.size(0) == N && (int)packed.size(1) == K / FQ_IQ2_XXS_GROUP,
+ "packed must be [N, K/256, 66]");
+ pstride = (int64_t)(K / FQ_IQ2_XXS_GROUP) * FQ_IQ2_XXS_BYTES;
+ }
+ else
+ {
+ TORCH_CHECK_DIM(packed, 2);
+ TORCH_CHECK_DIM(scales, 2);
+ TORCH_CHECK(K % FQ_NVFP4_GROUP == 0, "K must be a multiple of 16");
+ TORCH_CHECK((int)packed.size(0) == N && (int)packed.size(1) == K / 2, "packed must be [N, K/2]");
+ TORCH_CHECK((int)scales.size(0) == N && (int)scales.size(1) == K / 16, "scales must be [N, K/16]");
+ // v4 consecutive dot: E = K/32 elements per lane must be a multiple
+ // of 16 (one scale group) and even (half2 x reads, no k<K guards).
+ TORCH_CHECK(K % 64 == 0, "NVFP4 GEMV needs K a multiple of 64");
+ pstride = K / 2;
+ sstride = K / 16;
+ }
+ at::cuda::CUDAGuard guard(x.device());
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ int ntiles = (N + FQ_GEMV_OUT_PER_BLOCK - 1) / FQ_GEMV_OUT_PER_BLOCK;
+ size_t shmem = (size_t)K * sizeof(__half) + FQ_GEMV_THREADS * sizeof(float);
+ if constexpr (FMT == 1)
+ shmem += (size_t)8 * (K / FQ_IQ2_XXS_GROUP) * 16 * sizeof(uint32_t);
+ if constexpr (FMT == 2)
+ {
+ if (pair)
+ shmem += (size_t)256 * sizeof(float2);
+ if (fq_use_stab())
+ shmem += (size_t)256 * sizeof(float);
+ }
+ const uint8_t* sc = nullptr;
+ if constexpr (FMT == 2)
+ sc = scales.data_ptr<uint8_t>();
+ // Read once per launch (host): the kernel gets it as a uniform arg.
+ bool use_aux = (FMT == 2) ? fq_use_stab() : false;
+ auto launch = [&](auto* xp, auto* op, bool pr)
+ {
+ if constexpr (FMT == 2)
+ {
+ if (pr)
+ fq_gemv_kernel<FMT, std::decay_t<decltype(*xp)>, std::decay_t<decltype(*op)>, true>
+ <<<M * ntiles, FQ_GEMV_THREADS, shmem, stream>>>(
+ xp, packed.data_ptr<uint8_t>(), sc, (float)global_scale,
+ op, M, N, K, pstride, sstride, use_aux);
+ else
+ fq_gemv_kernel<FMT, std::decay_t<decltype(*xp)>, std::decay_t<decltype(*op)>, false>
+ <<<M * ntiles, FQ_GEMV_THREADS, shmem, stream>>>(
+ xp, packed.data_ptr<uint8_t>(), sc, (float)global_scale,
+ op, M, N, K, pstride, sstride, use_aux);
+ }
+ else
+ fq_gemv_kernel<FMT, std::decay_t<decltype(*xp)>, std::decay_t<decltype(*op)>>
+ <<<M * ntiles, FQ_GEMV_THREADS, shmem, stream>>>(
+ xp, packed.data_ptr<uint8_t>(), sc, (float)global_scale,
+ op, M, N, K, pstride, sstride, use_aux);
+ };
+ if (x.dtype() == torch::kHalf && out.dtype() == torch::kHalf)
+ launch(reinterpret_cast<const __half*>(x.data_ptr<at::Half>()),
+ reinterpret_cast<__half*>(out.data_ptr<at::Half>()), pair);
+ else if (x.dtype() == torch::kHalf)
+ launch(reinterpret_cast<const __half*>(x.data_ptr<at::Half>()),
+ out.data_ptr<float>(), pair);
+ else if (out.dtype() == torch::kHalf)
+ launch(x.data_ptr<float>(), reinterpret_cast<__half*>(out.data_ptr<at::Half>()), pair);
+ else
+ launch(x.data_ptr<float>(), out.data_ptr<float>(), pair);
+}
+
+} // namespace
+
+void fq_gemv_q8_0(torch::Tensor x, torch::Tensor packed, torch::Tensor out)
+{
+ if (fq_use_q8q8())
+ {
+ // q8_1-activation path: quantize once per row, integer dp4a dots.
+ TORCH_CHECK((int)x.size(1) % FQ_Q8_1_GROUP == 0, "K must be a multiple of 32");
+ int M = (int)x.size(0), K = (int)x.size(1);
+ torch::Tensor qb = fq_q8_scratch(x.get_device(), M, K);
+ fq_quant_q8_1_rows(x, qb);
+ fq_gemv_q8_0_q8(qb, packed, out);
+ return;
+ }
+ fq_gemv_q<0>(x, packed, {}, 1.0, out);
+}
+
+void fq_gemv_iq2_xxs(torch::Tensor x, torch::Tensor packed, torch::Tensor out)
+{
+ if (fq_use_q8act())
+ {
+ // q8_1-activation path: quantize once per row, integer dp4a dots.
+ TORCH_CHECK((int)x.size(1) % FQ_Q8_1_GROUP == 0, "K must be a multiple of 32");
+ int M = (int)x.size(0), K = (int)x.size(1);
+ torch::Tensor qb = fq_q8_scratch(x.get_device(), M, K);
+ fq_quant_q8_1_rows(x, qb);
+ fq_gemv_iq2_xxs_q8(qb, packed, out);
+ return;
+ }
+ fq_gemv_q<1>(x, packed, {}, 1.0, out);
+}
+
+void fq_gemv_nvfp4(torch::Tensor x, torch::Tensor packed, torch::Tensor scales, double global_scale,
+ torch::Tensor out, bool pair)
+{
+ if (fq_use_q8nv())
+ {
+ // q8_1-activation path: quantize once per row, integer dp4a dots.
+ int K = (int)x.size(1);
+ TORCH_CHECK(K % FQ_Q8_1_GROUP == 0, "K must be a multiple of 32");
+ int M = (int)x.size(0);
+ torch::Tensor qb = fq_q8_scratch(x.get_device(), M, K);
+ fq_quant_q8_1_rows(x, qb);
+ fq_gemv_nvfp4_q8(qb, packed, scales, global_scale, out);
+ return;
+ }
+ fq_gemv_q<2>(x, packed, scales, global_scale, out, pair);
+}
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_gemv.cuh b/exllamav3/exllamav3_ext/foreign_quant/fq_gemv.cuh
new file mode 100644
index 0000000..96ebcd7
--- /dev/null
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_gemv.cuh
@@ -0,0 +1,1147 @@
+// Shared device-inline helpers for the foreign-quant decode kernels
+// (fq_gemv.cu standalone GEMV, fq_moe.cu grouped MoE): x staging, lane dot
+// products per format, shared-memory codebooks. See fq_gemv.cu for the
+// design rationale (cooperative decode GEMV) and portability contract
+// (no PTX, no warp shuffles, __fmul_rn/__fadd_rn only).
+#pragma once
+
+#include <cstdlib>
+#include <cuda_fp16.h>
+#include "fq_dequant.cuh"
+
+namespace {
+
+// Same-binary A/B switch (read per launch, so one process can interleave
+// arms by flipping the env var): BOLT_FQ_STAB=0 restores the per-pair NVFP4
+// gs multiply. Default on.
+inline bool fq_use_stab()
+{
+ const char* e = std::getenv("BOLT_FQ_STAB");
+ return !e || e[0] != '0';
+}
+
+// q8_1-activation decode path (Bolt phase 2: port of the llama.cpp mmvq
+// design). Default ON (gates passed: exact-arithmetic, KLD rule,
+// e2e coherence): BOLT_FQ_Q8ACT=0 restores the fp32 IQ2_XXS dots,
+// BOLT_FQ_Q8NV=0 the fp32 NVFP4 dots, BOLT_FQ_Q8Q8=0 the fp32 Q8_0 dots.
+// Separate flags so one binary A/Bs each format independently.
+inline bool fq_use_q8act()
+{
+ const char* e = std::getenv("BOLT_FQ_Q8ACT");
+ return !e || e[0] != '0';
+}
+
+inline bool fq_use_q8nv()
+{
+ const char* e = std::getenv("BOLT_FQ_Q8NV");
+ return !e || e[0] != '0';
+}
+
+inline bool fq_use_q8q8()
+{
+ const char* e = std::getenv("BOLT_FQ_Q8Q8");
+ return !e || e[0] != '0';
+}
+
+// v2 IQ2_XXS q8 dot (mirrors ggml vec_dot_iq2_xxs_q8_1 exactly): grid
+// from __constant__ (like llama's iq2xxs_grid: 4 const u64 loads per
+// 32-elem chunk, fully cached 2 KB table), signs unpacked inline,
+// headers via direct u16 loads (2-aligned like ggml get_int_b2, no
+// staging). Drops the v1 header staging + signs32 table build + 2
+// barriers and the 18 bank-conflicted shared loads per chunk (SASS:
+// v1 executes ~1.76x llama's per-row instructions). Default on;
+// BOLT_FQ_Q8V2=0 restores the v1 dot for same-binary A/B.
+inline bool fq_use_q8v2()
+{
+ const char* e = std::getenv("BOLT_FQ_Q8V2");
+ return !e || e[0] != '0';
+}
+
+// Experiment knob: BOLT_FQ_Q8NT2=1 halves the row-per-block
+// IQ2 thread count (2 chunks per thread: better latency hiding + less
+// const-cache pressure at large nt). Same-binary A/B with full nt.
+// (Grouped MoE keeps its fixed 256-thread tiles; only the row-per-block
+// IQ2 launches use this.)
+inline int fq_q8_nt_iq2(int K)
+{
+ int nchunks = K / 32;
+ int nt = nchunks >= 256 ? 256 : ((nchunks + 31) / 32) * 32;
+ const char* e = std::getenv("BOLT_FQ_Q8NT2");
+ if (e && e[0] == '1')
+ nt = nt > 32 ? nt / 2 : nt;
+ return nt;
+}
+
+// Portable 4-way int8 dot-product-accumulate. CUDA: __dp4a (all our targets
+// are SM >= 61). HIP/other: widening scalar fallback (same values, no PTX,
+// no asm; mirrors llama.cpp ggml_cuda_dp4a's fallback arm).
+__device__ __forceinline__ int fq_dp4a(int a, int b, int c)
+{
+#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 610
+ return __dp4a(a, b, c);
+#else
+ const int8_t* a8 = reinterpret_cast<const int8_t*>(&a);
+ const int8_t* b8 = reinterpret_cast<const int8_t*>(&b);
+ return c + (int)a8[0] * (int)b8[0] + (int)a8[1] * (int)b8[1] +
+ (int)a8[2] * (int)b8[2] + (int)a8[3] * (int)b8[3];
+#endif
+}
+
+// q8_1 block geometry (ggml block_q8_1: half d, half s, 32 int8).
+#define FQ_Q8_1_GROUP 32
+#define FQ_Q8_1_BYTES 36
+
+// 8 outputs per block, 32 lanes per output, 256 threads per block.
+#define FQ_GEMV_OUT_PER_BLOCK 8
+#define FQ_GEMV_LANES 32
+#define FQ_GEMV_THREADS (FQ_GEMV_OUT_PER_BLOCK * FQ_GEMV_LANES)
+
+// Stage one x row (half or float in) to shared half. Vectorized float4 path
+// when K is a multiple of 8, scalar tail otherwise.
+template <typename IN>
+__device__ void fq_stage_x(const IN* __restrict__ xr, __half* __restrict__ xs, int K)
+{
+ int tid = threadIdx.x;
+ if (K % 8 == 0)
+ {
+ int nv = K / 8;
+ if constexpr (std::is_same<IN, __half>::value)
+ {
+ const float4* v = reinterpret_cast<const float4*>(xr);
+ float4* d = reinterpret_cast<float4*>(xs);
+ for (int i = tid; i < nv; i += blockDim.x)
+ d[i] = v[i];
+ }
+ else
+ {
+ const float* f = reinterpret_cast<const float*>(xr);
+ for (int i = tid; i < nv; i += blockDim.x)
+ {
+ __half h[8];
+ #pragma unroll
+ for (int j = 0; j < 8; j++)
+ h[j] = __float2half_rn(f[i * 8 + j]);
+ reinterpret_cast<float4*>(xs)[i] =
+ reinterpret_cast<const float4*>(h)[0];
+ }
+ }
+ }
+ else
+ {
+ for (int i = tid; i < K; i += blockDim.x)
+ {
+ if constexpr (std::is_same<IN, __half>::value)
+ xs[i] = xr[i];
+ else
+ xs[i] = __float2half_rn(xr[i]);
+ }
+ }
+}
+
+// Small codebooks staged in shared memory per block (loaded once,
+// cooperatively). They MUST NOT stay in __constant__ memory: every lane of a
+// group reads a different entry (nibbles / grid indices diverge), and the
+// constant cache serializes divergent addresses, while shared memory serves
+// them at full speed (measured: NVFP4 mamba_in 474 -> ~70us).
+struct fq_tables_sh
+{
+ // e2m1 replicated 4x (same value at nib<<2|c for c in 0..3): a warp's
+ // 32 divergent nibble reads spread over 64 banks instead of piling on
+ // 16 (measured NVFP4 at 211 GB/s vs Q8 485 GB/s on the same shape).
+ float e2m1[64];
+ uint32_t e4m3[256];
+ uint64_t grid[256];
+ uint8_t signs[128];
+ uint8_t kmask[8];
+};
+
+__device__ void fq_tables_load(fq_tables_sh* t, int need_e2m1_e4m3, int need_iq2)
+{
+ int tid = threadIdx.x;
+ if (need_e2m1_e4m3)
+ {
+ for (int i = tid; i < 64; i += blockDim.x)
+ t->e2m1[i] = FQ_E2M1_LUT[i >> 2]; // index (nib<<2)|rep -> LUT[nib]
+ for (int i = tid; i < 256; i += blockDim.x)
+ t->e4m3[i] = FQ_E4M3_BITS[i];
+ }
+ if (need_iq2)
+ {
+ for (int i = tid; i < 256; i += blockDim.x)
+ t->grid[i] = FQ_IQ2XXS_GRID[i];
+ for (int i = tid; i < 128; i += blockDim.x)
+ t->signs[i] = FQ_KSIGNS_IQ2XS[i];
+ if (tid < 8)
+ t->kmask[tid] = FQ_KMASK_IQ2XS[tid];
+ }
+}
+
+// Q8_0 lane dot: blocks of 32, lane l takes elements l (mod 32). No table
+// lookups (weight = int8 * scale), so nothing to stage. Four independent
+// scalar accumulators over strided blocks (b = c mod 4): one chain stalls
+// on the FMA + cvt latency every element; four chains keep independent
+// FMAs in flight. Scalars, not acc[b&3]: dynamic array indexing spills to
+// local memory. Values identical, summation order differs (fp16 tol).
+__device__ float fq_dot_q8_0(const uint8_t* __restrict__ wr, const __half* __restrict__ xs,
+ int K, int lane)
+{
+ float acc0 = 0.0f, acc1 = 0.0f, acc2 = 0.0f, acc3 = 0.0f;
+ int nb = K / 32;
+ for (int b = 0; b < nb; b++)
+ {
+ const uint8_t* blk = wr + b * 34;
+ __half dh;
+ memcpy(&dh, blk, 2);
+ float d = __half2float(dh);
+ float w = __fmul_rn((float)((int8_t)blk[2 + lane]), d);
+ float p = __fmul_rn(__half2float(xs[b * 32 + lane]), w);
+ int c = b & 3;
+ if (c == 0) acc0 = __fadd_rn(acc0, p);
+ else if (c == 1) acc1 = __fadd_rn(acc1, p);
+ else if (c == 2) acc2 = __fadd_rn(acc2, p);
+ else acc3 = __fadd_rn(acc3, p);
+ }
+ return __fadd_rn(__fadd_rn(acc0, acc1), __fadd_rn(acc2, acc3));
+}
+
+// Cooperatively stage a block's IQ2_XXS headers to shared: 8 groups x
+// nb*16 u32 (the 64 q bytes of every 256-wide block for each of the 8
+// output rows this block computes; scales excluded). Called in the kernel
+// prologue before the consuming __syncthreads, so it adds no sync of its
+// own. Rows past N are clamped to row 0 (callers' dots are n-guarded, so
+// the clamp data is never consumed and no OOB read is possible).
+// (The u32 source is generally misaligned, so plain LDG.U32 would fault;
+// the staging loop moves ~nb u32 per thread and is off the hot path.)
+__device__ void fq_stage_iq2_hdrs(const uint8_t* __restrict__ packed, int64_t stride,
+ uint32_t* __restrict__ hdrs, int nb, int n0, int N)
+{
+ int tid = threadIdx.x;
+ int per = nb * 16;
+ for (int i = tid; i < 8 * per; i += FQ_GEMV_THREADS)
+ {
+ int g = i / per;
+ int j = i % per;
+ int n = (n0 + g < N) ? n0 + g : 0;
+ uint32_t v;
+ memcpy(&v, packed + (int64_t)n * stride + (j >> 4) * 66 + 2 + (j & 15) * 4, 4);
+ hdrs[i] = v;
+ }
+}
+
+// Single-row variant for the row-per-block q8 kernels (stages one row's
+// headers: nb*16 u32). Same misalignment-safe memcpy loads as above.
+__device__ void fq_stage_iq2_hdrs_row(const uint8_t* __restrict__ packed, int64_t stride,
+ uint32_t* __restrict__ hdrs, int nb, int n, int N)
+{
+ int tid = threadIdx.x;
+ int per = nb * 16;
+ int nn = (n < N) ? n : 0;
+ for (int j = tid; j < per; j += blockDim.x)
+ {
+ uint32_t v;
+ memcpy(&v, packed + (int64_t)nn * stride + (j >> 4) * 66 + 2 + (j & 15) * 4, 4);
+ hdrs[j] = v;
+ }
+}
+
+// IQ2_XXS lane dot, v4: block headers (a0/a1/db source bytes) come from
+// the cooperatively staged shared hdrs instead of per-lane global byte
+// loads. SASS showed the old dot at ~220 instructions per 8-element
+// block step, ~64 of them LDG.E.U8 + ~40 address/shift/combine ops, ALL
+// redundantly executed by all 32 lanes for the same 8 bytes (the q chunk
+// is lane-invariant by construction of the ib-outer layout). Staging
+// loads each header byte once per block (coalesced, 1 u32 per thread at
+// K=4096) and every lane reads a0/a1 as uniform shared broadcasts.
+// Hoisted: elle/jj, kmask[jj], d*0.25; grid magnitude is a shared byte
+// index (v3). Values identical, summation order differs (fp16 tol).
+// (Step-10 negative: hoisting the uniform db = d4*(0.5+(a1>>28)) into a
+// prologue table measured +9-17% slower -- the extra shared load sits on
+// the dot's critical path at these occupancies. Reverted.)
+__device__ float fq_dot_iq2_xxs(const uint8_t* __restrict__ wr, const __half* __restrict__ xs,
+ const fq_tables_sh* __restrict__ tab,
+ const uint32_t* __restrict__ hdrs, int K, int lane)
+{
+ float acc0 = 0.0f, acc1 = 0.0f, acc2 = 0.0f, acc3 = 0.0f;
+ float acc4 = 0.0f, acc5 = 0.0f, acc6 = 0.0f, acc7 = 0.0f;
+ int elle = lane >> 3, jj = lane & 7;
+ uint8_t mask = tab->kmask[jj];
+ const uint8_t* grid8 = reinterpret_cast<const uint8_t*>(tab->grid);
+ int nb = K / 256;
+ for (int b = 0; b < nb; b++)
+ {
+ const uint8_t* blk = wr + b * 66;
+ __half dh;
+ memcpy(&dh, blk, 2);
+ float d4 = __fmul_rn(__half2float(dh), 0.25f);
+ const __half* xsb = xs + b * 256;
+ const uint32_t* hb = hdrs + b * 16;
+ for (int ib = 0; ib < 8; ib++)
+ {
+ uint32_t a0 = hb[ib * 2], a1 = hb[ib * 2 + 1];
+ float db = __fmul_rn(d4, 0.5f + (float)(a1 >> 28));
+ // The magnitude is the raw grid byte (idx, jj): one shared
+ // byte load instead of u64 load + shift + mask.
+ float mag = (float)grid8[(((a0 >> (8 * elle)) & 0xFF) << 3) + jj];
+ uint8_t signs = tab->signs[(a1 >> (7 * elle)) & 127];
+ float w = __fmul_rn(__fmul_rn(db, mag), (signs & mask) ? -1.0f : 1.0f);
+ float p = __fmul_rn(__half2float(xsb[(ib << 5) + lane]), w);
+ if (ib == 0) acc0 = __fadd_rn(acc0, p);
+ else if (ib == 1) acc1 = __fadd_rn(acc1, p);
+ else if (ib == 2) acc2 = __fadd_rn(acc2, p);
+ else if (ib == 3) acc3 = __fadd_rn(acc3, p);
+ else if (ib == 4) acc4 = __fadd_rn(acc4, p);
+ else if (ib == 5) acc5 = __fadd_rn(acc5, p);
+ else if (ib == 6) acc6 = __fadd_rn(acc6, p);
+ else acc7 = __fadd_rn(acc7, p);
+ }
+ }
+ return __fadd_rn(__fadd_rn(__fadd_rn(acc0, acc1), __fadd_rn(acc2, acc3)),
+ __fadd_rn(__fadd_rn(acc4, acc5), __fadd_rn(acc6, acc7)));
+}
+
+// NVFP4 lane dot, v4: 64-k steps over CONSECUTIVE k (step s covers
+// [64s, 64s+64); lane l takes the pair (64s+2l, 64s+2l+1)) instead of the
+// v2/v3 strided layout. Consecutive pairs make the warp's x/pr reads fully
+// coalesced (a strided consecutive-per-lane layout put every lane in one
+// shared bank: 32-way conflicts, 2.4x slower), each pr byte serve its
+// natural even/odd pair, x be read as half2, and each 16-wide scale group
+// share one broadcast e4m3 read. The E2M1 codebook stays in shared (a
+// register lut[] indexed by a runtime nibble would spill to local memory)
+// with the v2 4x replica bank spread. Eight scalar accumulators over steps
+// (s uniform across the warp, so the select is straight-line); values
+// identical to v3, summation order differs (fp16 tol).
+// NVFP4 E2M1 pair table: 256 float2 entries built cooperatively straight
+// from the __constant__ codebook (no dependency on the shared e2m1, so no
+// extra __syncthreads needed before the existing one; the 2 constant reads
+// per thread sit in the prologue, amortized over the whole dot).
+// Entry [byte] = (e2m1[lo nibble], e2m1[hi nibble]) unscaled; the per-step
+// scale gs multiplies after. One shared load + zero index ALU per pair
+// instead of two replicated-e2m1 loads + nibble extract/index math.
+// No 4x replica (the full byte index spreads naturally); +2 KB dynamic
+// shared for FMT==2 only, occupancy-neutral on Bolt shapes.
+__device__ void fq_e2m1p_build(float2* __restrict__ dst)
+{
+ int tid = threadIdx.x;
+ for (int b = tid; b < 256; b += FQ_GEMV_THREADS)
+ {
+ float lo = FQ_E2M1_LUT[b & 0xF];
+ float hi = FQ_E2M1_LUT[(b >> 4) & 0xF];
+ dst[b] = make_float2(lo, hi);
+ }
+}
+
+// NVFP4 scaled-e4m3 table: stab[i] = e4m3_float[i] * global, 256 entries
+// built cooperatively straight from the __constant__ codebook (no
+// dependency on shared state, so no extra __syncthreads; 256 threads do
+// one entry each, amortized over the whole dot). The per-launch-uniform
+// `global` multiply moves from every pair (one FMUL per 2 elements) into
+// the prologue; the dot then pays one shared broadcast load per pair
+// instead of (sr byte load + e4m3 load + FMUL). Same FMUL with the same
+// operands, so gs (and the output) is bit-identical.
+__device__ void fq_e2m1s_build(float* __restrict__ dst, float global)
+{
+ int tid = threadIdx.x;
+ if (tid < 256)
+ dst[tid] = __fmul_rn(__uint_as_float(FQ_E4M3_BITS[tid]), global);
+}
+
+// One 64-k step of the v4 NVFP4 dot: lane l's pair
+// (elements 64s+2l, 64s+2l+1) -> partial dot. Split out so the main loop
+// can unroll 8 straight-line steps (one per accumulator, no select).
+// STAB selects the gs source at compile time: true = prologue
+// scaled-e4m3 table (BOLT_FQ_STAB=1), false = e4m3 load + global FMUL.
+// Bit-identical either way; the template keeps each arm clean.
+template <bool PAIR, bool STAB>
+__device__ float fq_nvfp4_pair(const uint8_t* __restrict__ pr, const uint8_t* __restrict__ sr,
+ const half2* __restrict__ x2,
+ const fq_tables_sh* __restrict__ tab,
+ const float2* __restrict__ e2m1p,
+ const float* __restrict__ stab,
+ int s, int lane, float global)
+{
+ // Lane l's pair = byte/pr index 32s+l (consecutive across the warp).
+ int bi = (s << 5) + lane;
+ uint8_t pbyte = pr[bi];
+ float2 xv = __half22float2(x2[bi]);
+ // 4 unique scale bytes per step across the warp; shared broadcast.
+ uint8_t sc = sr[(s << 2) + (lane >> 3)];
+ float gs;
+ if constexpr (STAB)
+ gs = stab[sc];
+ else
+ gs = __fmul_rn(__uint_as_float(tab->e4m3[sc]), global);
+ float w0, w1;
+ if constexpr (PAIR)
+ {
+ float2 w = e2m1p[pbyte];
+ w0 = __fmul_rn(w.x, gs);
+ w1 = __fmul_rn(w.y, gs);
+ }
+ else
+ {
+ int rep = lane & 3;
+ w0 = __fmul_rn(tab->e2m1[((pbyte & 0xF) << 2) | rep], gs);
+ w1 = __fmul_rn(tab->e2m1[(((pbyte >> 4) & 0xF) << 2) | rep], gs);
+ }
+ return __fadd_rn(__fmul_rn(xv.x, w0), __fmul_rn(xv.y, w1));
+}
+
+template <bool PAIR, bool STAB>
+__device__ float fq_dot_nvfp4(const uint8_t* __restrict__ pr, const uint8_t* __restrict__ sr,
+ const __half* __restrict__ xs,
+ const fq_tables_sh* __restrict__ tab,
+ const float2* __restrict__ e2m1p,
+ const float* __restrict__ stab,
+ int K, int lane, float global)
+{
+ float acc0 = 0.0f, acc1 = 0.0f, acc2 = 0.0f, acc3 = 0.0f;
+ float acc4 = 0.0f, acc5 = 0.0f, acc6 = 0.0f, acc7 = 0.0f;
+ int S = K >> 6; // 64-k steps (K a multiple of 64)
+ const half2* __restrict__ x2 = reinterpret_cast<const half2*>(xs);
+ // Full chunks of 8 steps: straight-line, one accumulator each.
+ int S8 = S & ~7;
+ for (int s0 = 0; s0 < S8; s0 += 8)
+ {
+ acc0 = __fadd_rn(acc0, fq_nvfp4_pair<PAIR, STAB>(pr, sr, x2, tab, e2m1p, stab, s0 + 0, lane, global));
+ acc1 = __fadd_rn(acc1, fq_nvfp4_pair<PAIR, STAB>(pr, sr, x2, tab, e2m1p, stab, s0 + 1, lane, global));
+ acc2 = __fadd_rn(acc2, fq_nvfp4_pair<PAIR, STAB>(pr, sr, x2, tab, e2m1p, stab, s0 + 2, lane, global));
+ acc3 = __fadd_rn(acc3, fq_nvfp4_pair<PAIR, STAB>(pr, sr, x2, tab, e2m1p, stab, s0 + 3, lane, global));
+ acc4 = __fadd_rn(acc4, fq_nvfp4_pair<PAIR, STAB>(pr, sr, x2, tab, e2m1p, stab, s0 + 4, lane, global));
+ acc5 = __fadd_rn(acc5, fq_nvfp4_pair<PAIR, STAB>(pr, sr, x2, tab, e2m1p, stab, s0 + 5, lane, global));
+ acc6 = __fadd_rn(acc6, fq_nvfp4_pair<PAIR, STAB>(pr, sr, x2, tab, e2m1p, stab, s0 + 6, lane, global));
+ acc7 = __fadd_rn(acc7, fq_nvfp4_pair<PAIR, STAB>(pr, sr, x2, tab, e2m1p, stab, s0 + 7, lane, global));
+ }
+ // Remainder steps (S < 8 shapes, e.g. the K=256 E4M3 sweep).
+ for (int s = S8; s < S; s++)
+ {
+ float p = fq_nvfp4_pair<PAIR, STAB>(pr, sr, x2, tab, e2m1p, stab, s, lane, global);
+ int a = s & 7;
+ if (a == 0) acc0 = __fadd_rn(acc0, p);
+ else if (a == 1) acc1 = __fadd_rn(acc1, p);
+ else if (a == 2) acc2 = __fadd_rn(acc2, p);
+ else if (a == 3) acc3 = __fadd_rn(acc3, p);
+ else if (a == 4) acc4 = __fadd_rn(acc4, p);
+ else if (a == 5) acc5 = __fadd_rn(acc5, p);
+ else if (a == 6) acc6 = __fadd_rn(acc6, p);
+ else acc7 = __fadd_rn(acc7, p);
+ }
+ return __fadd_rn(__fadd_rn(__fadd_rn(acc0, acc1), __fadd_rn(acc2, acc3)),
+ __fadd_rn(__fadd_rn(acc4, acc5), __fadd_rn(acc6, acc7)));
+}
+
+// ---- q8_1-activation decode path (Bolt phase 2) ----
+//
+// Port of the llama.cpp mmvq design: activations are quantized once per
+// (row) to q8_1 blocks (int8 + fp16 scale, same arithmetic as ggml's
+// quantize_q8_1: d = amax/127, q = round-half-away(xi/d)), then each
+// weight dot is an INTEGER dp4a accumulate with ONE float scale per
+// 32-elem chunk (same op order as ggml vec_dot_*_q8_1). ~10-20x fewer
+// instructions per element than the per-element fp32 dequant dots above.
+//
+// Thread mapping (row-per-block kernels below): thread tid takes 32-elem
+// chunks c = tid, tid+NT, ... (NT = blockDim.x). All 4-element groups
+// inside a chunk stay within one 32-block, so int32 activation loads
+// never span blocks and weight grid/sign bytes are consecutive.
+
+// One 32-block of a row: amax, scale, round-half-away quantize, store.
+// Matches ggml quantize_q8_1 (d = amax/127, q = amax==0 ? 0 : round(xi/d),
+// ds = (d, sum)). NOTE: kept for documentation; the live quant kernel
+// (fq_gemv_q8.cu) inlines its own per-thread loops. If you revive this,
+// store dh/sh with single u16 stores, NOT memcpy (the memcpy byte-split
+// store pattern loses the low byte with this toolchain, see phase-2 log).
+template <typename IN>
+__device__ void fq_quant_q8_1_block(const IN* __restrict__ xr, uint8_t* __restrict__ qb,
+ int K)
+{
+ int tid = threadIdx.x;
+ int nb32 = K / FQ_Q8_1_GROUP;
+ for (int b = tid; b < nb32; b += blockDim.x)
+ {
+ float amax = 0.0f, sum = 0.0f;
+ for (int i = 0; i < 32; i++)
+ {
+ float v;
+ if constexpr (std::is_same<IN, __half>::value)
+ v = __half2float(xr[b * 32 + i]);
+ else
+ v = xr[b * 32 + i];
+ float a = fabsf(v);
+ amax = fmaxf(amax, a);
+ sum += v;
+ }
+ float d = amax / 127.0f;
+ uint8_t* blk = qb + (size_t)b * FQ_Q8_1_BYTES;
+ __half dh = __float2half_rn(d);
+ __half sh = __float2half_rn(sum);
+ memcpy(blk, &dh, 2);
+ memcpy(blk + 2, &sh, 2);
+ #pragma unroll
+ for (int i = 0; i < 32; i++)
+ {
+ float v;
+ if constexpr (std::is_same<IN, __half>::value)
+ v = __half2float(xr[b * 32 + i]);
+ else
+ v = xr[b * 32 + i];
+ // roundf = round-half-away, like ggml's quantize_q8_1.
+ int q = (amax == 0.0f) ? 0 : (int)roundf(v / d);
+ q = q < -127 ? -127 : (q > 127 ? 127 : q);
+ blk[4 + i] = (uint8_t)(int8_t)q;
+ }
+ }
+}
+
+// Expanded IQ2_XXS sign table for the q8 dot: signs32[i][h] holds the 4
+// sign bytes (0x00/0xFF) for sign-index i and jj-half h (jj = 4h..4h+3),
+// built cooperatively in the prologue from the staged signs table
+// (kmask[jj] = 1<<jj single-bit selects). 256 entries; the q8 kernels run
+// 32..256 threads, so loop (a bare `tid < 256` guard leaves entries
+// unwritten at small NT).
+__device__ void fq_signs32_build(const fq_tables_sh* __restrict__ tab,
+ uint32_t* __restrict__ s32)
+{
+ int tid = threadIdx.x;
+ for (int e = tid; e < 256; e += blockDim.x)
+ {
+ int i = e >> 1, h = e & 1;
+ uint32_t S = tab->signs[i];
+ uint32_t v = 0;
+ #pragma unroll
+ for (int m = 0; m < 4; m++)
+ {
+ uint32_t bit = (S >> (4 * h + m)) & 1u;
+ // Mask to one byte: (0u-bit) is 0x00000000/0xFFFFFFFF.
+ v |= ((0u - bit) & 0xFFu) << (8 * m);
+ }
+ s32[e] = v;
+ }
+}
+
+// ksigns unpack for the v2 IQ2 q8 dot: verbatim ggml unpack_ksigns
+// (vecdotq.cuh): v is the 7-bit sign index, the 8th sign rides the
+// parity bit. Broadcast over u32 so the 0x08040201/0x80402010 masks
+// select one sign bit per byte. Portable scalar ALU.
+__device__ __forceinline__ uint32_t fq_unpack_ksigns(uint8_t v)
+{
+ uint32_t p = (uint32_t)__popc((unsigned int)v) & 1u;
+ uint32_t s = (uint32_t)v ^ (p << 7);
+ return s * 0x01010101u;
+}
+
+// Per-byte != 0 expand (0xFF where set, 0x00 where clear). CUDA: the
+// __vcmpne4 video-SIMD builtin (1 insn; a compiler builtin like
+// __dp4a/__byte_perm, not inline PTX). Other toolchains: widening
+// scalar fallback (same values; mirrors fq_dp4a's fallback arm).
+__device__ __forceinline__ uint32_t fq_vcmpne4(uint32_t a)
+{
+#if defined(__CUDA_ARCH__)
+ return __vcmpne4(a, 0u);
+#else
+ uint32_t v = 0;
+ #pragma unroll
+ for (int m = 0; m < 4; m++)
+ v |= ((0u - ((a >> (8 * m)) & 1u)) & 0xFFu) << (8 * m);
+ return v;
+#endif
+}
+
+// IQ2_XXS q8_1 lane dot v2: per-thread partial sum over its 32-elem
+// chunks. Same integer arithmetic and op order as ggml
+// vec_dot_iq2_xxs_q8_1 (4 grid-uint2 groups per chunk, 2 dp4a each,
+// integer ls scale, one float scale per chunk), so KLD-vs-reference
+// equals llama's by construction. Grid comes straight from the
+// __constant__ table (no staging); headers load direct as u16 pairs
+// (2-aligned, ggml get_int_b2 pattern); signs unpack inline (no
+// signs32 table). The sign apply keeps the proven branchless
+// ((g^s)+(s&0x01010101)) formula: grid bytes are never 0 so no
+// cross-byte borrow, identical to llama's xor+__vsub4.
+__device__ float fq_dot_iq2_xxs_q8v2(const uint8_t* __restrict__ wr,
+ const uint8_t* __restrict__ aqb,
+ int K, int tid, int nthreads)
+{
+ int nchunks = K / 32;
+ float acc = 0.0f;
+ const uint2* grid2 = reinterpret_cast<const uint2*>(FQ_IQ2XXS_GRID);
+ for (int c = tid; c < nchunks; c += nthreads)
+ {
+ int b = c >> 3; // 256-block
+ int sub = c & 7; // 32-chunk within the block
+ const uint8_t* blk = wr + (size_t)b * FQ_IQ2_XXS_BYTES;
+ __half dwh;
+ memcpy(&dwh, blk, 2);
+ float dw = __half2float(dwh);
+ // Header pair (a0, a1): 4 u16 at blk+2+sub*8 (even = 2-aligned:
+ // row base 16B-aligned + b*66 even + 2 + sub*8 even).
+ const uint16_t* h16 = reinterpret_cast<const uint16_t*>(blk + 2 + sub * 8);
+ uint16_t h0 = h16[0], h1 = h16[1], h2 = h16[2], h3 = h16[3];
+ uint32_t a0 = (uint32_t)h0 | ((uint32_t)h1 << 16);
+ uint32_t a1 = (uint32_t)h2 | ((uint32_t)h3 << 16);
+ int ls = (int)((a1 >> 27) | 1u); // (scale*2+1), integer path
+ __half dah;
+ memcpy(&dah, aqb + (size_t)c * FQ_Q8_1_BYTES, 2);
+ float da = __half2float(dah);
+ // Vectorized u32 activation loads (qb stride/offsets multiples of 4).
+ const int32_t* aq32 = reinterpret_cast<const int32_t*>(aqb + (size_t)c * FQ_Q8_1_BYTES + 4);
+ const uint8_t* aux8 = reinterpret_cast<const uint8_t*>(&a0);
+ int sumi = 0;
+ #pragma unroll
+ for (int j = 0; j < 4; j++)
+ {
+ uint2 gp = grid2[aux8[j]];
+ uint32_t signs = fq_unpack_ksigns((uint8_t)(a1 >> (7 * j)));
+ uint32_t sv0 = fq_vcmpne4(signs & 0x08040201u);
+ uint32_t sv1 = fq_vcmpne4(signs & 0x80402010u);
+ uint32_t w0 = (gp.x ^ sv0) + (sv0 & 0x01010101u);
+ uint32_t w1 = (gp.y ^ sv1) + (sv1 & 0x01010101u);
+ sumi = fq_dp4a((int32_t)w0, aq32[2 * j], sumi);
+ sumi = fq_dp4a((int32_t)w1, aq32[2 * j + 1], sumi);
+ }
+ int scaled = sumi * ls / 8;
+ acc = __fadd_rn(acc, __fmul_rn(__fmul_rn(dw, da), (float)scaled));
+ }
+ return acc;
+}
+
+// IQ2_XXS q8_1 lane dot: per-thread partial sum over its 32-elem chunks.
+// Same integer arithmetic as ggml vec_dot_iq2_xxs_q8_1: 8 dp4a per chunk,
+// integer ls scale ((a1>>27)|1, applied as sumi*ls/8 in int), one float
+// scale (block d * activation d) per chunk. grid8 = staged grid bytes
+// (u32-aligned pairs: chunk sub-group j2 reads u32 [g*2+(j2&1)]),
+// signs32 = expanded signs (entry [(sidx<<1)+(j2&1)], bytes 0x00/0xFF),
+// aqb = global q8_1 blocks of the row, hdrs = staged row headers
+// (16 u32 per 256-block).
+__device__ float fq_dot_iq2_xxs_q8(const uint8_t* __restrict__ wr,
+ const uint32_t* __restrict__ hdrs,
+ const uint8_t* __restrict__ grid8,
+ const uint32_t* __restrict__ signs32,
+ const uint8_t* __restrict__ aqb,
+ int K, int tid, int nthreads)
+{
+ int nchunks = K / 32;
+ float acc = 0.0f;
+ const uint32_t* grid32 = reinterpret_cast<const uint32_t*>(grid8);
+ for (int c = tid; c < nchunks; c += nthreads)
+ {
+ int b = c >> 3; // 256-block
+ int sub = c & 7; // 32-chunk within the block
+ const uint8_t* blk = wr + (size_t)b * FQ_IQ2_XXS_BYTES;
+ __half dwh;
+ memcpy(&dwh, blk, 2);
+ float dw = __half2float(dwh);
+ uint32_t a0 = hdrs[(size_t)b * 16 + sub * 2];
+ uint32_t a1 = hdrs[(size_t)b * 16 + sub * 2 + 1];
+ int ls = (int)((a1 >> 27) | 1u); // (scale*2+1), integer path
+ __half dah;
+ memcpy(&dah, aqb + (size_t)c * FQ_Q8_1_BYTES, 2);
+ float da = __half2float(dah);
+ // Vectorized u32 activation loads (qb stride/offsets are multiples
+ // of 4; the old memcpy-bytes compiled to LDG.E.U8).
+ const int32_t* aq32 = reinterpret_cast<const int32_t*>(aqb + (size_t)c * FQ_Q8_1_BYTES + 4);
+ int sumi = 0;
+ #pragma unroll
+ for (int j2 = 0; j2 < 8; j2++)
+ {
+ // 4 consecutive elements: grid bytes [g*8+4h .. +3] (one u32),
+ // signs s32 for (sidx, h), activations 4 consecutive int8.
+ int elle = j2 >> 1;
+ int h = j2 & 1;
+ uint32_t g = (a0 >> (8 * elle)) & 0xFFu;
+ int32_t gv;
+ memcpy(&gv, &grid32[g * 2 + h], 4);
+ uint32_t sidx = (a1 >> (7 * elle)) & 127u;
+ uint32_t sv = signs32[(sidx << 1) + h];
+ // Apply signs without cross-byte borrow: grid bytes are never
+ // 0 (iq2xxs magnitudes are 8/25/43), so (g^0xFF)+1 = -g mod
+ // 256 carries at most into... nothing: 255-g <= 247, +1 <= 248.
+ // s=0x00 keeps g (+0). Portable, no video intrinsics.
+ uint32_t w4 = ((uint32_t)gv ^ sv) + (sv & 0x01010101u);
+ sumi = fq_dp4a((int32_t)w4, aq32[j2], sumi);
+ }
+ int scaled = sumi * ls / 8;
+ acc = __fadd_rn(acc, __fmul_rn(__fmul_rn(dw, da), (float)scaled));
+ }
+ return acc;
+}
+
+// Doubled-E2M1 int8 table for the NVFP4 q8 dot, replicated 8x in shared
+// (128 B): lookup j of a thread uses replica (j & 7), so consecutive
+// lookups spread over 8 banks (same bank-spread pattern as the proven
+// float e2m1 4x replica). Built cooperatively straight from the
+// __constant__ table (no dependency on shared state, no extra sync).
+// (Fallback path only: CUDA uses the __byte_perm expansion below.)
+__device__ void fq_e2m1db_build(int8_t* __restrict__ dst)
+{
+ int tid = threadIdx.x;
+ for (int e = tid; e < 128; e += blockDim.x)
+ dst[e] = FQ_E2M1_DBL[e >> 3];
+}
+
+// Expand 8 consecutive E2M1 nibbles (one u32 of packed bytes, little-endian:
+// byte j holds nibbles 2j (lo) and 2j+1 (hi)) to 8 consecutive doubled
+// int8 as int2 (x = elems 0-3, y = elems 4-7). Same construction as
+// llama.cpp's get_int_from_table_16 (vecdotq.cuh) MINUS its final
+// even/odd shuffle: the intermediate tmp[i] already holds 4 consecutive
+// values (nibbles 4i..4i+3), which is exactly our (consecutive) activation
+// order, so the 0x6420/0x7531 reshuffle is skipped. 6 __byte_perm per 8
+// nibbles. __byte_perm is a CUDA compiler builtin (no inline PTX); the
+// table is __constant__ and read UNIFORMLY (all lanes read the same 4
+// u32s, then permute in-register), so no constant-cache serialization
+// (contrast the step-4 lesson on DIVERGENT constant reads). Non-CUDA
+// toolchains take the shared-table scalar fallback (fq_dot_nvfp4_q8_fb
+// below), which is the same verified arithmetic.
+__device__ __forceinline__ int2 fq_e2m1_expand_8(uint32_t q4)
+{
+#if defined(__CUDA_ARCH__)
+ const uint32_t* table32 = reinterpret_cast<const uint32_t*>(FQ_E2M1_DBL);
+ const uint32_t sel = 0x32103210u | ((q4 & 0x88888888u) >> 1);
+ uint32_t lo = __byte_perm(table32[0], table32[1], q4);
+ uint32_t hi = __byte_perm(table32[2], table32[3], q4);
+ uint32_t t0 = __byte_perm(lo, hi, sel);
+ uint32_t q4h = q4 >> 16;
+ lo = __byte_perm(table32[0], table32[1], q4h);
+ hi = __byte_perm(table32[2], table32[3], q4h);
+ uint32_t t1 = __byte_perm(lo, hi, sel >> 16);
+ return make_int2((int)t0, (int)t1);
+#else
+ (void)q4;
+ return make_int2(0, 0);
+#endif
+}
+
+// NVFP4 q8_1 lane dot: per-thread partial sum over its 32-elem chunks.
+// Same integer factorization as ggml vec_dot_nvfp4_q8_1: per 16-elem
+// group, 4 dp4a over (doubled-e2m1 int8 x q8_1 int8), one float scale
+// (ue4m3 = raw e4m3 x 0.5, exact dyadic halving, x activation d) per
+// group. The row-uniform `global` multiplies once at the end (one
+// rounding instead of one per group in the fp32 path). Layout note:
+// unlike ggml's interleaved d[4]+qs[32] 64-blocks, ours is split
+// (packed [N, K/2] E2M1 bytes, scales [N, K/16] E4M3 bytes): chunk c
+// owns pr bytes [c*16, c*16+16) and scale bytes [c*2, c*2+2), and the
+// activation q8_1 block c owns the 32 int8. ModelOpt packing: low
+// nibble = even index, like fq_nvfp4_group.
+// Weight expansion: CUDA packs each 8-nibble u32 via fq_e2m1_expand_8
+// (6 __byte_perm); other toolchains use the shared-table scalar
+// fallback (same arithmetic, verified by the exact gate).
+__device__ float fq_dot_nvfp4_q8(const uint8_t* __restrict__ pr,
+ const uint8_t* __restrict__ sr,
+ const uint8_t* __restrict__ aqb,
+ const int8_t* __restrict__ e2m1db,
+ int K, float global, int tid, int nthreads)
+{
+ int nchunks = K / 32;
+ float acc = 0.0f;
+ for (int c = tid; c < nchunks; c += nthreads)
+ {
+ __half dah;
+ memcpy(&dah, aqb + (size_t)c * FQ_Q8_1_BYTES, 2);
+ float da = __half2float(dah);
+ const int8_t* aq = reinterpret_cast<const int8_t*>(aqb + (size_t)c * FQ_Q8_1_BYTES + 4);
+ const uint8_t* prc = pr + (size_t)c * 16;
+ for (int g = 0; g < 2; g++)
+ {
+ // ue4m3 scale x 0.5 (matches ggml_cuda_ue4m3_to_fp32's /2;
+ // exact: FQ_E4M3_BITS holds exact dyadics) x activation d.
+ float d = __fmul_rn(__fmul_rn(__uint_as_float(FQ_E4M3_BITS[sr[c * 2 + g]]),
+ 0.5f), da);
+ int32_t w0, w1, w2, w3;
+#if defined(__CUDA_ARCH__)
+ // Vectorized u32 weight loads (one LDG.E.U32 each, not 4 byte
+ // loads: SASS showed the memcpy-bytes compile to LDG.E.U8).
+ // Safe: pr rows have stride K/2 (multiple of 4, K%32 checked)
+ // and chunk offsets c*16+g*8 (multiples of 8); torch bases are
+ // 16B+ aligned. (Llama's get_int_b4 makes the same assumption.)
+ // (pr/sr arrive row-offset by the caller.)
+ const uint8_t* prn = pr + (size_t)c * 16 + g * 8;
+ uint32_t q4a = reinterpret_cast<const uint32_t*>(prn)[0];
+ uint32_t q4b = reinterpret_cast<const uint32_t*>(prn)[1];
+ int2 e01 = fq_e2m1_expand_8(q4a);
+ int2 e23 = fq_e2m1_expand_8(q4b);
+ w0 = e01.x;
+ w1 = e01.y;
+ w2 = e23.x;
+ w3 = e23.y;
+ // Vectorized u32 activation loads: qb rows stride nb32*36
+ // (multiple of 4: 36 = 4*9) and offsets c*36+4+g*16 (multiple
+ // of 4), so these are 4-aligned too.
+ const int32_t* aq32 = reinterpret_cast<const int32_t*>(aq + g * 16);
+ int32_t u0 = aq32[0];
+ int32_t u1 = aq32[1];
+ int32_t u2 = aq32[2];
+ int32_t u3 = aq32[3];
+ int sumi = 0;
+ sumi = fq_dp4a(w0, u0, sumi);
+ sumi = fq_dp4a(w1, u1, sumi);
+ sumi = fq_dp4a(w2, u2, sumi);
+ sumi = fq_dp4a(w3, u3, sumi);
+#else
+ // Scalar fallback: 16 nibble lookups in the bank-spread
+ // table ((j & 7) replica spreads lookups over 8 banks).
+ uint32_t b[16];
+ #pragma unroll
+ for (int j = 0; j < 16; j++)
+ {
+ uint8_t pbyte = prc[g * 8 + (j >> 1)];
+ uint8_t nib = (j & 1) ? (pbyte >> 4) & 0xF : pbyte & 0xF;
+ b[j] = (uint32_t)(uint8_t)e2m1db[((uint32_t)nib << 3) | (uint32_t)(j & 7)];
+ }
+ w0 = (int32_t)(b[0] | (b[1] << 8) | (b[2] << 16) | (b[3] << 24));
+ w1 = (int32_t)(b[4] | (b[5] << 8) | (b[6] << 16) | (b[7] << 24));
+ w2 = (int32_t)(b[8] | (b[9] << 8) | (b[10] << 16) | (b[11] << 24));
+ w3 = (int32_t)(b[12] | (b[13] << 8) | (b[14] << 16) | (b[15] << 24));
+ int32_t u0, u1, u2, u3;
+ memcpy(&u0, aq + g * 16, 4);
+ memcpy(&u1, aq + g * 16 + 4, 4);
+ memcpy(&u2, aq + g * 16 + 8, 4);
+ memcpy(&u3, aq + g * 16 + 12, 4);
+ int sumi = 0;
+ sumi = fq_dp4a(w0, u0, sumi);
+ sumi = fq_dp4a(w1, u1, sumi);
+ sumi = fq_dp4a(w2, u2, sumi);
+ sumi = fq_dp4a(w3, u3, sumi);
+#endif
+ acc = __fadd_rn(acc, __fmul_rn(d, (float)sumi));
+ }
+ }
+ return __fmul_rn(acc, global);
+}
+
+// Q8_0 q8_1 lane dot: per-thread partial sum over its 32-elem chunks.
+// Same integer arithmetic as ggml vec_dot_q8_0_q8_1 (VDR_MMVQ arm): 8
+// dp4a over (weight int8 x activation int8), one float scale (weight d
+// x activation d) per 32-block. No tables at all (weights are int8).
+__device__ float fq_dot_q8_0_q8(const uint8_t* __restrict__ wr,
+ const uint8_t* __restrict__ aqb,
+ int K, int tid, int nthreads)
+{
+ int nchunks = K / 32;
+ float acc = 0.0f;
+ for (int c = tid; c < nchunks; c += nthreads)
+ {
+ const uint8_t* blk = wr + (size_t)c * FQ_Q8_0_BYTES;
+ __half dwh;
+ memcpy(&dwh, blk, 2);
+ float dw = __half2float(dwh);
+ __half dah;
+ memcpy(&dah, aqb + (size_t)c * FQ_Q8_1_BYTES, 2);
+ float da = __half2float(dah);
+ const int8_t* aq = reinterpret_cast<const int8_t*>(aqb + (size_t)c * FQ_Q8_1_BYTES + 4);
+ // Vectorized loads (SASS showed memcpy-bytes compile to LDG.E.U8):
+ // weights as u16 pairs (Q8 blocks stride 34B: 2-aligned but not
+ // 4-aligned -- same reason llama's Q8 path uses get_int_b2),
+ // activations as u32 (qb stride/offsets are multiples of 4).
+ const uint16_t* w16 = reinterpret_cast<const uint16_t*>(blk + 2);
+ const int32_t* aq32 = reinterpret_cast<const int32_t*>(aq);
+ int sumi = 0;
+ #pragma unroll
+ for (int j2 = 0; j2 < 8; j2++)
+ {
+ int32_t w4 = (int32_t)(w16[j2 * 2] | ((uint32_t)w16[j2 * 2 + 1] << 16));
+ sumi = fq_dp4a(w4, aq32[j2], sumi);
+ }
+ acc = __fadd_rn(acc, __fmul_rn(__fmul_rn(dw, da), (float)sumi));
+ }
+ return acc;
+}
+
+// K-quant + IQ4_XS q8_1-activation lane dots (port of the
+// llama.cpp mmvq vmmq arms in ggml/src/ggml-cuda/vecdotq.cuh, MIT ggml-org).
+// Same portable contract as the dots above (no PTX, no shuffles; __dp4a via
+// fq_dp4a with HIP fallback, __vsub4/__vcmpne4 builtins with scalar
+// fallback). Threads take sub-chunks round-robin (16 elems for Q4_K/Q5_K,
+// 8 for Q6_K, 32 for IQ4_XS -- one vec_dot call each, same integer op
+// order as ggml, so KLD-vs-reference equals llama's by construction).
+// Weight words load via 4B memcpy (compiles to a single LDG.U32 when
+// aligned) and scales via 2B memcpy; both are safe on any alignment.
+
+// Q4_K geometry (QK_K = 256): dm half2 at +0, scales[12] at +4, qs[128]
+// at +16; 144 B per 256-block.
+#define FQ_Q4_K_GROUP 256
+#define FQ_Q4_K_BYTES 144
+
+// Q5_K geometry: dm half2 at +0, scales[12] at +4, qh[32] at +16,
+// qs[128] at +48; 176 B per 256-block.
+#define FQ_Q5_K_GROUP 256
+#define FQ_Q5_K_BYTES 176
+
+// Q6_K geometry: ql[128] at +0, qh[64] at +128, scales[16] int8 at +192,
+// d half at +208; 210 B per 256-block.
+#define FQ_Q6_K_GROUP 256
+#define FQ_Q6_K_BYTES 210
+
+// IQ4_XS geometry: d half at +0, scales_h u16 at +2, scales_l[4] at +4,
+// qs[128] at +8; 136 B per 256-block.
+#define FQ_IQ4_XS_GROUP 256
+#define FQ_IQ4_XS_BYTES 136
+
+// IQ4_XS nonlinear codebook (verbatim ggml kvalues_iq4nl, 16 int8).
+// Plain __device__ (= global, L1-cached LDG), NOT __constant__: every lane
+// reads a different nibble entry (divergent), and the constant cache
+// serializes divergent addresses (measured; same reason the IQ2 grid
+// is __device__). Internal linkage (const) like FQ_IQ2XXS_GRID, so sharing
+// this header across TUs is safe.
+__device__ const int8_t FQ_KVALUES_IQ4NL[16] = {
+ -127, -104, -83, -65, -49, -35, -22, -10,
+ 1, 13, 25, 38, 53, 69, 89, 113
+};
+
+// Per-byte subtract mod 256. CUDA: the __vsub4 video-SIMD builtin (1 insn;
+// a compiler builtin like __vcmpne4, not inline PTX). Other toolchains:
+// scalar fallback (same values; mirrors fq_vcmpne4's fallback arm).
+__device__ __forceinline__ uint32_t fq_vsub4(uint32_t a, uint32_t b)
+{
+#if defined(__CUDA_ARCH__)
+ return __vsub4(a, b);
+#else
+ uint32_t v = 0;
+ #pragma unroll
+ for (int m = 0; m < 4; m++)
+ v |= (((((a >> (8 * m)) & 0xFFu) - ((b >> (8 * m)) & 0xFFu)) & 0xFFu) << (8 * m));
+ return v;
+#endif
+}
+
+// Q4_K branchless scale/min decode (verbatim ggml get_scale_min_k4): 8
+// (sc, m) pairs per 256-block from the 12 scale bytes; j = sub-group.
+__device__ __forceinline__ void fq_q4k_scales(const uint8_t* __restrict__ sc12,
+ int j, uint8_t* sc, uint8_t* m)
+{
+ uint16_t s0, s2, s4;
+ memcpy(&s0, sc12 + (j & 1) * 2, 2);
+ memcpy(&s2, sc12 + ((j & 1) + 2) * 2, 2);
+ memcpy(&s4, sc12 + ((j & 1) + 4) * 2, 2);
+ uint32_t hi = (j >= 2) ? 0xFFFFFFFFu : 0u;
+ uint16_t aux0 = (uint16_t)(((s0 & 0x3F3Fu) & ~hi) |
+ ((((s4 >> 0) & 0x0F0Fu) | ((s0 & 0xC0C0u) >> 2)) & hi));
+ uint16_t aux1 = (uint16_t)(((s2 & 0x3F3Fu) & ~hi) |
+ ((((s4 >> 4) & 0x0F0Fu) | ((s2 & 0xC0C0u) >> 2)) & hi));
+ sc[0] = (uint8_t)(aux0 & 0xFFu);
+ sc[1] = (uint8_t)((aux0 >> 8) & 0xFFu);
+ m[0] = (uint8_t)(aux1 & 0xFFu);
+ m[1] = (uint8_t)((aux1 >> 8) & 0xFFu);
+}
+
+// Q4_K q8_1 lane dot: per-thread partial over 16-elem sub-chunks
+// (t = c & 15 within each 256-block b = c >> 4). Same integer arithmetic
+// and op order as ggml vec_dot_q4_K_q8_1 (vmmq arm).
+__device__ float fq_dot_q4_k_q8(const uint8_t* __restrict__ wr,
+ const uint8_t* __restrict__ aqb,
+ int K, int tid, int nthreads)
+{
+ int nsub = K / 16;
+ float acc = 0.0f;
+ for (int c = tid; c < nsub; c += nthreads)
+ {
+ int b = c >> 4;
+ int t = c & 15;
+ int bo = 2 * (t >> 2);
+ int qo = t & 3;
+ const uint8_t* blk = wr + (size_t)b * FQ_Q4_K_BYTES;
+ __half dmh[2];
+ memcpy(dmh, blk, 4);
+ float dm0 = __half2float(dmh[0]);
+ float dm1 = __half2float(dmh[1]);
+ uint8_t sc[2], m[2];
+ fq_q4k_scales(blk + 4, bo >> 1, sc, m);
+ uint32_t v0, v1;
+ memcpy(&v0, blk + 16 + 16 * bo + 4 * qo, 4);
+ memcpy(&v1, blk + 16 + 16 * bo + 4 * qo + 16, 4);
+ float sumf_d = 0.0f, sumf_m = 0.0f;
+ #pragma unroll
+ for (int i = 0; i < 2; i++)
+ {
+ uint32_t v0i = (v0 >> (4 * i)) & 0x0F0F0F0Fu;
+ uint32_t v1i = (v1 >> (4 * i)) & 0x0F0F0F0Fu;
+ int ab = b * 8 + bo + i;
+ const uint8_t* aqb_blk = aqb + (size_t)ab * FQ_Q8_1_BYTES;
+ __half dah;
+ memcpy(&dah, aqb_blk, 2);
+ float d8 = __half2float(dah);
+ int32_t u0, u1;
+ memcpy(&u0, aqb_blk + 4 + 4 * qo, 4);
+ memcpy(&u1, aqb_blk + 4 + 16 + 4 * qo, 4);
+ int dot1 = fq_dp4a((int32_t)v0i, u0, 0);
+ dot1 = fq_dp4a((int32_t)v1i, u1, dot1);
+ int32_t su0 = u0, su1 = u1;
+ int dot2 = fq_dp4a(0x01010101, su0, 0);
+ dot2 = fq_dp4a(0x01010101, su1, dot2);
+ sumf_d = __fadd_rn(sumf_d, __fmul_rn(d8, (float)(dot1 * sc[i])));
+ sumf_m = __fadd_rn(sumf_m, __fmul_rn(d8, (float)(dot2 * m[i])));
+ }
+ acc = __fadd_rn(acc, __fadd_rn(__fmul_rn(dm0, sumf_d), -__fmul_rn(dm1, sumf_m)));
+ }
+ return acc;
+}
+
+// Q5_K q8_1 lane dot: same grid as Q4_K plus the high-bit plane
+// (verbatim ggml vec_dot_q5_K_q8_1 vmmq arm).
+__device__ float fq_dot_q5_k_q8(const uint8_t* __restrict__ wr,
+ const uint8_t* __restrict__ aqb,
+ int K, int tid, int nthreads)
+{
+ int nsub = K / 16;
+ float acc = 0.0f;
+ for (int c = tid; c < nsub; c += nthreads)
+ {
+ int b = c >> 4;
+ int t = c & 15;
+ int bo = 2 * (t >> 2);
+ int qo = t & 3;
+ const uint8_t* blk = wr + (size_t)b * FQ_Q5_K_BYTES;
+ __half dmh[2];
+ memcpy(dmh, blk, 4);
+ float dm0 = __half2float(dmh[0]);
+ float dm1 = __half2float(dmh[1]);
+ uint8_t sc[2], m[2];
+ fq_q4k_scales(blk + 4, bo >> 1, sc, m);
+ uint32_t vl0, vl1, vh0, vh1;
+ memcpy(&vl0, blk + 48 + 16 * bo + 4 * qo, 4);
+ memcpy(&vl1, blk + 48 + 16 * bo + 4 * qo + 16, 4);
+ memcpy(&vh0, blk + 16 + 4 * qo, 4);
+ memcpy(&vh1, blk + 16 + 4 * qo + 16, 4);
+ vh0 >>= bo;
+ vh1 >>= bo;
+ float sumf_d = 0.0f, sumf_m = 0.0f;
+ #pragma unroll
+ for (int i = 0; i < 2; i++)
+ {
+ uint32_t vl0i = (vl0 >> (4 * i)) & 0x0F0F0F0Fu;
+ uint32_t vl1i = (vl1 >> (4 * i)) & 0x0F0F0F0Fu;
+ uint32_t vh0i = ((vh0 >> i) << 4) & 0x10101010u;
+ uint32_t vh1i = ((vh1 >> i) << 4) & 0x10101010u;
+ uint32_t v0i = vl0i | vh0i;
+ uint32_t v1i = vl1i | vh1i;
+ int ab = b * 8 + bo + i;
+ const uint8_t* aqb_blk = aqb + (size_t)ab * FQ_Q8_1_BYTES;
+ __half dah;
+ memcpy(&dah, aqb_blk, 2);
+ float d8 = __half2float(dah);
+ int32_t u0, u1;
+ memcpy(&u0, aqb_blk + 4 + 4 * qo, 4);
+ memcpy(&u1, aqb_blk + 4 + 16 + 4 * qo, 4);
+ int dot1 = fq_dp4a((int32_t)v0i, u0, 0);
+ dot1 = fq_dp4a((int32_t)v1i, u1, dot1);
+ int dot2 = fq_dp4a(0x01010101, u0, 0);
+ dot2 = fq_dp4a(0x01010101, u1, dot2);
+ sumf_d = __fadd_rn(sumf_d, __fmul_rn(d8, (float)(dot1 * sc[i])));
+ sumf_m = __fadd_rn(sumf_m, __fmul_rn(d8, (float)(dot2 * m[i])));
+ }
+ acc = __fadd_rn(acc, __fadd_rn(__fmul_rn(dm0, sumf_d), -__fmul_rn(dm1, sumf_m)));
+ }
+ return acc;
+}
+
+// Q6_K q8_1 lane dot: per-thread partial over 8-elem sub-chunks
+// (iqs = c & 31 within each 256-block b = c >> 5). Verbatim ggml
+// vec_dot_q6_K_q8_1 (mmvq arm).
+__device__ float fq_dot_q6_k_q8(const uint8_t* __restrict__ wr,
+ const uint8_t* __restrict__ aqb,
+ int K, int tid, int nthreads)
+{
+ int nsub = K / 8;
+ float acc = 0.0f;
+ for (int c = tid; c < nsub; c += nthreads)
+ {
+ int b = c >> 5;
+ int iqs = c & 31;
+ const uint8_t* blk = wr + (size_t)b * FQ_Q6_K_BYTES;
+ int bq8_off = 4 * (iqs / 16) + (iqs % 16) / 8;
+ int sc_off = 8 * (iqs / 16) + (iqs % 16) / 4;
+ int vh_shift = 2 * ((iqs % 16) / 8);
+ uint32_t vl, vh;
+ memcpy(&vl, blk + 4 * iqs, 4);
+ memcpy(&vh, blk + 128 + 4 * (8 * (iqs / 16) + iqs % 8), 4);
+ vh >>= vh_shift;
+ const int8_t* scales = reinterpret_cast<const int8_t*>(blk + 192 + sc_off);
+ __half dh;
+ memcpy(&dh, blk + 208, 2);
+ float d = __half2float(dh);
+ float sumf = 0.0f;
+ #pragma unroll
+ for (int i = 0; i < 2; i++)
+ {
+ int scc = (int)scales[4 * i];
+ uint32_t vil = (vl >> (4 * i)) & 0x0F0F0F0Fu;
+ uint32_t vih = ((vh >> (4 * i)) << 4) & 0x30303030u;
+ uint32_t vi = fq_vsub4(vil | vih, 0x20202020u);
+ int ab = b * 8 + bq8_off + 2 * i;
+ const uint8_t* aqb_blk = aqb + (size_t)ab * FQ_Q8_1_BYTES;
+ __half dah;
+ memcpy(&dah, aqb_blk, 2);
+ float d8 = __half2float(dah);
+ int32_t u;
+ memcpy(&u, aqb_blk + 4 + 4 * (iqs % 8), 4);
+ sumf = __fadd_rn(sumf, __fmul_rn(d8, (float)(fq_dp4a((int32_t)vi, u, 0) * scc)));
+ }
+ acc = __fadd_rn(acc, __fmul_rn(d, sumf));
+ }
+ return acc;
+}
+
+// IQ4_XS codebook as two register-held u64 (bytes = verbatim kvalues_iq4nl
+// as u8: P0 = bytes 0..7, P1 = bytes 8..15). Register shifts replace the 32
+// divergent L1 loads per chunk below; the extracted bytes (hence the dp4a
+// chain and every downstream value) are bitwise unchanged.
+#define FQ_IQ4XS_LUT0 0xF6EADDCFBFAD9881ULL
+#define FQ_IQ4XS_LUT1 0x7159453526190D01ULL
+__device__ __forceinline__ uint32_t fq_iq4xs_lut(uint32_t idx)
+{
+ uint64_t p = (idx < 8) ? FQ_IQ4XS_LUT0 : FQ_IQ4XS_LUT1;
+ return (uint32_t)((p >> (8 * (idx & 7))) & 0xFFu);
+}
+
+// IQ4_XS q8_1 lane dot: per-thread partial over 32-elem chunks
+// (iqs = 4 * (c & 7) within each 256-block b = c >> 3). Verbatim ggml
+// vec_dot_iq4_xs_q8_1; the codebook comes from the register LUT above.
+__device__ float fq_dot_iq4_xs_q8(const uint8_t* __restrict__ wr,
+ const uint8_t* __restrict__ aqb,
+ int K, int tid, int nthreads)
+{
+ int nchunks = K / 32;
+ float acc = 0.0f;
+ for (int c = tid; c < nchunks; c += nthreads)
+ {
+ int b = c >> 3;
+ int sub = c & 7;
+ int iqs = 4 * sub;
+ const uint8_t* blk = wr + (size_t)b * FQ_IQ4_XS_BYTES;
+ __half dwh;
+ memcpy(&dwh, blk, 2);
+ float dw = __half2float(dwh);
+ uint16_t sh;
+ memcpy(&sh, blk + 2, 2);
+ uint8_t sl = *(blk + 4 + sub / 2);
+ int ls = (int)(((sl >> (4 * (sub % 2))) & 0xF) | ((((uint32_t)sh >> (2 * sub)) & 3u) << 4));
+ const uint8_t* qs = blk + 8;
+ const uint8_t* aqbb = aqb + (size_t)(b * 8 + sub) * FQ_Q8_1_BYTES;
+ __half dah;
+ memcpy(&dah, aqbb, 2);
+ float da = __half2float(dah);
+ const uint8_t* aq = aqbb + 4;
+ int sumi = 0;
+ #pragma unroll
+ for (int j = 0; j < 4; j++)
+ {
+ uint32_t aux;
+ memcpy(&aux, qs + 4 * (iqs + j), 4);
+ uint32_t vx = 0, vy = 0;
+ #pragma unroll
+ for (int k = 0; k < 4; k++)
+ {
+ // get_int_from_table_16 even/odd de-interleave: x takes the
+ // even nibbles (low of each byte), y the odd nibbles (high).
+ vx |= fq_iq4xs_lut((aux >> (8 * k)) & 0xFu) << (8 * k);
+ vy |= fq_iq4xs_lut((aux >> (8 * k + 4)) & 0xFu) << (8 * k);
+ }
+ int32_t u0, u1;
+ memcpy(&u0, aq + 4 * j, 4);
+ memcpy(&u1, aq + 4 * (j + 4), 4);
+ sumi = fq_dp4a((int32_t)vx, u0, sumi);
+ sumi = fq_dp4a((int32_t)vy, u1, sumi);
+ }
+ sumi *= ls - 32;
+ acc = __fadd_rn(acc, __fmul_rn(__fmul_rn(dw, da), (float)sumi));
+ }
+ return acc;
+}
+
+} // namespace
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_gemv_kq.cu b/exllamav3/exllamav3_ext/foreign_quant/fq_gemv_kq.cu
new file mode 100644
index 0000000..e89d3f3
--- /dev/null
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_gemv_kq.cu
@@ -0,0 +1,134 @@
+// q8_1-activation decode kernels for K-quant + IQ4_XS weights
+// port of the llama.cpp mmvq vmmq arms (ggml/src/ggml-cuda/vecdotq.cuh).
+// Activations are quantized ONCE per row to q8_1 blocks by the shared
+// fq_quant_q8_1_rows (fq_gemv_q8.cu) into the caller-cached global scratch,
+// then row-per-block dots (fq_dot_q4_k_q8 / fq_dot_q5_k_q8 / fq_dot_q6_k_q8 /
+// fq_dot_iq4_xs_q8 in fq_gemv.cuh) run INTEGER dp4a dots.
+//
+// Same portability contract as fq_gemv_q8.cu (no PTX, no warp shuffles,
+// shared-memory reduction, fq_dp4a + fq_vsub4 builtins with scalar
+// fallbacks off-CUDA).
+#include <cuda_fp16.h>
+#include <torch/extension.h>
+#include <c10/cuda/CUDAGuard.h>
+#include <ATen/cuda/CUDAContext.h>
+#include "../util.h"
+#include "fq_gemv.cuh"
+#include "fq_api.h"
+
+namespace {
+
+// Row-per-block KQ q8 dot: block bidx computes output row n of x-row m
+// against the packed K-quant matrix. Threads take sub-chunks round-robin;
+// partials reduce sequentially (portable, same grid as the IQ2/NVFP4/Q8 row
+// kernels in fq_gemv_q8.cu). FMT selects the dot (0 = Q4_K, 1 = Q5_K,
+// 2 = Q6_K, 3 = IQ4_XS).
+template <typename OUT, int FMT>
+__global__ void fq_gemv_kq_kernel(const uint8_t* __restrict__ aqb,
+ const uint8_t* __restrict__ packed,
+ OUT* __restrict__ out,
+ int M, int N, int K, int64_t packed_stride,
+ int64_t qb_stride)
+{
+ int bidx = blockIdx.x;
+ int m = bidx / N;
+ int n = bidx % N;
+ int tid = threadIdx.x;
+ int nt = blockDim.x;
+
+ extern __shared__ float red[];
+
+ float acc = 0.0f;
+ if (n < N)
+ {
+ const uint8_t* wr = packed + (int64_t)n * packed_stride;
+ const uint8_t* aq = aqb + (int64_t)m * qb_stride;
+ if constexpr (FMT == 0)
+ acc = fq_dot_q4_k_q8(wr, aq, K, tid, nt);
+ else if constexpr (FMT == 1)
+ acc = fq_dot_q5_k_q8(wr, aq, K, tid, nt);
+ else if constexpr (FMT == 2)
+ acc = fq_dot_q6_k_q8(wr, aq, K, tid, nt);
+ else
+ acc = fq_dot_iq4_xs_q8(wr, aq, K, tid, nt);
+ }
+ red[tid] = acc;
+ __syncthreads();
+ if (n < N && tid == 0)
+ {
+ float s = 0.0f;
+ for (int l = 0; l < nt; l++)
+ s = __fadd_rn(s, red[l]);
+ if constexpr (std::is_same<OUT, __half>::value)
+ out[(int64_t)m * N + n] = __float2half_rn(s);
+ else
+ out[(int64_t)m * N + n] = s;
+ }
+}
+
+} // namespace
+
+// Shared row-per-block q8 launch sizing: threads take sub-chunks
+// round-robin (same as fq_q8_nt in fq_gemv_q8.cu, generalized).
+static inline int fq_kq_nt(int K, int sub)
+{
+ int nsub = K / sub;
+ return nsub >= 256 ? 256 : ((nsub + 31) / 32) * 32;
+}
+
+template <int FMT, int SUB>
+static void fq_gemv_kq_launch(torch::Tensor qb, torch::Tensor packed, torch::Tensor out,
+ int64_t block_bytes)
+{
+ TORCH_CHECK(qb.is_cuda() && packed.is_cuda() && out.is_cuda(), "tensors must be CUDA");
+ TORCH_CHECK(qb.is_contiguous() && packed.is_contiguous() && out.is_contiguous(),
+ "tensors must be contiguous");
+ TORCH_CHECK(out.dtype() == torch::kHalf || out.dtype() == torch::kFloat,
+ "out must be half or float");
+ TORCH_CHECK_DIM(qb, 2);
+ TORCH_CHECK_DIM(packed, 2);
+ TORCH_CHECK_DIM(out, 2);
+ int M = (int)qb.size(0);
+ int N = (int)packed.size(0);
+ TORCH_CHECK((int)out.size(0) == M, "out rows must match qb rows");
+ TORCH_CHECK((int)out.size(1) == N, "out cols must match N");
+ int K = (int)qb.size(1) / FQ_Q8_1_BYTES * FQ_Q8_1_GROUP;
+ TORCH_CHECK(K % SUB == 0, "K must be a multiple of the dot sub-chunk");
+ TORCH_CHECK((int)packed.size(1) == (K / FQ_Q4_K_GROUP) * block_bytes, "packed width must match K");
+ int64_t pstride = (int64_t)(K / FQ_Q4_K_GROUP) * block_bytes;
+ int64_t qb_stride = (int64_t)(K / FQ_Q8_1_GROUP) * FQ_Q8_1_BYTES;
+ int nt = fq_kq_nt(K, SUB);
+ size_t shmem = (size_t)nt * sizeof(float);
+ at::cuda::CUDAGuard guard(qb.device());
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ auto launch = [&](auto* op)
+ {
+ fq_gemv_kq_kernel<std::decay_t<decltype(*op)>, FMT> <<<M * N, nt, shmem, stream>>>(
+ qb.data_ptr<uint8_t>(), packed.data_ptr<uint8_t>(),
+ op, M, N, K, pstride, qb_stride);
+ };
+ if (out.dtype() == torch::kHalf)
+ launch(reinterpret_cast<__half*>(out.data_ptr<at::Half>()));
+ else
+ launch(out.data_ptr<float>());
+}
+
+void fq_gemv_q4_k_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out)
+{
+ fq_gemv_kq_launch<0, 16>(qb, packed, out, FQ_Q4_K_BYTES);
+}
+
+void fq_gemv_q5_k_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out)
+{
+ fq_gemv_kq_launch<1, 16>(qb, packed, out, FQ_Q5_K_BYTES);
+}
+
+void fq_gemv_q6_k_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out)
+{
+ fq_gemv_kq_launch<2, 8>(qb, packed, out, FQ_Q6_K_BYTES);
+}
+
+void fq_gemv_iq4_xs_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out)
+{
+ fq_gemv_kq_launch<3, 32>(qb, packed, out, FQ_IQ4_XS_BYTES);
+}
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_gemv_q8.cu b/exllamav3/exllamav3_ext/foreign_quant/fq_gemv_q8.cu
new file mode 100644
index 0000000..2078e87
--- /dev/null
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_gemv_q8.cu
@@ -0,0 +1,425 @@
+// q8_1-activation decode kernels for foreign-quant weights (Bolt phase 2):
+// port of the llama.cpp mmvq design. Activations are quantized ONCE per
+// row to q8_1 blocks (fq_quant_q8_1_kernel, same arithmetic as ggml's
+// quantize_q8_1) into a caller-cached global scratch, then row-per-block
+// dot kernels run INTEGER dp4a dots (fq_dot_iq2_xxs_q8 in fq_gemv.cuh).
+//
+// Same portability contract as fq_gemv.cu (no PTX, no warp shuffles,
+// shared-memory reduction, __fmul_rn/__fadd_rn + fq_dp4a only).
+#include <cuda_fp16.h>
+#include <map>
+#include <torch/extension.h>
+#include <c10/cuda/CUDAGuard.h>
+#include <ATen/cuda/CUDAContext.h>
+#include "../util.h"
+#include "fq_gemv.cuh"
+#include "fq_api.h"
+
+namespace {
+
+// Quantize M rows (x: [M, K] half/float) to q8_1 blocks in qb ([M][nb32]
+// blocks of 36B). Grid: M*nb32 blocks x 32 threads; block (m, b) owns
+// 32-block b of row m. Each thread independently recomputes the block
+// amax over all 32 elements (redundant but L1-served and sync-free),
+// then writes its own qs byte; thread 0 additionally stores (d, sum).
+// No shared memory, no __syncthreads, no cross-thread state at all.
+// Matches ggml quantize_q8_1: d = amax/127, q = round-half-away(xi/d).
+template <typename IN>
+__global__ void fq_quant_q8_1_kernel(const IN* __restrict__ x, uint8_t* __restrict__ qb,
+ int M, int K)
+{
+ int blk = blockIdx.x;
+ int nb32 = K / FQ_Q8_1_GROUP;
+ int m = blk / nb32;
+ int b = blk % nb32;
+ int tid = threadIdx.x;
+ if (m >= M)
+ return;
+ const IN* xr = x + (int64_t)m * K + (int64_t)b * 32;
+ float amax = 0.0f;
+ #pragma unroll
+ for (int i = 0; i < 32; i++)
+ {
+ float vi;
+ if constexpr (std::is_same<IN, __half>::value)
+ vi = __half2float(xr[i]);
+ else
+ vi = xr[i];
+ amax = fmaxf(amax, fabsf(vi));
+ }
+ float d = amax / 127.0f;
+ float v;
+ if constexpr (std::is_same<IN, __half>::value)
+ v = __half2float(xr[tid]);
+ else
+ v = xr[tid];
+ int q = (amax == 0.0f) ? 0 : (int)roundf(v / d);
+ q = q < -127 ? -127 : (q > 127 ? 127 : q);
+ uint8_t* qbblk = qb + ((int64_t)m * nb32 + b) * FQ_Q8_1_BYTES;
+ qbblk[4 + tid] = (uint8_t)(int8_t)q;
+ if (tid == 0)
+ {
+ float sum = 0.0f;
+ #pragma unroll
+ for (int i = 0; i < 32; i++)
+ {
+ if constexpr (std::is_same<IN, __half>::value)
+ sum += __half2float(xr[i]);
+ else
+ sum += xr[i];
+ }
+ // NOTE: store dh/sh with single u16 stores, NOT memcpy. The
+ // memcpy byte-split pattern (shr + 2x st.global.u8) loses the low
+ // byte with this toolchain (observed constant 0x1E65 stored as
+ // 0x1E00); single st.global.u16 is exact. qbblk is 2B-aligned
+ // (torch base alignment, b*36 even).
+ __half dh = __float2half_rn(d);
+ __half sh = __float2half_rn(sum);
+ uint16_t dhb, shb;
+ memcpy(&dhb, &dh, 2);
+ memcpy(&shb, &sh, 2);
+ reinterpret_cast<uint16_t*>(qbblk)[0] = dhb;
+ reinterpret_cast<uint16_t*>(qbblk)[1] = shb;
+ }
+}
+
+// Row-per-block IQ2_XXS q8 dot: block bidx computes output row n of x-row
+// m against the packed IQ2_XXS matrix. NT = blockDim.x threads take
+// 32-elem chunks round-robin; partials reduce sequentially (portable).
+// V2 (default, BOLT_FQ_Q8V2=1): the v2 dot needs no prologue tables at
+// all (const grid, inline signs, direct headers), so shmem is just the
+// reduction row; V2=false keeps the v1 staged path for same-binary A/B.
+template <typename OUT, bool V2>
+__global__ void fq_gemv_q8_iq2_kernel(const uint8_t* __restrict__ aqb,
+ const uint8_t* __restrict__ packed,
+ OUT* __restrict__ out,
+ int M, int N, int K, int64_t packed_stride,
+ int64_t qb_stride)
+{
+ int bidx = blockIdx.x;
+ int m = bidx / N;
+ int n = bidx % N;
+ int tid = threadIdx.x;
+ int nt = blockDim.x;
+ int nb = K / FQ_IQ2_XXS_GROUP;
+
+ extern __shared__ uint8_t sh[];
+ float* red;
+ uint32_t* hdrs = nullptr;
+ uint32_t* signs32 = nullptr;
+ __shared__ fq_tables_sh tab;
+ const uint8_t* grid8 = nullptr;
+ if constexpr (!V2)
+ {
+ // Layout: hdrs (nb*16 u32), signs32 (256 u32), red (nt floats).
+ hdrs = reinterpret_cast<uint32_t*>(sh);
+ signs32 = hdrs + (size_t)nb * 16;
+ red = reinterpret_cast<float*>(signs32 + 256);
+ fq_tables_load(&tab, 0, 1);
+ if (n < N)
+ fq_stage_iq2_hdrs_row(packed, packed_stride, hdrs, nb, n, N);
+ // Barrier BEFORE signs32_build consumes the staged tab: the staging
+ // above is cooperative (different threads write different entries) and
+ // the build reads other threads' entries. (The kernel's later
+ // __syncthreads only covers the dot; without this one the build races
+ // staging and signs come out zero/garbage nondeterministically.)
+ __syncthreads();
+ fq_signs32_build(&tab, signs32);
+ __syncthreads();
+ grid8 = reinterpret_cast<const uint8_t*>(tab.grid);
+ }
+ else
+ {
+ red = reinterpret_cast<float*>(sh);
+ }
+ float acc = 0.0f;
+ if (n < N)
+ {
+ if constexpr (V2)
+ acc = fq_dot_iq2_xxs_q8v2(packed + (int64_t)n * packed_stride,
+ aqb + (int64_t)m * qb_stride, K, tid, nt);
+ else
+ acc = fq_dot_iq2_xxs_q8(packed + (int64_t)n * packed_stride, hdrs, grid8,
+ signs32, aqb + (int64_t)m * qb_stride, K, tid, nt);
+ }
+ red[tid] = acc;
+ __syncthreads();
+ if (n < N && tid == 0)
+ {
+ float s = 0.0f;
+ for (int l = 0; l < nt; l++)
+ s = __fadd_rn(s, red[l]);
+ if constexpr (std::is_same<OUT, __half>::value)
+ out[(int64_t)m * N + n] = __float2half_rn(s);
+ else
+ out[(int64_t)m * N + n] = s;
+ }
+}
+
+// Row-per-block NVFP4 q8 dot: block bidx computes output row n of x-row
+// m. Same grid/mapping as the IQ2 kernel above; the dot is fq_dot_nvfp4_q8
+// (4 dp4a per 16-group, split packed/scales layout). The row-uniform
+// `global` multiplies once inside the dot.
+template <typename OUT>
+__global__ void fq_gemv_q8_nvfp4_kernel(const uint8_t* __restrict__ aqb,
+ const uint8_t* __restrict__ packed,
+ const uint8_t* __restrict__ scales,
+ float global,
+ OUT* __restrict__ out,
+ int M, int N, int K, int64_t packed_stride,
+ int64_t scales_stride, int64_t qb_stride)
+{
+ int bidx = blockIdx.x;
+ int m = bidx / N;
+ int n = bidx % N;
+ int tid = threadIdx.x;
+ int nt = blockDim.x;
+
+ extern __shared__ uint8_t sh[];
+ // Layout: e2m1db (128 int8), red (nt floats).
+ int8_t* e2m1db = reinterpret_cast<int8_t*>(sh);
+ float* red = reinterpret_cast<float*>(e2m1db + 128);
+
+ fq_e2m1db_build(e2m1db);
+ __syncthreads();
+ float acc = 0.0f;
+ if (n < N)
+ {
+ acc = fq_dot_nvfp4_q8(packed + (int64_t)n * packed_stride,
+ scales + (int64_t)n * scales_stride,
+ aqb + (int64_t)m * qb_stride, e2m1db,
+ K, global, tid, nt);
+ }
+ red[tid] = acc;
+ __syncthreads();
+ if (n < N && tid == 0)
+ {
+ float s = 0.0f;
+ for (int l = 0; l < nt; l++)
+ s = __fadd_rn(s, red[l]);
+ if constexpr (std::is_same<OUT, __half>::value)
+ out[(int64_t)m * N + n] = __float2half_rn(s);
+ else
+ out[(int64_t)m * N + n] = s;
+ }
+}
+
+// Row-per-block Q8_0 q8 dot: same grid; the dot is fq_dot_q8_0_q8
+// (8 dp4a per 32-block, weights are int8, no tables).
+template <typename OUT>
+__global__ void fq_gemv_q8_q8_kernel(const uint8_t* __restrict__ aqb,
+ const uint8_t* __restrict__ packed,
+ OUT* __restrict__ out,
+ int M, int N, int K, int64_t packed_stride,
+ int64_t qb_stride)
+{
+ int bidx = blockIdx.x;
+ int m = bidx / N;
+ int n = bidx % N;
+ int tid = threadIdx.x;
+ int nt = blockDim.x;
+
+ extern __shared__ float red[];
+
+ float acc = 0.0f;
+ if (n < N)
+ {
+ acc = fq_dot_q8_0_q8(packed + (int64_t)n * packed_stride,
+ aqb + (int64_t)m * qb_stride, K, tid, nt);
+ }
+ red[tid] = acc;
+ __syncthreads();
+ if (n < N && tid == 0)
+ {
+ float s = 0.0f;
+ for (int l = 0; l < nt; l++)
+ s = __fadd_rn(s, red[l]);
+ if constexpr (std::is_same<OUT, __half>::value)
+ out[(int64_t)m * N + n] = __float2half_rn(s);
+ else
+ out[(int64_t)m * N + n] = s;
+ }
+}
+
+// Cached global q8_1 scratch: [M][nb32(K)] 36B blocks. One buffer serves
+// all layers of a decode step (single stream: no two dots live at once;
+// allocated on first use = outside CUDA-graph capture, like act_cache).
+torch::Tensor fq_q8_scratch_cached(int dev, int M, int K)
+{
+ static thread_local std::map<std::tuple<int, int, int>, torch::Tensor> cache;
+ auto key = std::make_tuple(dev, M, K);
+ auto it = cache.find(key);
+ if (it != cache.end())
+ return it->second;
+ auto opts = torch::dtype(torch::kUInt8).device(torch::Device(torch::kCUDA, dev));
+ torch::Tensor t = torch::empty({M, (K / FQ_Q8_1_GROUP) * FQ_Q8_1_BYTES}, opts);
+ cache[key] = t;
+ return t;
+}
+
+} // namespace
+
+torch::Tensor fq_q8_scratch(int dev, int M, int K)
+{
+ return fq_q8_scratch_cached(dev, M, K);
+}
+
+void fq_quant_q8_1_rows(torch::Tensor x, torch::Tensor qb)
+{
+ TORCH_CHECK(x.is_cuda() && qb.is_cuda(), "tensors must be CUDA"); TORCH_CHECK(x.is_contiguous() && qb.is_contiguous(), "tensors must be contiguous");
+ TORCH_CHECK(x.dtype() == torch::kHalf || x.dtype() == torch::kFloat, "x must be half or float");
+ TORCH_CHECK_DIM(x, 2);
+ TORCH_CHECK_DIM(qb, 2);
+ int M = (int)x.size(0), K = (int)x.size(1);
+ TORCH_CHECK(K % FQ_Q8_1_GROUP == 0, "K must be a multiple of 32");
+ TORCH_CHECK((int)qb.size(0) == M &&
+ (int)qb.size(1) == (K / FQ_Q8_1_GROUP) * FQ_Q8_1_BYTES,
+ "qb must be [M, nb32*36]");
+ at::cuda::CUDAGuard guard(x.device());
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ int nb32 = K / FQ_Q8_1_GROUP;
+ auto launch = [&](auto* xp)
+ {
+ fq_quant_q8_1_kernel<<<M * nb32, 32, 0, stream>>>(
+ xp, qb.data_ptr<uint8_t>(), M, K);
+ };
+ if (x.dtype() == torch::kHalf)
+ launch(reinterpret_cast<const __half*>(x.data_ptr<at::Half>()));
+ else
+ launch(x.data_ptr<float>());
+}
+
+// Shared row-per-block q8 launch sizing: threads take 32-elem chunks
+// round-robin (same as the IQ2 kernel).
+static inline int fq_q8_nt(int K)
+{
+ int nchunks = K / 32;
+ return nchunks >= 256 ? 256 : ((nchunks + 31) / 32) * 32;
+}
+
+// q8_1-activation NVFP4 decode GEMV. x is quantized by the caller into
+// qb (fq_quant_q8_1_rows); out is half or float [M, N].
+void fq_gemv_nvfp4_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor scales,
+ double global_scale, torch::Tensor out)
+{
+ TORCH_CHECK(qb.is_cuda() && packed.is_cuda() && scales.is_cuda() && out.is_cuda(),
+ "tensors must be CUDA");
+ TORCH_CHECK(qb.is_contiguous() && packed.is_contiguous() && scales.is_contiguous() &&
+ out.is_contiguous(), "tensors must be contiguous");
+ TORCH_CHECK(out.dtype() == torch::kHalf || out.dtype() == torch::kFloat,
+ "out must be half or float");
+ TORCH_CHECK_DIM(qb, 2);
+ TORCH_CHECK_DIM(packed, 2);
+ TORCH_CHECK_DIM(scales, 2);
+ TORCH_CHECK_DIM(out, 2);
+ int M = (int)qb.size(0);
+ int N = (int)packed.size(0);
+ TORCH_CHECK((int)out.size(0) == M, "out rows must match qb rows");
+ TORCH_CHECK((int)out.size(1) == N, "out cols must match N");
+ int K = (int)qb.size(1) / FQ_Q8_1_BYTES * FQ_Q8_1_GROUP;
+ TORCH_CHECK(K % 32 == 0, "K must be a multiple of 32");
+ TORCH_CHECK((int)packed.size(1) == K / 2, "packed width must be K/2");
+ TORCH_CHECK((int)scales.size(1) == K / 16, "scales width must be K/16");
+ int64_t pstride = (int64_t)(K / 2);
+ int64_t sstride = (int64_t)(K / 16);
+ int64_t qb_stride = (int64_t)(K / FQ_Q8_1_GROUP) * FQ_Q8_1_BYTES;
+ int nt = fq_q8_nt(K);
+ size_t shmem = 128 * sizeof(int8_t) + (size_t)nt * sizeof(float);
+ at::cuda::CUDAGuard guard(qb.device());
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ auto launch = [&](auto* op)
+ {
+ fq_gemv_q8_nvfp4_kernel<std::decay_t<decltype(*op)>> <<<M * N, nt, shmem, stream>>>(
+ qb.data_ptr<uint8_t>(), packed.data_ptr<uint8_t>(), scales.data_ptr<uint8_t>(),
+ (float)global_scale, op, M, N, K, pstride, sstride, qb_stride);
+ };
+ if (out.dtype() == torch::kHalf)
+ launch(reinterpret_cast<__half*>(out.data_ptr<at::Half>()));
+ else
+ launch(out.data_ptr<float>());
+}
+
+// q8_1-activation Q8_0 decode GEMV. Same contract as above.
+void fq_gemv_q8_0_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out)
+{
+ TORCH_CHECK(qb.is_cuda() && packed.is_cuda() && out.is_cuda(), "tensors must be CUDA");
+ TORCH_CHECK(qb.is_contiguous() && packed.is_contiguous() && out.is_contiguous(),
+ "tensors must be contiguous");
+ TORCH_CHECK(out.dtype() == torch::kHalf || out.dtype() == torch::kFloat,
+ "out must be half or float");
+ TORCH_CHECK_DIM(qb, 2);
+ TORCH_CHECK_DIM(packed, 3);
+ TORCH_CHECK_DIM(out, 2);
+ int M = (int)qb.size(0);
+ int N = (int)packed.size(0);
+ TORCH_CHECK((int)out.size(0) == M, "out rows must match qb rows");
+ TORCH_CHECK((int)out.size(1) == N, "out cols must match N");
+ TORCH_CHECK_SIZE(packed, 2, FQ_Q8_0_BYTES);
+ int nb = (int)packed.size(1);
+ int K = nb * FQ_Q8_0_GROUP;
+ TORCH_CHECK((int)qb.size(1) == (K / FQ_Q8_1_GROUP) * FQ_Q8_1_BYTES, "qb width must match K");
+ int64_t pstride = (int64_t)nb * FQ_Q8_0_BYTES;
+ int64_t qb_stride = (int64_t)(K / FQ_Q8_1_GROUP) * FQ_Q8_1_BYTES;
+ int nt = fq_q8_nt(K);
+ size_t shmem = (size_t)nt * sizeof(float);
+ at::cuda::CUDAGuard guard(qb.device());
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ auto launch = [&](auto* op)
+ {
+ fq_gemv_q8_q8_kernel<std::decay_t<decltype(*op)>> <<<M * N, nt, shmem, stream>>>(
+ qb.data_ptr<uint8_t>(), packed.data_ptr<uint8_t>(),
+ op, M, N, K, pstride, qb_stride);
+ };
+ if (out.dtype() == torch::kHalf)
+ launch(reinterpret_cast<__half*>(out.data_ptr<at::Half>()));
+ else
+ launch(out.data_ptr<float>());
+}
+
+// q8_1-activation IQ2_XXS decode GEMV. x is quantized by the caller into
+// qb (fq_quant_q8_1_rows); out is half or float [M, N].
+void fq_gemv_iq2_xxs_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out)
+{
+ TORCH_CHECK(qb.is_cuda() && packed.is_cuda() && out.is_cuda(), "tensors must be CUDA");
+ TORCH_CHECK(qb.is_contiguous() && packed.is_contiguous() && out.is_contiguous(),
+ "tensors must be contiguous");
+ TORCH_CHECK(out.dtype() == torch::kHalf || out.dtype() == torch::kFloat,
+ "out must be half or float");
+ TORCH_CHECK_DIM(qb, 2);
+ TORCH_CHECK_DIM(packed, 3);
+ TORCH_CHECK_DIM(out, 2);
+ int M = (int)qb.size(0);
+ int N = (int)packed.size(0);
+ TORCH_CHECK((int)out.size(0) == M, "out rows must match qb rows");
+ TORCH_CHECK((int)out.size(1) == N, "out cols must match N");
+ TORCH_CHECK_SIZE(packed, 2, FQ_IQ2_XXS_BYTES);
+ int nb = (int)packed.size(1);
+ int K = nb * FQ_IQ2_XXS_GROUP;
+ TORCH_CHECK((int)qb.size(1) == (K / FQ_Q8_1_GROUP) * FQ_Q8_1_BYTES, "qb width must match K");
+ TORCH_CHECK(K <= 8192, "IQ2 header scratch covers K <= 8192");
+ int64_t pstride = (int64_t)nb * FQ_IQ2_XXS_BYTES;
+ int64_t qb_stride = (int64_t)(K / FQ_Q8_1_GROUP) * FQ_Q8_1_BYTES;
+ int nchunks = K / 32;
+ int nt = fq_q8_nt_iq2(K);
+ bool v2 = fq_use_q8v2();
+ size_t shmem = v2 ? (size_t)nt * sizeof(float)
+ : (size_t)nb * 16 * sizeof(uint32_t) + 256 * sizeof(uint32_t) +
+ (size_t)nt * sizeof(float);
+ at::cuda::CUDAGuard guard(qb.device());
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ auto launch = [&](auto* op)
+ {
+ if (v2)
+ fq_gemv_q8_iq2_kernel<std::decay_t<decltype(*op)>, true> <<<M * N, nt, shmem, stream>>>(
+ qb.data_ptr<uint8_t>(), packed.data_ptr<uint8_t>(),
+ op, M, N, K, pstride, qb_stride);
+ else
+ fq_gemv_q8_iq2_kernel<std::decay_t<decltype(*op)>, false> <<<M * N, nt, shmem, stream>>>(
+ qb.data_ptr<uint8_t>(), packed.data_ptr<uint8_t>(),
+ op, M, N, K, pstride, qb_stride);
+ };
+ if (out.dtype() == torch::kHalf)
+ launch(reinterpret_cast<__half*>(out.data_ptr<at::Half>()));
+ else
+ launch(out.data_ptr<float>());
+}
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_mlp.cu b/exllamav3/exllamav3_ext/foreign_quant/fq_mlp.cu
new file mode 100644
index 0000000..71d9ee9
--- /dev/null
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_mlp.cu
@@ -0,0 +1,185 @@
+// Fused shared-expert up + relu2 for foreign-quant MLPs (Bolt MoE layers,
+// dense IQ2_XXS shared expert): batch-1 up GEMV with the torch-exact relu2
+// epilogue, writing the [1, I] half activations to a caller-owned scratch
+// the down GEMV (plain fq_gemv_iq2_xxs, half in / float out) then consumes.
+//
+// Why: the shared expert runs on the torch path (up gemv + torch relu +
+// torch square + down gemv, 2 x 86 us + elementwise launches per layer at
+// Bolt shapes). The dots dominate and are unchanged here; this fuses only
+// the activation into the up epilogue, killing the relu/square launches,
+// the intermediate u allocation, and u's global round-trip. Same dot and
+// same epilogue arithmetic as fq_moe_up_kernel (fq_moe.cu), so output is
+// bit-identical to the torch path (not just fp16-tolerant).
+//
+// Portable CUDA/HIP: same contract as fq_gemv.cu (no PTX, no shuffles,
+// shared-memory reduction, __fmul_rn/__fadd_rn only).
+#include <cuda_fp16.h>
+#include <torch/extension.h>
+#include <c10/cuda/CUDAGuard.h>
+#include <ATen/cuda/CUDAContext.h>
+#include "../util.h"
+#include "fq_gemv.cuh"
+#include "fq_api.h"
+
+namespace {
+
+// Dense S=1 up kernel: block t computes up to 8 rows of up against x,
+// relu2 (rounded to half exactly like torch square(relu(half)): the sum is
+// rounded to half first, then the square of two half values is exact in
+// fp32 and rounds to half identically to a hardware hmul) into h.
+__global__ void fq_mlp_up_kernel(const __half* __restrict__ x,
+ const uint8_t* __restrict__ up,
+ int64_t up_stride,
+ __half* __restrict__ h,
+ int I, int K, int ntiles)
+{
+ int t = blockIdx.x;
+ int grp = threadIdx.x / FQ_GEMV_LANES; // 0..7 output slot in this block
+ int lane = threadIdx.x % FQ_GEMV_LANES;
+ int n = t * FQ_GEMV_OUT_PER_BLOCK + grp;
+
+ extern __shared__ __half sh[];
+ __half* xs = sh; // K halves: staged x
+ uint32_t* hdrs = reinterpret_cast<uint32_t*>(xs + K); // 8 x K/256*16 u32
+ float* red = reinterpret_cast<float*>(hdrs + 8 * (K / FQ_IQ2_XXS_GROUP) * 16);
+
+ __shared__ fq_tables_sh tab;
+ fq_tables_load(&tab, 0, 1);
+ fq_stage_x<__half>(x, xs, K);
+ fq_stage_iq2_hdrs(up, up_stride, hdrs, K / FQ_IQ2_XXS_GROUP,
+ t * FQ_GEMV_OUT_PER_BLOCK, I);
+ __syncthreads();
+
+ float u = 0.0f;
+ if (n < I)
+ u = fq_dot_iq2_xxs(up + (int64_t)n * up_stride, xs, &tab,
+ hdrs + (int64_t)grp * (K / FQ_IQ2_XXS_GROUP) * 16, K, lane);
+ red[threadIdx.x] = u;
+ __syncthreads();
+ if (n < I && lane == 0)
+ {
+ float su = 0.0f;
+ #pragma unroll
+ for (int l = 0; l < 32; l++)
+ su = __fadd_rn(su, red[grp * 32 + l]);
+ float uh = __half2float(__float2half_rn(su));
+ float au = uh > 0.0f ? uh * uh : 0.0f;
+ h[n] = __float2half_rn(au);
+ }
+}
+
+// q8_1-activation variant (Bolt phase 2): row-per-block integer-dp4a dot
+// over the globally quantized x, same torch-exact relu2 epilogue.
+// V2 template (default on): the v2 dot needs no prologue tables.
+template <bool V2>
+__global__ void fq_mlp_up_kernel_q8(const uint8_t* __restrict__ aqb,
+ const uint8_t* __restrict__ up,
+ int64_t up_stride,
+ __half* __restrict__ h,
+ int I, int K)
+{
+ int n = blockIdx.x;
+ int tid = threadIdx.x;
+ int nt = blockDim.x;
+ int nb = K / FQ_IQ2_XXS_GROUP;
+
+ extern __shared__ uint8_t sh8[];
+ float* red;
+ uint32_t* hdrs = nullptr;
+ uint32_t* signs32 = nullptr;
+ __shared__ fq_tables_sh tab;
+ const uint8_t* grid8 = nullptr;
+ if constexpr (!V2)
+ {
+ hdrs = reinterpret_cast<uint32_t*>(sh8);
+ signs32 = hdrs + (size_t)nb * 16;
+ red = reinterpret_cast<float*>(signs32 + 256);
+ fq_tables_load(&tab, 0, 1);
+ if (n < I)
+ fq_stage_iq2_hdrs_row(up, up_stride, hdrs, nb, n, I);
+ __syncthreads(); // staging race guard (see fq_gemv_q8.cu)
+ fq_signs32_build(&tab, signs32);
+ __syncthreads();
+ grid8 = reinterpret_cast<const uint8_t*>(tab.grid);
+ }
+ else
+ {
+ red = reinterpret_cast<float*>(sh8);
+ }
+
+ float u = 0.0f;
+ if (n < I)
+ {
+ if constexpr (V2)
+ u = fq_dot_iq2_xxs_q8v2(up + (int64_t)n * up_stride, aqb, K, tid, nt);
+ else
+ u = fq_dot_iq2_xxs_q8(up + (int64_t)n * up_stride, hdrs, grid8,
+ signs32, aqb, K, tid, nt);
+ }
+ red[tid] = u;
+ __syncthreads();
+ if (n < I && tid == 0)
+ {
+ float su = 0.0f;
+ for (int l = 0; l < nt; l++)
+ su = __fadd_rn(su, red[l]);
+ float uh = __half2float(__float2half_rn(su));
+ float au = uh > 0.0f ? uh * uh : 0.0f;
+ h[n] = __float2half_rn(au);
+ }
+}
+
+} // namespace
+
+void fq_mlp_shared_iq2xxs(torch::Tensor x, torch::Tensor up_packed, torch::Tensor h)
+{
+ TORCH_CHECK(x.is_cuda() && up_packed.is_cuda() && h.is_cuda(), "tensors must be CUDA");
+ TORCH_CHECK(x.is_contiguous() && up_packed.is_contiguous() && h.is_contiguous(),
+ "tensors must be contiguous");
+ TORCH_CHECK_DTYPE(x, kHalf);
+ TORCH_CHECK_DTYPE(h, kHalf);
+ TORCH_CHECK_DIM(x, 2);
+ TORCH_CHECK_DIM(up_packed, 3);
+ TORCH_CHECK_DIM(h, 2);
+ TORCH_CHECK((int)x.size(0) == 1 && (int)h.size(0) == 1, "batch-1 decode only");
+ int K = (int)x.size(1);
+ int I = (int)h.size(1);
+ TORCH_CHECK(K % FQ_IQ2_XXS_GROUP == 0, "K must be a multiple of 256");
+ TORCH_CHECK(K <= 8192, "IQ2 header scratch covers K <= 8192");
+ TORCH_CHECK((int)up_packed.size(0) == I && (int)up_packed.size(1) == K / FQ_IQ2_XXS_GROUP,
+ "up_packed must be [I, K/256, 66]");
+ TORCH_CHECK_SIZE(up_packed, 2, FQ_IQ2_XXS_BYTES);
+ at::cuda::CUDAGuard guard(x.device());
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ if (fq_use_q8act())
+ {
+ torch::Tensor aqb = fq_q8_scratch((int)x.get_device(), 1, K);
+ fq_quant_q8_1_rows(x, aqb);
+ int64_t up_stride = (int64_t)(K / FQ_IQ2_XXS_GROUP) * FQ_IQ2_XXS_BYTES;
+ int nchunks = K / 32;
+ int nt = fq_q8_nt_iq2(K);
+ bool v2 = fq_use_q8v2();
+ size_t shmem = v2 ? (size_t)nt * sizeof(float)
+ : (size_t)(K / FQ_IQ2_XXS_GROUP) * 16 * sizeof(uint32_t) +
+ 256 * sizeof(uint32_t) + (size_t)nt * sizeof(float);
+ if (v2)
+ fq_mlp_up_kernel_q8<true><<<I, nt, shmem, stream>>>(
+ aqb.data_ptr<uint8_t>(),
+ up_packed.data_ptr<uint8_t>(), up_stride,
+ reinterpret_cast<__half*>(h.data_ptr<at::Half>()), I, K);
+ else
+ fq_mlp_up_kernel_q8<false><<<I, nt, shmem, stream>>>(
+ aqb.data_ptr<uint8_t>(),
+ up_packed.data_ptr<uint8_t>(), up_stride,
+ reinterpret_cast<__half*>(h.data_ptr<at::Half>()), I, K);
+ return;
+ }
+ int64_t up_stride = (int64_t)(K / FQ_IQ2_XXS_GROUP) * FQ_IQ2_XXS_BYTES;
+ int ntiles = (I + FQ_GEMV_OUT_PER_BLOCK - 1) / FQ_GEMV_OUT_PER_BLOCK;
+ size_t shmem = ((size_t)K) * sizeof(__half) + FQ_GEMV_THREADS * sizeof(float) +
+ ((size_t)8 * (K / FQ_IQ2_XXS_GROUP)) * 16 * sizeof(uint32_t);
+ fq_mlp_up_kernel<<<ntiles, FQ_GEMV_THREADS, shmem, stream>>>(
+ reinterpret_cast<const __half*>(x.data_ptr<at::Half>()),
+ up_packed.data_ptr<uint8_t>(), up_stride,
+ reinterpret_cast<__half*>(h.data_ptr<at::Half>()), I, K, ntiles);
+}
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_moe.cu b/exllamav3/exllamav3_ext/foreign_quant/fq_moe.cu
new file mode 100644
index 0000000..9620857
--- /dev/null
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_moe.cu
@@ -0,0 +1,233 @@
+// Grouped decode MoE for foreign-quant experts (Bolt latent MoE, gateless
+// relu2, IQ2_XXS): the selected experts' up + down GEMVs run in two launches
+// (plus a weighted-fold launch), replacing the per-expert torch loop (9 up +
+// 9 down launches, plus the argsort / bincount+tolist host sync /
+// index_select / index_add_ per MoE layer that the dense dispatch pays at
+// decode).
+//
+// Grid (BOTH kernels): one 256-thread block per (slot s, 8-row tile t) --
+// the same parallelization as fq_gemv (one block must NOT loop all tiles:
+// a single block running every tile sequentially leaves 73 of 82 SMs idle
+// and measured 6x slower than the per-expert loop). The up kernel writes
+// the relu2-half activations to a global [S, I] scratch (46 KB at Bolt
+// shapes); the down kernel stages one scratch row and writes partial[s].
+// A third single-block kernel folds partial with the routing weights in
+// slot order (fp32). Element arithmetic is the same fq_dot_* as fq_gemv.cu
+// (shared header fq_gemv.cuh); only accumulation/summation ORDERS differ
+// from the dense torch path (fp16 tolerance).
+//
+// Portable CUDA/HIP: same contract as fq_gemv.cu (no PTX, no shuffles,
+// shared-memory reduction, __fmul_rn/__fadd_rn only).
+#include <cuda_fp16.h>
+#include <map>
+#include <torch/extension.h>
+#include <c10/cuda/CUDAGuard.h>
+#include <ATen/cuda/CUDAContext.h>
+#include "../util.h"
+#include "fq_gemv.cuh"
+#include "fq_api.h"
+
+namespace {
+
+// Up kernel: block (s, t) computes up to 8 rows of up[sel[s]] against h,
+// relu2 (rounded to half exactly like torch square(relu(half)): the sum is
+// rounded to half first, then the square of two half values is exact in
+// fp32 and rounds to half identically to a hardware hmul) into act[s].
+__global__ void fq_moe_up_kernel(const __half* __restrict__ h,
+ const int64_t* __restrict__ sel,
+ const uint8_t* const* __restrict__ up_bases,
+ int64_t up_stride,
+ __half* __restrict__ act,
+ int S, int I, int K, int E, int ntiles_u)
+{
+ int b = blockIdx.x;
+ int s = b / ntiles_u;
+ int t = b % ntiles_u;
+ int grp = threadIdx.x / FQ_GEMV_LANES; // 0..7 output slot in this block
+ int lane = threadIdx.x % FQ_GEMV_LANES;
+ int64_t e = sel[s];
+ e = (e < 0 || e >= E) ? 0 : e;
+ int n = t * FQ_GEMV_OUT_PER_BLOCK + grp;
+
+ extern __shared__ __half sh[];
+ __half* xs = sh; // K halves: staged h
+ uint32_t* hdrs = reinterpret_cast<uint32_t*>(xs + K); // 8 x K/256*16 u32
+ float* red = reinterpret_cast<float*>(hdrs + 8 * (K / FQ_IQ2_XXS_GROUP) * 16);
+
+ __shared__ fq_tables_sh tab;
+ fq_tables_load(&tab, 0, 1);
+ fq_stage_x<__half>(h, xs, K);
+ fq_stage_iq2_hdrs(up_bases[e], up_stride, hdrs, K / FQ_IQ2_XXS_GROUP,
+ t * FQ_GEMV_OUT_PER_BLOCK, I);
+ __syncthreads();
+
+ float u = 0.0f;
+ if (n < I)
+ u = fq_dot_iq2_xxs(up_bases[e] + (int64_t)n * up_stride, xs, &tab,
+ hdrs + (int64_t)grp * (K / FQ_IQ2_XXS_GROUP) * 16, K, lane);
+ red[threadIdx.x] = u;
+ __syncthreads();
+ if (n < I && lane == 0)
+ {
+ float su = 0.0f;
+ #pragma unroll
+ for (int l = 0; l < 32; l++)
+ su = __fadd_rn(su, red[grp * 32 + l]);
+ float uh = __half2float(__float2half_rn(su));
+ float au = uh > 0.0f ? uh * uh : 0.0f;
+ act[(int64_t)s * I + n] = __float2half_rn(au);
+ }
+}
+
+// Down kernel: block (s, t) stages act[s] and computes up to 8 rows of
+// down[sel[s]] into partial[s].
+__global__ void fq_moe_down_kernel(const __half* __restrict__ act,
+ const int64_t* __restrict__ sel,
+ const uint8_t* const* __restrict__ down_bases,
+ int64_t down_stride,
+ float* __restrict__ partial,
+ int S, int I, int K, int E, int ntiles_d)
+{
+ int b = blockIdx.x;
+ int s = b / ntiles_d;
+ int t = b % ntiles_d;
+ int grp = threadIdx.x / FQ_GEMV_LANES;
+ int lane = threadIdx.x % FQ_GEMV_LANES;
+ int64_t e = sel[s];
+ e = (e < 0 || e >= E) ? 0 : e;
+ int n = t * FQ_GEMV_OUT_PER_BLOCK + grp;
+
+ extern __shared__ __half sh[];
+ __half* xs = sh; // I halves: staged act row
+ uint32_t* hdrs = reinterpret_cast<uint32_t*>(xs + I); // 8 x I/256*16 u32
+ float* red = reinterpret_cast<float*>(hdrs + 8 * (I / FQ_IQ2_XXS_GROUP) * 16);
+
+ __shared__ fq_tables_sh tab;
+ fq_tables_load(&tab, 0, 1);
+ fq_stage_x<__half>(act + (int64_t)s * I, xs, I);
+ fq_stage_iq2_hdrs(down_bases[e], down_stride, hdrs, I / FQ_IQ2_XXS_GROUP,
+ t * FQ_GEMV_OUT_PER_BLOCK, K);
+ __syncthreads();
+
+ float p = 0.0f;
+ if (n < K)
+ p = fq_dot_iq2_xxs(down_bases[e] + (int64_t)n * down_stride, xs, &tab,
+ hdrs + (int64_t)grp * (I / FQ_IQ2_XXS_GROUP) * 16, I, lane);
+ red[threadIdx.x] = p;
+ __syncthreads();
+ if (n < K && lane == 0)
+ {
+ float sp = 0.0f;
+ #pragma unroll
+ for (int l = 0; l < 32; l++)
+ sp = __fadd_rn(sp, red[grp * 32 + l]);
+ partial[(int64_t)s * K + n] = sp;
+ }
+}
+
+// Weighted fold: out[k] = sum_s w[s] * partial[s, k]. One block, 256
+// threads, each a strided subset of K.
+__global__ void fq_moe_combine_kernel(const float* __restrict__ partial,
+ const __half* __restrict__ wts,
+ float* __restrict__ out, int S, int K)
+{
+ for (int k = blockIdx.x * blockDim.x + threadIdx.x; k < K; k += gridDim.x * blockDim.x)
+ {
+ float acc = 0.0f;
+ #pragma unroll
+ for (int s = 0; s < 32; s++)
+ {
+ if (s < S)
+ acc = __fadd_rn(acc, __fmul_rn(partial[(int64_t)s * K + k],
+ __half2float(wts[s])));
+ }
+ out[k] = acc;
+ }
+}
+
+} // namespace
+
+void fq_moe_iq2xxs_grouped(torch::Tensor h, torch::Tensor sel, torch::Tensor wts,
+ torch::Tensor up_ptrs, torch::Tensor down_ptrs,
+ int64_t up_stride, int64_t down_stride,
+ torch::Tensor partial, torch::Tensor out)
+{
+ TORCH_CHECK(h.is_cuda() && sel.is_cuda() && wts.is_cuda() && partial.is_cuda() && out.is_cuda(),
+ "tensors must be CUDA");
+ TORCH_CHECK(h.is_contiguous() && sel.is_contiguous() && wts.is_contiguous() &&
+ partial.is_contiguous() && out.is_contiguous(), "tensors must be contiguous");
+ TORCH_CHECK_DTYPE(h, kHalf);
+ TORCH_CHECK_DTYPE(sel, kLong);
+ TORCH_CHECK_DTYPE(wts, kHalf);
+ TORCH_CHECK_DTYPE(up_ptrs, kLong);
+ TORCH_CHECK_DTYPE(down_ptrs, kLong);
+ TORCH_CHECK_DTYPE(partial, kFloat);
+ TORCH_CHECK_DTYPE(out, kFloat);
+ TORCH_CHECK_DIM(h, 2);
+ TORCH_CHECK((int)h.size(0) == 1, "grouped MoE covers batch-1 decode");
+ int K = (int)h.size(1);
+ int S = (int)sel.numel();
+ TORCH_CHECK((int)wts.numel() == S, "sel/wts must agree");
+ TORCH_CHECK((int)partial.size(0) == S && (int)partial.size(1) == K, "partial must be [S, K]");
+ TORCH_CHECK((int)out.size(0) == 1 && (int)out.size(1) == K, "out must be [1, K]");
+ TORCH_CHECK(S >= 1 && S <= 32, "top-k must be 1..32");
+ TORCH_CHECK(K % FQ_IQ2_XXS_GROUP == 0, "expert width K must be a multiple of 256");
+ TORCH_CHECK(K <= 4096, "expert width K <= 4096 (shared scratch)");
+ int E = (int)up_ptrs.numel();
+ TORCH_CHECK(E > 0 && (int)down_ptrs.numel() == E, "expert pointer tables must agree");
+ if (fq_use_q8moe())
+ {
+ // q8_1-activation path (fq_moe_q8.cu): quantize once, integer dp4a
+ // dots. Same contract (fp16 tolerance vs the dense torch path).
+ fq_moe_iq2xxs_grouped_q8(h, sel, wts, up_ptrs, down_ptrs,
+ up_stride, down_stride, partial, out);
+ return;
+ }
+ at::cuda::CUDAGuard guard(h.device());
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ // Widths from the row strides: up rows are [K/256, 66] (K = expert
+ // input width), down rows are [I/256, 66] (I = intermediate width).
+ TORCH_CHECK(up_stride == (int64_t)(K / FQ_IQ2_XXS_GROUP) * FQ_IQ2_XXS_BYTES,
+ "up stride must match K");
+ TORCH_CHECK(down_stride % FQ_IQ2_XXS_BYTES == 0, "bad down stride");
+ int I = (int)(down_stride / FQ_IQ2_XXS_BYTES) * FQ_IQ2_XXS_GROUP;
+ TORCH_CHECK(I % FQ_IQ2_XXS_GROUP == 0 && I <= 4096, "intermediate width 256..4096");
+ // The [S, I] half activation scratch lives in the caller's partial
+ // buffer tail? No: separate cached workspace below (partial stays [S,K]).
+ int ntiles_u = (I + FQ_GEMV_OUT_PER_BLOCK - 1) / FQ_GEMV_OUT_PER_BLOCK;
+ int ntiles_d = (K + FQ_GEMV_OUT_PER_BLOCK - 1) / FQ_GEMV_OUT_PER_BLOCK;
+ // Activation scratch: cached per (device, S, I) on the CUDA device.
+ static thread_local std::map<std::tuple<int, int, int>, torch::Tensor> act_cache;
+ auto key = std::make_tuple((int)h.get_device(), S, I);
+ auto it = act_cache.find(key);
+ torch::Tensor act;
+ if (it != act_cache.end())
+ act = it->second;
+ else
+ {
+ act = torch::empty({S, I}, torch::dtype(torch::kHalf).device(h.device()));
+ act_cache[key] = act;
+ }
+ size_t shmem_u = ((size_t)K) * sizeof(__half) + FQ_GEMV_THREADS * sizeof(float) +
+ ((size_t)8 * (K / FQ_IQ2_XXS_GROUP)) * 16 * sizeof(uint32_t);
+ fq_moe_up_kernel<<<S * ntiles_u, FQ_GEMV_THREADS, shmem_u, stream>>>(
+ reinterpret_cast<const __half*>(h.data_ptr<at::Half>()),
+ sel.data_ptr<int64_t>(),
+ reinterpret_cast<const uint8_t* const*>(up_ptrs.data_ptr<int64_t>()),
+ up_stride,
+ reinterpret_cast<__half*>(act.data_ptr<at::Half>()),
+ S, I, K, E, ntiles_u);
+ size_t shmem_d = ((size_t)I) * sizeof(__half) + FQ_GEMV_THREADS * sizeof(float) +
+ ((size_t)8 * (I / FQ_IQ2_XXS_GROUP)) * 16 * sizeof(uint32_t);
+ fq_moe_down_kernel<<<S * ntiles_d, FQ_GEMV_THREADS, shmem_d, stream>>>(
+ reinterpret_cast<const __half*>(act.data_ptr<at::Half>()),
+ sel.data_ptr<int64_t>(),
+ reinterpret_cast<const uint8_t* const*>(down_ptrs.data_ptr<int64_t>()),
+ down_stride,
+ partial.data_ptr<float>(), S, I, K, E, ntiles_d);
+ int nblocks = (K + 255) / 256;
+ fq_moe_combine_kernel<<<nblocks, 256, 0, stream>>>(
+ partial.data_ptr<float>(),
+ reinterpret_cast<const __half*>(wts.data_ptr<at::Half>()),
+ out.data_ptr<float>(), S, K);
+}
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_moe_kq.cu b/exllamav3/exllamav3_ext/foreign_quant/fq_moe_kq.cu
new file mode 100644
index 0000000..1c84d42
--- /dev/null
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_moe_kq.cu
@@ -0,0 +1,263 @@
+// Grouped decode MoE with q8_1 activations for K-quant/IQ4_XS experts
+// same (slot, tile) grid as fq_moe_q8.cu (one 256-thread
+// block per (slot s, 8-row tile t), gate+up + down + fold launches) but the
+// KQ/IQ4_XS integer-dp4a dots (fq_dot_*_q8 in fq_gemv.cuh) and a SwiGLU
+// epilogue (MiniCPM MoE is SwiGLU, unlike Bolt's gateless latent MoE).
+// h [1, K] is quantized once; the [S, I] act scratch is quantized per slot
+// row for the down dots. FMT selects the dot (0 = Q4_K, 1 = Q5_K,
+// 2 = Q6_K, 3 = IQ4_XS). Portable (no PTX/shuffles).
+#include <cuda_fp16.h>
+#include <map>
+#include <torch/extension.h>
+#include <c10/cuda/CUDAGuard.h>
+#include <ATen/cuda/CUDAContext.h>
+#include "../util.h"
+#include "fq_gemv.cuh"
+#include "fq_api.h"
+
+namespace {
+
+// Up+gate kernel: block (s, t) computes up to 8 gate rows and 8 up rows of
+// expert sel[s] against the pre-quantized h (aqb, one row), SwiGLU epilogue
+// (silu(gate) * up, torch half path) into act[s]. Lane mapping: group grp
+// owns output n; lane l takes sub-chunks round-robin (the dot's (lane, 32)
+// split), 32 partials reduce in shared.
+template <int FMT>
+__global__ void fq_moe_kq_upgate_kernel(const uint8_t* __restrict__ aqb,
+ const int64_t* __restrict__ sel,
+ const uint8_t* const* __restrict__ gate_bases,
+ const uint8_t* const* __restrict__ up_bases,
+ int64_t gate_stride,
+ int64_t up_stride,
+ int64_t qb_stride,
+ __half* __restrict__ act,
+ int S, int I, int K, int E, int ntiles_u)
+{
+ int b = blockIdx.x;
+ int s = b / ntiles_u;
+ int t = b % ntiles_u;
+ int grp = threadIdx.x / FQ_GEMV_LANES;
+ int lane = threadIdx.x % FQ_GEMV_LANES;
+ int64_t e = sel[s];
+ e = (e < 0 || e >= E) ? 0 : e;
+ int n = t * FQ_GEMV_OUT_PER_BLOCK + grp;
+
+ extern __shared__ float red[];
+
+ float g = 0.0f, u = 0.0f;
+ if (n < I)
+ {
+ const uint8_t* gr = gate_bases[e] + (int64_t)n * gate_stride;
+ const uint8_t* ur = up_bases[e] + (int64_t)n * up_stride;
+ if constexpr (FMT == 0)
+ {
+ g = fq_dot_q4_k_q8(gr, aqb, K, lane, FQ_GEMV_LANES);
+ u = fq_dot_q4_k_q8(ur, aqb, K, lane, FQ_GEMV_LANES);
+ }
+ else if constexpr (FMT == 1)
+ {
+ g = fq_dot_q5_k_q8(gr, aqb, K, lane, FQ_GEMV_LANES);
+ u = fq_dot_q5_k_q8(ur, aqb, K, lane, FQ_GEMV_LANES);
+ }
+ else if constexpr (FMT == 2)
+ {
+ g = fq_dot_q6_k_q8(gr, aqb, K, lane, FQ_GEMV_LANES);
+ u = fq_dot_q6_k_q8(ur, aqb, K, lane, FQ_GEMV_LANES);
+ }
+ else
+ {
+ g = fq_dot_iq4_xs_q8(gr, aqb, K, lane, FQ_GEMV_LANES);
+ u = fq_dot_iq4_xs_q8(ur, aqb, K, lane, FQ_GEMV_LANES);
+ }
+ }
+ // Two reductions in one shared row: red[2*tid] = g, red[2*tid+1] = u.
+ red[2 * threadIdx.x] = g;
+ red[2 * threadIdx.x + 1] = u;
+ __syncthreads();
+ if (n < I && lane == 0)
+ {
+ float sg = 0.0f, su = 0.0f;
+ #pragma unroll
+ for (int l = 0; l < 32; l++)
+ {
+ sg = __fadd_rn(sg, red[(grp * 32 + l) * 2]);
+ su = __fadd_rn(su, red[(grp * 32 + l) * 2 + 1]);
+ }
+ // Torch half path: g/u round to half (Linear out_dtype = half),
+ // silu in float, product back to half.
+ float gh = __half2float(__float2half_rn(sg));
+ float uh = __half2float(__float2half_rn(su));
+ float sig = 1.0f / (1.0f + expf(-gh));
+ act[(int64_t)s * I + n] = __float2half_rn(sig * gh * uh);
+ }
+}
+
+// Down kernel: block (s, t) dots down[sel[s]] rows against the
+// pre-quantized act row s into partial[s]. Same lane split as above.
+template <int FMT>
+__global__ void fq_moe_kq_down_kernel(const uint8_t* __restrict__ aqb,
+ int64_t qb_stride,
+ const int64_t* __restrict__ sel,
+ const uint8_t* __restrict__ const* down_bases,
+ int64_t down_stride,
+ float* __restrict__ partial,
+ int S, int I, int K, int E, int ntiles_d)
+{
+ int b = blockIdx.x;
+ int s = b / ntiles_d;
+ int t = b % ntiles_d;
+ int grp = threadIdx.x / FQ_GEMV_LANES;
+ int lane = threadIdx.x % FQ_GEMV_LANES;
+ int64_t e = sel[s];
+ e = (e < 0 || e >= E) ? 0 : e;
+ int n = t * FQ_GEMV_OUT_PER_BLOCK + grp;
+
+ extern __shared__ float red[];
+
+ float p = 0.0f;
+ if (n < K)
+ {
+ const uint8_t* dr = down_bases[e] + (int64_t)n * down_stride;
+ const uint8_t* aq = aqb + (int64_t)s * qb_stride;
+ if constexpr (FMT == 0)
+ p = fq_dot_q4_k_q8(dr, aq, I, lane, FQ_GEMV_LANES);
+ else if constexpr (FMT == 1)
+ p = fq_dot_q5_k_q8(dr, aq, I, lane, FQ_GEMV_LANES);
+ else if constexpr (FMT == 2)
+ p = fq_dot_q6_k_q8(dr, aq, I, lane, FQ_GEMV_LANES);
+ else
+ p = fq_dot_iq4_xs_q8(dr, aq, I, lane, FQ_GEMV_LANES);
+ }
+ red[threadIdx.x] = p;
+ __syncthreads();
+ if (n < K && lane == 0)
+ {
+ float sp = 0.0f;
+ #pragma unroll
+ for (int l = 0; l < 32; l++)
+ sp = __fadd_rn(sp, red[grp * 32 + l]);
+ partial[(int64_t)s * K + n] = sp;
+ }
+}
+
+} // namespace
+
+// Weighted fold (same as fq_moe_q8.cu's): out[k] = sum_s w[s]*partial[s,k].
+__global__ void fq_moe_kq_combine_kernel(const float* __restrict__ partial,
+ const __half* __restrict__ wts,
+ float* __restrict__ out, int S, int K)
+{
+ for (int k = blockIdx.x * blockDim.x + threadIdx.x; k < K; k += gridDim.x * blockDim.x)
+ {
+ float acc = 0.0f;
+ #pragma unroll
+ for (int s = 0; s < 32; s++)
+ {
+ if (s < S)
+ acc = __fadd_rn(acc, __fmul_rn(partial[(int64_t)s * K + k],
+ __half2float(wts[s])));
+ }
+ out[k] = acc;
+ }
+}
+
+template <int FMT>
+static void fq_moe_kq_grouped_launch(torch::Tensor h, torch::Tensor sel, torch::Tensor wts,
+ torch::Tensor gate_ptrs, torch::Tensor up_ptrs,
+ torch::Tensor down_ptrs,
+ int64_t gate_stride, int64_t up_stride,
+ int64_t down_stride, int64_t block_bytes,
+ torch::Tensor partial, torch::Tensor out)
+{
+ int K = (int)h.size(1);
+ int S = (int)sel.numel();
+ TORCH_CHECK_DTYPE(h, kHalf);
+ int E = (int)up_ptrs.numel();
+ // I from the down row stride (down rows are I-wide, like Bolt's
+ // derivation from down_stride).
+ int I = (int)(down_stride / block_bytes) * FQ_Q4_K_GROUP;
+ at::cuda::CUDAGuard guard(h.device());
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ int ntiles_u = (I + FQ_GEMV_OUT_PER_BLOCK - 1) / FQ_GEMV_OUT_PER_BLOCK;
+ int ntiles_d = (K + FQ_GEMV_OUT_PER_BLOCK - 1) / FQ_GEMV_OUT_PER_BLOCK;
+ torch::Tensor qb_h = fq_q8_scratch(h.get_device(), 1, K);
+ fq_quant_q8_1_rows(h, qb_h);
+ int64_t qb_stride_h = (int64_t)(K / FQ_Q8_1_GROUP) * FQ_Q8_1_BYTES;
+ static thread_local std::map<std::tuple<int, int, int>, torch::Tensor> act_cache;
+ auto key = std::make_tuple((int)h.get_device(), S, I);
+ auto it = act_cache.find(key);
+ torch::Tensor act;
+ if (it != act_cache.end())
+ act = it->second;
+ else
+ {
+ act = torch::empty({S, I}, torch::dtype(torch::kHalf).device(h.device()));
+ act_cache[key] = act;
+ }
+ // Up+gate: 2 floats per thread in shared (g and u side by side).
+ size_t shmem_u = (size_t)FQ_GEMV_THREADS * 2 * sizeof(float);
+ fq_moe_kq_upgate_kernel<FMT><<<S * ntiles_u, FQ_GEMV_THREADS, shmem_u, stream>>>(
+ qb_h.data_ptr<uint8_t>(), sel.data_ptr<int64_t>(),
+ reinterpret_cast<const uint8_t* const*>(gate_ptrs.data_ptr<int64_t>()),
+ reinterpret_cast<const uint8_t* const*>(up_ptrs.data_ptr<int64_t>()),
+ gate_stride, up_stride, qb_stride_h,
+ reinterpret_cast<__half*>(act.data_ptr<at::Half>()),
+ S, I, K, E, ntiles_u);
+ torch::Tensor qb_act = fq_q8_scratch(h.get_device(), S, I);
+ fq_quant_q8_1_rows(act, qb_act);
+ int64_t qb_stride_a = (int64_t)(I / FQ_Q8_1_GROUP) * FQ_Q8_1_BYTES;
+ size_t shmem_d = (size_t)FQ_GEMV_THREADS * sizeof(float);
+ fq_moe_kq_down_kernel<FMT><<<S * ntiles_d, FQ_GEMV_THREADS, shmem_d, stream>>>(
+ qb_act.data_ptr<uint8_t>(), qb_stride_a, sel.data_ptr<int64_t>(),
+ reinterpret_cast<const uint8_t* const*>(down_ptrs.data_ptr<int64_t>()),
+ down_stride, partial.data_ptr<float>(), S, I, K, E, ntiles_d);
+ int nblocks = (K + 255) / 256;
+ fq_moe_kq_combine_kernel<<<nblocks, 256, 0, stream>>>(
+ partial.data_ptr<float>(),
+ reinterpret_cast<const __half*>(wts.data_ptr<at::Half>()),
+ out.data_ptr<float>(), S, K);
+}
+
+void fq_moe_q4k_grouped_q8(torch::Tensor h, torch::Tensor sel, torch::Tensor wts,
+ torch::Tensor gate_ptrs, torch::Tensor up_ptrs,
+ torch::Tensor down_ptrs,
+ int64_t gate_stride, int64_t up_stride, int64_t down_stride,
+ torch::Tensor partial, torch::Tensor out)
+{
+ fq_moe_kq_grouped_launch<0>(h, sel, wts, gate_ptrs, up_ptrs, down_ptrs,
+ gate_stride, up_stride, down_stride,
+ FQ_Q4_K_BYTES, partial, out);
+}
+
+void fq_moe_q5k_grouped_q8(torch::Tensor h, torch::Tensor sel, torch::Tensor wts,
+ torch::Tensor gate_ptrs, torch::Tensor up_ptrs,
+ torch::Tensor down_ptrs,
+ int64_t gate_stride, int64_t up_stride, int64_t down_stride,
+ torch::Tensor partial, torch::Tensor out)
+{
+ fq_moe_kq_grouped_launch<1>(h, sel, wts, gate_ptrs, up_ptrs, down_ptrs,
+ gate_stride, up_stride, down_stride,
+ FQ_Q5_K_BYTES, partial, out);
+}
+
+void fq_moe_q6k_grouped_q8(torch::Tensor h, torch::Tensor sel, torch::Tensor wts,
+ torch::Tensor gate_ptrs, torch::Tensor up_ptrs,
+ torch::Tensor down_ptrs,
+ int64_t gate_stride, int64_t up_stride, int64_t down_stride,
+ torch::Tensor partial, torch::Tensor out)
+{
+ fq_moe_kq_grouped_launch<2>(h, sel, wts, gate_ptrs, up_ptrs, down_ptrs,
+ gate_stride, up_stride, down_stride,
+ FQ_Q6_K_BYTES, partial, out);
+}
+
+void fq_moe_iq4xs_grouped_q8(torch::Tensor h, torch::Tensor sel, torch::Tensor wts,
+ torch::Tensor gate_ptrs, torch::Tensor up_ptrs,
+ torch::Tensor down_ptrs,
+ int64_t gate_stride, int64_t up_stride, int64_t down_stride,
+ torch::Tensor partial, torch::Tensor out)
+{
+ fq_moe_kq_grouped_launch<3>(h, sel, wts, gate_ptrs, up_ptrs, down_ptrs,
+ gate_stride, up_stride, down_stride,
+ FQ_IQ4_XS_BYTES, partial, out);
+}
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_moe_q8.cu b/exllamav3/exllamav3_ext/foreign_quant/fq_moe_q8.cu
new file mode 100644
index 0000000..7e90b0d
--- /dev/null
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_moe_q8.cu
@@ -0,0 +1,267 @@
+// Grouped decode MoE with q8_1 activations (Bolt phase 2): same grid as
+// fq_moe.cu (one 256-thread block per (slot s, 8-row tile t), up + down +
+// fold launches) but integer-dp4a dots over once-per-step q8_1 activations
+// (llama.cpp mmvq design). h [1, K] is quantized once for the up dots;
+// the [S, I] act scratch is quantized per slot row for the down dots.
+// Opt-in via BOLT_FQ_Q8MOE=1 (branch inside fq_moe_iq2xxs_grouped).
+// Portable (no PTX/shuffles; __dp4a via fq_dp4a with HIP fallback).
+#include <cuda_fp16.h>
+#include <map>
+#include <torch/extension.h>
+#include <c10/cuda/CUDAGuard.h>
+#include <ATen/cuda/CUDAContext.h>
+#include "../util.h"
+#include "fq_gemv.cuh"
+#include "fq_api.h"
+
+namespace {
+
+// Up kernel: block (s, t) computes up to 8 rows of up[sel[s]] against the
+// pre-quantized h (aqb, one row), relu2 epilogue torch-exact, into act[s].
+// Lane mapping: group grp owns output n; lane l takes 32-chunks round-robin
+// (the fq_dot_iq2_xxs_q8 (lane, 32) split), 32 partials reduce in shared.
+// V2 template (default on): the v2 dot needs no prologue tables.
+template <bool V2>
+__global__ void fq_moe_up_kernel_q8(const uint8_t* __restrict__ aqb,
+ const int64_t* __restrict__ sel,
+ const uint8_t* const* __restrict__ up_bases,
+ int64_t up_stride,
+ int64_t qb_stride,
+ __half* __restrict__ act,
+ int S, int I, int K, int E, int ntiles_u)
+{
+ int b = blockIdx.x;
+ int s = b / ntiles_u;
+ int t = b % ntiles_u;
+ int grp = threadIdx.x / FQ_GEMV_LANES;
+ int lane = threadIdx.x % FQ_GEMV_LANES;
+ int64_t e = sel[s];
+ e = (e < 0 || e >= E) ? 0 : e;
+ int n = t * FQ_GEMV_OUT_PER_BLOCK + grp;
+
+ extern __shared__ uint8_t sh[];
+ float* red;
+ uint32_t* hdrs = nullptr;
+ uint32_t* signs32 = nullptr;
+ __shared__ fq_tables_sh tab;
+ const uint8_t* grid8 = nullptr;
+ int nb = K / FQ_IQ2_XXS_GROUP;
+ if constexpr (!V2)
+ {
+ // Layout: hdrs (8 x nb*16 u32), signs32 (256 u32), red (256 floats).
+ hdrs = reinterpret_cast<uint32_t*>(sh);
+ signs32 = hdrs + (size_t)8 * nb * 16;
+ red = reinterpret_cast<float*>(signs32 + 256);
+ fq_tables_load(&tab, 0, 1);
+ fq_stage_iq2_hdrs(up_bases[e], up_stride, hdrs, nb,
+ t * FQ_GEMV_OUT_PER_BLOCK, I);
+ // Barrier BEFORE signs32_build consumes the staged tab (same race as
+ // the row-per-block kernel: staging is cooperative, the build reads
+ // other threads' entries).
+ __syncthreads();
+ fq_signs32_build(&tab, signs32);
+ __syncthreads();
+ grid8 = reinterpret_cast<const uint8_t*>(tab.grid);
+ }
+ else
+ {
+ red = reinterpret_cast<float*>(sh);
+ }
+
+ float u = 0.0f;
+ if (n < I)
+ {
+ if constexpr (V2)
+ u = fq_dot_iq2_xxs_q8v2(up_bases[e] + (int64_t)n * up_stride,
+ aqb, K, lane, FQ_GEMV_LANES);
+ else
+ u = fq_dot_iq2_xxs_q8(up_bases[e] + (int64_t)n * up_stride,
+ hdrs + (int64_t)grp * nb * 16, grid8, signs32,
+ aqb, K, lane, FQ_GEMV_LANES);
+ }
+ red[threadIdx.x] = u;
+ __syncthreads();
+ if (n < I && lane == 0)
+ {
+ float su = 0.0f;
+ #pragma unroll
+ for (int l = 0; l < 32; l++)
+ su = __fadd_rn(su, red[grp * 32 + l]);
+ float uh = __half2float(__float2half_rn(su));
+ float au = uh > 0.0f ? uh * uh : 0.0f;
+ act[(int64_t)s * I + n] = __float2half_rn(au);
+ }
+}
+
+// Down kernel: block (s, t) dots down[sel[s]] rows against the
+// pre-quantized act row s into partial[s]. V2 template (default on).
+template <bool V2>
+__global__ void fq_moe_down_kernel_q8(const uint8_t* __restrict__ aqb,
+ int64_t qb_stride,
+ const int64_t* __restrict__ sel,
+ const uint8_t* __restrict__ const* down_bases,
+ int64_t down_stride,
+ float* __restrict__ partial,
+ int S, int I, int K, int E, int ntiles_d)
+{
+ int b = blockIdx.x;
+ int s = b / ntiles_d;
+ int t = b % ntiles_d;
+ int grp = threadIdx.x / FQ_GEMV_LANES;
+ int lane = threadIdx.x % FQ_GEMV_LANES;
+ int64_t e = sel[s];
+ e = (e < 0 || e >= E) ? 0 : e;
+ int n = t * FQ_GEMV_OUT_PER_BLOCK + grp;
+
+ extern __shared__ uint8_t sh[];
+ float* red;
+ uint32_t* hdrs = nullptr;
+ uint32_t* signs32 = nullptr;
+ __shared__ fq_tables_sh tab;
+ const uint8_t* grid8 = nullptr;
+ int nb = I / FQ_IQ2_XXS_GROUP;
+ if constexpr (!V2)
+ {
+ hdrs = reinterpret_cast<uint32_t*>(sh);
+ signs32 = hdrs + (size_t)8 * nb * 16;
+ red = reinterpret_cast<float*>(signs32 + 256);
+ fq_tables_load(&tab, 0, 1);
+ fq_stage_iq2_hdrs(down_bases[e], down_stride, hdrs, nb,
+ t * FQ_GEMV_OUT_PER_BLOCK, K);
+ // Barrier BEFORE signs32_build (see up kernel above).
+ __syncthreads();
+ fq_signs32_build(&tab, signs32);
+ __syncthreads();
+ grid8 = reinterpret_cast<const uint8_t*>(tab.grid);
+ }
+ else
+ {
+ red = reinterpret_cast<float*>(sh);
+ }
+
+ float p = 0.0f;
+ if (n < K)
+ {
+ if constexpr (V2)
+ p = fq_dot_iq2_xxs_q8v2(down_bases[e] + (int64_t)n * down_stride,
+ aqb + (int64_t)s * qb_stride, I, lane, FQ_GEMV_LANES);
+ else
+ p = fq_dot_iq2_xxs_q8(down_bases[e] + (int64_t)n * down_stride,
+ hdrs + (int64_t)grp * nb * 16, grid8, signs32,
+ aqb + (int64_t)s * qb_stride, I, lane, FQ_GEMV_LANES);
+ }
+ red[threadIdx.x] = p;
+ __syncthreads();
+ if (n < K && lane == 0)
+ {
+ float sp = 0.0f;
+ #pragma unroll
+ for (int l = 0; l < 32; l++)
+ sp = __fadd_rn(sp, red[grp * 32 + l]);
+ partial[(int64_t)s * K + n] = sp;
+ }
+}
+
+} // namespace
+
+// Weighted fold (duplicate of fq_moe.cu's: that TU keeps it in an
+// anonymous namespace, so this TU has its own copy): out[k] = sum_s
+// w[s] * partial[s, k]. One block, 256 threads, strided subset of K.
+__global__ void fq_moe_combine_kernel_q8(const float* __restrict__ partial,
+ const __half* __restrict__ wts,
+ float* __restrict__ out, int S, int K)
+{
+ for (int k = blockIdx.x * blockDim.x + threadIdx.x; k < K; k += gridDim.x * blockDim.x)
+ {
+ float acc = 0.0f;
+ #pragma unroll
+ for (int s = 0; s < 32; s++)
+ {
+ if (s < S)
+ acc = __fadd_rn(acc, __fmul_rn(partial[(int64_t)s * K + k],
+ __half2float(wts[s])));
+ }
+ out[k] = acc;
+ }
+}
+
+bool fq_use_q8moe()
+{
+ const char* e = std::getenv("BOLT_FQ_Q8MOE");
+ return !e || e[0] != '0';
+}
+
+void fq_moe_iq2xxs_grouped_q8(torch::Tensor h, torch::Tensor sel, torch::Tensor wts,
+ torch::Tensor up_ptrs, torch::Tensor down_ptrs,
+ int64_t up_stride, int64_t down_stride,
+ torch::Tensor partial, torch::Tensor out)
+{
+ int K = (int)h.size(1);
+ int S = (int)sel.numel();
+ // Entry checks (S range, K/I multiples, dtypes) are done by the caller
+ // (fq_moe_iq2xxs_grouped branches here after validating); K%256 and
+ // I%256 imply the q8 path's K%32/I%32.
+ TORCH_CHECK_DTYPE(h, kHalf);
+ int E = (int)up_ptrs.numel();
+ int I = (int)(down_stride / FQ_IQ2_XXS_BYTES) * FQ_IQ2_XXS_GROUP;
+ at::cuda::CUDAGuard guard(h.device());
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ int ntiles_u = (I + FQ_GEMV_OUT_PER_BLOCK - 1) / FQ_GEMV_OUT_PER_BLOCK;
+ int ntiles_d = (K + FQ_GEMV_OUT_PER_BLOCK - 1) / FQ_GEMV_OUT_PER_BLOCK;
+ // Quantize once: h row (up dots) + per-slot act rows (down dots).
+ torch::Tensor qb_h = fq_q8_scratch(h.get_device(), 1, K);
+ fq_quant_q8_1_rows(h, qb_h);
+ int64_t qb_stride_h = (int64_t)(K / FQ_Q8_1_GROUP) * FQ_Q8_1_BYTES;
+ static thread_local std::map<std::tuple<int, int, int>, torch::Tensor> act_cache;
+ auto key = std::make_tuple((int)h.get_device(), S, I);
+ auto it = act_cache.find(key);
+ torch::Tensor act;
+ if (it != act_cache.end())
+ act = it->second;
+ else
+ {
+ act = torch::empty({S, I}, torch::dtype(torch::kHalf).device(h.device()));
+ act_cache[key] = act;
+ }
+ int nb_u = K / FQ_IQ2_XXS_GROUP;
+ bool v2 = fq_use_q8v2();
+ size_t shmem_u = v2 ? FQ_GEMV_THREADS * sizeof(float)
+ : (size_t)8 * nb_u * 16 * sizeof(uint32_t) +
+ 256 * sizeof(uint32_t) + FQ_GEMV_THREADS * sizeof(float);
+ if (v2)
+ fq_moe_up_kernel_q8<true><<<S * ntiles_u, FQ_GEMV_THREADS, shmem_u, stream>>>(
+ qb_h.data_ptr<uint8_t>(), sel.data_ptr<int64_t>(),
+ reinterpret_cast<const uint8_t* const*>(up_ptrs.data_ptr<int64_t>()),
+ up_stride, qb_stride_h,
+ reinterpret_cast<__half*>(act.data_ptr<at::Half>()),
+ S, I, K, E, ntiles_u);
+ else
+ fq_moe_up_kernel_q8<false><<<S * ntiles_u, FQ_GEMV_THREADS, shmem_u, stream>>>(
+ qb_h.data_ptr<uint8_t>(), sel.data_ptr<int64_t>(),
+ reinterpret_cast<const uint8_t* const*>(up_ptrs.data_ptr<int64_t>()),
+ up_stride, qb_stride_h,
+ reinterpret_cast<__half*>(act.data_ptr<at::Half>()),
+ S, I, K, E, ntiles_u);
+ torch::Tensor qb_act = fq_q8_scratch(h.get_device(), S, I);
+ fq_quant_q8_1_rows(act, qb_act);
+ int64_t qb_stride_a = (int64_t)(I / FQ_Q8_1_GROUP) * FQ_Q8_1_BYTES;
+ int nb_d = I / FQ_IQ2_XXS_GROUP;
+ size_t shmem_d = v2 ? FQ_GEMV_THREADS * sizeof(float)
+ : (size_t)8 * nb_d * 16 * sizeof(uint32_t) +
+ 256 * sizeof(uint32_t) + FQ_GEMV_THREADS * sizeof(float);
+ if (v2)
+ fq_moe_down_kernel_q8<true><<<S * ntiles_d, FQ_GEMV_THREADS, shmem_d, stream>>>(
+ qb_act.data_ptr<uint8_t>(), qb_stride_a, sel.data_ptr<int64_t>(),
+ reinterpret_cast<const uint8_t* const*>(down_ptrs.data_ptr<int64_t>()),
+ down_stride, partial.data_ptr<float>(), S, I, K, E, ntiles_d);
+ else
+ fq_moe_down_kernel_q8<false><<<S * ntiles_d, FQ_GEMV_THREADS, shmem_d, stream>>>(
+ qb_act.data_ptr<uint8_t>(), qb_stride_a, sel.data_ptr<int64_t>(),
+ reinterpret_cast<const uint8_t* const*>(down_ptrs.data_ptr<int64_t>()),
+ down_stride, partial.data_ptr<float>(), S, I, K, E, ntiles_d);
+ int nblocks = (K + 255) / 256;
+ fq_moe_combine_kernel_q8<<<nblocks, 256, 0, stream>>>(
+ partial.data_ptr<float>(),
+ reinterpret_cast<const __half*>(wts.data_ptr<at::Half>()),
+ out.data_ptr<float>(), S, K);
+}
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_tables.cuh b/exllamav3/exllamav3_ext/foreign_quant/fq_tables.cuh
new file mode 100644
index 0000000..213092d
--- /dev/null
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_tables.cuh
@@ -0,0 +1,165 @@
+// AUTO-GENERATED from exllamav3/foreign_quant/iq2_xxs.py (_IQ2XXS_GRID,
+// _KSIGNS_IQ2XS, _KMASK_IQ2XS). Do not hand-edit; regenerate with:
+// python3 -c <this command> (see BOLT step-3 commit).
+// Tables are verbatim llama.cpp ggml/src/ggml-common.h (MIT): iq2xxs_grid,
+// ksigns_iq2xs, kmask_iq2xs. Stored as uint64 so the device reads one grid
+// entry (8 magnitude bytes, little-endian) per load, like the C cast
+// (const uint8_t *)(iq2xxs_grid + idx).
+// NOTE: plain __device__ (= global, L1-cached LDG), NOT
+// __constant__: every thread of a dot reads a DIFFERENT grid entry
+// (divergent), and the constant cache serializes divergent addresses
+// (measured: v2 dot slower than v1 at K>=4096 through LDC, while small
+// shapes won). llama.cpp declares iq2xxs_grid as static const
+// __device__ (global) for the same reason; its mmvq SASS has zero LDC.
+// Uniform/cooperative readers (staging) are unaffected (L1 either way).
+#pragma once
+#include <stdint.h>
+
+__device__ const uint64_t FQ_IQ2XXS_GRID[256] = {
+ 0x0808080808080808ULL, 0x080808080808082bULL, 0x0808080808081919ULL, 0x0808080808082b08ULL,
+ 0x0808080808082b2bULL, 0x0808080808190819ULL, 0x0808080808191908ULL, 0x08080808082b0808ULL,
+ 0x08080808082b082bULL, 0x08080808082b2b08ULL, 0x08080808082b2b2bULL, 0x0808080819080819ULL,
+ 0x0808080819081908ULL, 0x0808080819190808ULL, 0x0808080819192b08ULL, 0x08080808192b0819ULL,
+ 0x08080808192b1908ULL, 0x080808082b080808ULL, 0x080808082b08082bULL, 0x080808082b082b2bULL,
+ 0x080808082b2b082bULL, 0x0808081908080819ULL, 0x0808081908081908ULL, 0x0808081908190808ULL,
+ 0x0808081908191919ULL, 0x0808081919080808ULL, 0x080808192b081908ULL, 0x080808192b192b08ULL,
+ 0x0808082b08080808ULL, 0x0808082b0808082bULL, 0x0808082b082b082bULL, 0x0808082b2b08082bULL,
+ 0x0808190808080819ULL, 0x0808190808081908ULL, 0x0808190808190808ULL, 0x08081908082b0819ULL,
+ 0x08081908082b1908ULL, 0x0808190819080808ULL, 0x080819081908082bULL, 0x0808190819082b08ULL,
+ 0x08081908192b0808ULL, 0x080819082b080819ULL, 0x080819082b081908ULL, 0x080819082b190808ULL,
+ 0x080819082b2b1908ULL, 0x0808191908080808ULL, 0x080819190808082bULL, 0x0808191908082b08ULL,
+ 0x08081919082b0808ULL, 0x080819191908192bULL, 0x08081919192b2b19ULL, 0x080819192b080808ULL,
+ 0x080819192b190819ULL, 0x0808192b08082b19ULL, 0x0808192b08190808ULL, 0x0808192b19080808ULL,
+ 0x0808192b2b081908ULL, 0x0808192b2b2b1908ULL, 0x08082b0808080808ULL, 0x08082b0808081919ULL,
+ 0x08082b0808082b08ULL, 0x08082b0808191908ULL, 0x08082b08082b2b08ULL, 0x08082b0819080819ULL,
+ 0x08082b0819081908ULL, 0x08082b0819190808ULL, 0x08082b081919082bULL, 0x08082b082b082b08ULL,
+ 0x08082b1908081908ULL, 0x08082b1919080808ULL, 0x08082b2b0808082bULL, 0x08082b2b08191908ULL,
+ 0x0819080808080819ULL, 0x0819080808081908ULL, 0x0819080808190808ULL, 0x08190808082b0819ULL,
+ 0x0819080819080808ULL, 0x08190808192b0808ULL, 0x081908082b081908ULL, 0x081908082b190808ULL,
+ 0x081908082b191919ULL, 0x0819081908080808ULL, 0x0819081908082b08ULL, 0x08190819082b0808ULL,
+ 0x0819081919190808ULL, 0x0819081919192b2bULL, 0x081908192b080808ULL, 0x0819082b082b1908ULL,
+ 0x0819082b19081919ULL, 0x0819190808080808ULL, 0x0819190808082b08ULL, 0x08191908082b0808ULL,
+ 0x08191908082b1919ULL, 0x0819190819082b19ULL, 0x081919082b080808ULL, 0x0819191908192b08ULL,
+ 0x08191919192b082bULL, 0x0819192b08080808ULL, 0x0819192b0819192bULL, 0x08192b0808080819ULL,
+ 0x08192b0808081908ULL, 0x08192b0808190808ULL, 0x08192b0819080808ULL, 0x08192b082b080819ULL,
+ 0x08192b1908080808ULL, 0x08192b1908081919ULL, 0x08192b192b2b0808ULL, 0x08192b2b19190819ULL,
+ 0x082b080808080808ULL, 0x082b08080808082bULL, 0x082b080808082b2bULL, 0x082b080819081908ULL,
+ 0x082b0808192b0819ULL, 0x082b08082b080808ULL, 0x082b08082b08082bULL, 0x082b0819082b2b19ULL,
+ 0x082b081919082b08ULL, 0x082b082b08080808ULL, 0x082b082b0808082bULL, 0x082b190808080819ULL,
+ 0x082b190808081908ULL, 0x082b190808190808ULL, 0x082b190819080808ULL, 0x082b19081919192bULL,
+ 0x082b191908080808ULL, 0x082b191919080819ULL, 0x082b1919192b1908ULL, 0x082b192b2b190808ULL,
+ 0x082b2b0808082b08ULL, 0x082b2b08082b0808ULL, 0x082b2b082b191908ULL, 0x082b2b2b19081908ULL,
+ 0x1908080808080819ULL, 0x1908080808081908ULL, 0x1908080808190808ULL, 0x1908080808192b08ULL,
+ 0x19080808082b0819ULL, 0x19080808082b1908ULL, 0x1908080819080808ULL, 0x1908080819082b08ULL,
+ 0x190808081919192bULL, 0x19080808192b0808ULL, 0x190808082b080819ULL, 0x190808082b081908ULL,
+ 0x190808082b190808ULL, 0x1908081908080808ULL, 0x19080819082b0808ULL, 0x19080819192b0819ULL,
+ 0x190808192b080808ULL, 0x190808192b081919ULL, 0x1908082b08080819ULL, 0x1908082b08190808ULL,
+ 0x1908082b19082b08ULL, 0x1908082b1919192bULL, 0x1908082b192b2b08ULL, 0x1908190808080808ULL,
+ 0x1908190808082b08ULL, 0x19081908082b0808ULL, 0x190819082b080808ULL, 0x190819082b192b19ULL,
+ 0x190819190819082bULL, 0x19081919082b1908ULL, 0x1908192b08080808ULL, 0x19082b0808080819ULL,
+ 0x19082b0808081908ULL, 0x19082b0808190808ULL, 0x19082b0819080808ULL, 0x19082b0819081919ULL,
+ 0x19082b1908080808ULL, 0x19082b1919192b08ULL, 0x19082b19192b0819ULL, 0x19082b192b08082bULL,
+ 0x19082b2b19081919ULL, 0x19082b2b2b190808ULL, 0x1919080808080808ULL, 0x1919080808082b08ULL,
+ 0x1919080808190819ULL, 0x1919080808192b19ULL, 0x19190808082b0808ULL, 0x191908082b080808ULL,
+ 0x191908082b082b08ULL, 0x1919081908081908ULL, 0x191908191908082bULL, 0x191908192b2b1908ULL,
+ 0x1919082b2b190819ULL, 0x191919082b190808ULL, 0x191919082b19082bULL, 0x1919191908082b2bULL,
+ 0x1919192b08080819ULL, 0x1919192b19191908ULL, 0x19192b0808080808ULL, 0x19192b0808190819ULL,
+ 0x19192b0808192b19ULL, 0x19192b08192b1908ULL, 0x19192b1919080808ULL, 0x19192b2b08082b08ULL,
+ 0x192b080808081908ULL, 0x192b080808190808ULL, 0x192b080819080808ULL, 0x192b0808192b2b08ULL,
+ 0x192b081908080808ULL, 0x192b081919191919ULL, 0x192b082b08192b08ULL, 0x192b082b192b0808ULL,
+ 0x192b190808080808ULL, 0x192b190808081919ULL, 0x192b191908190808ULL, 0x192b19190819082bULL,
+ 0x192b19192b081908ULL, 0x192b2b081908082bULL, 0x2b08080808080808ULL, 0x2b0808080808082bULL,
+ 0x2b08080808082b2bULL, 0x2b08080819080819ULL, 0x2b0808082b08082bULL, 0x2b08081908081908ULL,
+ 0x2b08081908192b08ULL, 0x2b08081919080808ULL, 0x2b08082b08190819ULL, 0x2b08190808080819ULL,
+ 0x2b08190808081908ULL, 0x2b08190808190808ULL, 0x2b08190808191919ULL, 0x2b08190819080808ULL,
+ 0x2b081908192b0808ULL, 0x2b08191908080808ULL, 0x2b0819191908192bULL, 0x2b0819192b191908ULL,
+ 0x2b08192b08082b19ULL, 0x2b08192b19080808ULL, 0x2b08192b192b0808ULL, 0x2b082b080808082bULL,
+ 0x2b082b1908081908ULL, 0x2b082b2b08190819ULL, 0x2b19080808081908ULL, 0x2b19080808190808ULL,
+ 0x2b190808082b1908ULL, 0x2b19080819080808ULL, 0x2b1908082b2b0819ULL, 0x2b1908190819192bULL,
+ 0x2b1908192b080808ULL, 0x2b19082b19081919ULL, 0x2b19190808080808ULL, 0x2b191908082b082bULL,
+ 0x2b19190819081908ULL, 0x2b19191919190819ULL, 0x2b192b082b080819ULL, 0x2b192b19082b0808ULL,
+ 0x2b2b08080808082bULL, 0x2b2b080819190808ULL, 0x2b2b08082b081919ULL, 0x2b2b081908082b19ULL,
+ 0x2b2b082b08080808ULL, 0x2b2b190808192b08ULL, 0x2b2b2b0819190808ULL, 0x2b2b2b1908081908ULL
+};
+__constant__ uint8_t FQ_KSIGNS_IQ2XS[128] = {
+ 0, 129, 130, 3, 132, 5, 6, 135, 136, 9, 10, 139, 12, 141, 142, 15,
+ 144, 17, 18, 147, 20, 149, 150, 23, 24, 153, 154, 27, 156, 29, 30, 159,
+ 160, 33, 34, 163, 36, 165, 166, 39, 40, 169, 170, 43, 172, 45, 46, 175,
+ 48, 177, 178, 51, 180, 53, 54, 183, 184, 57, 58, 187, 60, 189, 190, 63,
+ 192, 65, 66, 195, 68, 197, 198, 71, 72, 201, 202, 75, 204, 77, 78, 207,
+ 80, 209, 210, 83, 212, 85, 86, 215, 216, 89, 90, 219, 92, 221, 222, 95,
+ 96, 225, 226, 99, 228, 101, 102, 231, 232, 105, 106, 235, 108, 237, 238, 111,
+ 240, 113, 114, 243, 116, 245, 246, 119, 120, 249, 250, 123, 252, 125, 126, 255
+};
+__constant__ uint8_t FQ_KMASK_IQ2XS[8] = {1, 2, 4, 8, 16, 32, 64, 128};
+
+// OCP MX E2M1 finite codebook (index = nibble value), float32. Matches
+// exllamav3/foreign_quant/nvfp4.py E2M1_LUT bit-exactly.
+__constant__ float FQ_E2M1_LUT[16] = {
+ 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f,
+ -0.0f, -0.5f, -1.0f, -1.5f, -2.0f, -3.0f, -4.0f, -6.0f
+};
+
+// E2M1 codebook DOUBLED to int8 (2x FQ_E2M1_LUT, exact: all entries are
+// multiples of 0.5). Verbatim llama.cpp ggml/src/ggml-common.h (MIT)
+// kvalues_fp4 (= kvalues_mxfp4), shared by MXFP4 and NVFP4: the doubled
+// values are integers, so the q8_1-activation dots accumulate in int32
+// via dp4a and apply the compensating 0.5 in the float scale (same
+// factorization as llama's vec_dot_nvfp4_q8_1: ue4m3/2 scale x doubled
+// weights). Nibble order matches FQ_E2M1_LUT (sign = high bit).
+__constant__ int8_t FQ_E2M1_DBL[16] = {
+ 0, 1, 2, 3, 4, 6, 8, 12,
+ 0, -1, -2, -3, -4, -6, -8, -12
+};
+
+// --- Appended (not part of the iq2 auto-generation above) ---
+// OCP MX E4M3 full byte -> fp32 bits. __uint_as_float(FQ_E4M3_BITS[b]) equals
+// fq_e4m3(b) in fq_dequant.cuh bit-exactly (all 256 codes: every finite value
+// is an exact dyadic; 0x7F/0xFF map to 0x7FC00000, the same quiet NaN
+// nanf("") produces), so the GEMV path replaces the branchy per-element
+// conversion with one constant load. Stored as bits because __constant__
+// rejects dynamic initializers like nanf(""). Generated with:
+// python3 -c "import math, struct
+// def e(b):
+// x=(b>>3)&0xF; m=b&0x7
+// if x==15 and m==7: return 0x7FC00000
+// v=0.0 if (x==0 and m==0) else (m*2.0**-9 if x==0 else math.ldexp(1.0+m/8.0,x-7))
+// v=-v if b&0x80 else v
+// return struct.unpack('<I', struct.pack('<f', v))[0]
+// print(',\n'.join(' '+', '.join('0x%08XU'%e(b) for b in range(i,i+8)) for i in range(0,256,8)))"
+// Verified by the fq_gemv scale-sweep in bolt1/test_gemv2.py (all 256 codes
+// vs the dequant path).
+__constant__ uint32_t FQ_E4M3_BITS[256] = {
+ 0x00000000U, 0x3B000000U, 0x3B800000U, 0x3BC00000U, 0x3C000000U, 0x3C200000U, 0x3C400000U, 0x3C600000U,
+ 0x3C800000U, 0x3C900000U, 0x3CA00000U, 0x3CB00000U, 0x3CC00000U, 0x3CD00000U, 0x3CE00000U, 0x3CF00000U,
+ 0x3D000000U, 0x3D100000U, 0x3D200000U, 0x3D300000U, 0x3D400000U, 0x3D500000U, 0x3D600000U, 0x3D700000U,
+ 0x3D800000U, 0x3D900000U, 0x3DA00000U, 0x3DB00000U, 0x3DC00000U, 0x3DD00000U, 0x3DE00000U, 0x3DF00000U,
+ 0x3E000000U, 0x3E100000U, 0x3E200000U, 0x3E300000U, 0x3E400000U, 0x3E500000U, 0x3E600000U, 0x3E700000U,
+ 0x3E800000U, 0x3E900000U, 0x3EA00000U, 0x3EB00000U, 0x3EC00000U, 0x3ED00000U, 0x3EE00000U, 0x3EF00000U,
+ 0x3F000000U, 0x3F100000U, 0x3F200000U, 0x3F300000U, 0x3F400000U, 0x3F500000U, 0x3F600000U, 0x3F700000U,
+ 0x3F800000U, 0x3F900000U, 0x3FA00000U, 0x3FB00000U, 0x3FC00000U, 0x3FD00000U, 0x3FE00000U, 0x3FF00000U,
+ 0x40000000U, 0x40100000U, 0x40200000U, 0x40300000U, 0x40400000U, 0x40500000U, 0x40600000U, 0x40700000U,
+ 0x40800000U, 0x40900000U, 0x40A00000U, 0x40B00000U, 0x40C00000U, 0x40D00000U, 0x40E00000U, 0x40F00000U,
+ 0x41000000U, 0x41100000U, 0x41200000U, 0x41300000U, 0x41400000U, 0x41500000U, 0x41600000U, 0x41700000U,
+ 0x41800000U, 0x41900000U, 0x41A00000U, 0x41B00000U, 0x41C00000U, 0x41D00000U, 0x41E00000U, 0x41F00000U,
+ 0x42000000U, 0x42100000U, 0x42200000U, 0x42300000U, 0x42400000U, 0x42500000U, 0x42600000U, 0x42700000U,
+ 0x42800000U, 0x42900000U, 0x42A00000U, 0x42B00000U, 0x42C00000U, 0x42D00000U, 0x42E00000U, 0x42F00000U,
+ 0x43000000U, 0x43100000U, 0x43200000U, 0x43300000U, 0x43400000U, 0x43500000U, 0x43600000U, 0x43700000U,
+ 0x43800000U, 0x43900000U, 0x43A00000U, 0x43B00000U, 0x43C00000U, 0x43D00000U, 0x43E00000U, 0x7FC00000U,
+ 0x80000000U, 0xBB000000U, 0xBB800000U, 0xBBC00000U, 0xBC000000U, 0xBC200000U, 0xBC400000U, 0xBC600000U,
+ 0xBC800000U, 0xBC900000U, 0xBCA00000U, 0xBCB00000U, 0xBCC00000U, 0xBCD00000U, 0xBCE00000U, 0xBCF00000U,
+ 0xBD000000U, 0xBD100000U, 0xBD200000U, 0xBD300000U, 0xBD400000U, 0xBD500000U, 0xBD600000U, 0xBD700000U,
+ 0xBD800000U, 0xBD900000U, 0xBDA00000U, 0xBDB00000U, 0xBDC00000U, 0xBDD00000U, 0xBDE00000U, 0xBDF00000U,
+ 0xBE000000U, 0xBE100000U, 0xBE200000U, 0xBE300000U, 0xBE400000U, 0xBE500000U, 0xBE600000U, 0xBE700000U,
+ 0xBE800000U, 0xBE900000U, 0xBEA00000U, 0xBEB00000U, 0xBEC00000U, 0xBED00000U, 0xBEE00000U, 0xBEF00000U,
+ 0xBF000000U, 0xBF100000U, 0xBF200000U, 0xBF300000U, 0xBF400000U, 0xBF500000U, 0xBF600000U, 0xBF700000U,
+ 0xBF800000U, 0xBF900000U, 0xBFA00000U, 0xBFB00000U, 0xBFC00000U, 0xBFD00000U, 0xBFE00000U, 0xBFF00000U,
+ 0xC0000000U, 0xC0100000U, 0xC0200000U, 0xC0300000U, 0xC0400000U, 0xC0500000U, 0xC0600000U, 0xC0700000U,
+ 0xC0800000U, 0xC0900000U, 0xC0A00000U, 0xC0B00000U, 0xC0C00000U, 0xC0D00000U, 0xC0E00000U, 0xC0F00000U,
+ 0xC1000000U, 0xC1100000U, 0xC1200000U, 0xC1300000U, 0xC1400000U, 0xC1500000U, 0xC1600000U, 0xC1700000U,
+ 0xC1800000U, 0xC1900000U, 0xC1A00000U, 0xC1B00000U, 0xC1C00000U, 0xC1D00000U, 0xC1E00000U, 0xC1F00000U,
+ 0xC2000000U, 0xC2100000U, 0xC2200000U, 0xC2300000U, 0xC2400000U, 0xC2500000U, 0xC2600000U, 0xC2700000U,
+ 0xC2800000U, 0xC2900000U, 0xC2A00000U, 0xC2B00000U, 0xC2C00000U, 0xC2D00000U, 0xC2E00000U, 0xC2F00000U,
+ 0xC3000000U, 0xC3100000U, 0xC3200000U, 0xC3300000U, 0xC3400000U, 0xC3500000U, 0xC3600000U, 0xC3700000U,
+ 0xC3800000U, 0xC3900000U, 0xC3A00000U, 0xC3B00000U, 0xC3C00000U, 0xC3D00000U, 0xC3E00000U, 0x7FC00000U
+};
diff --git a/exllamav3/exllamav3_ext/graph.cuh b/exllamav3/exllamav3_ext/graph.cuh
index 7e40992..5fa1872 100644
--- a/exllamav3/exllamav3_ext/graph.cuh
+++ b/exllamav3/exllamav3_ext/graph.cuh
@@ -104,6 +104,16 @@ enum GraphedParams
GP_moe_bias_add_weighted_weights
};
+#if !defined(USE_ROCM)
+// True while `stream` is being captured by an outer (whole-forward) CUDA graph. BC objects then launch their
+// kernels eagerly into that capture (pointers taken from the current call) instead of capturing or patching their own graph.
+inline bool graph_outer_capture(cudaStream_t stream)
+{
+ cudaStreamCaptureStatus st = cudaStreamCaptureStatusNone;
+ return cudaStreamIsCapturing(stream, &st) == cudaSuccess && st != cudaStreamCaptureStatusNone;
+}
+#endif
+
class Graph
{
public:
diff --git a/exllamav3/exllamav3_ext/hc_mix.cu b/exllamav3/exllamav3_ext/hc_mix.cu
index 7e1f8d3..98349be 100644
--- a/exllamav3/exllamav3_ext/hc_mix.cu
+++ b/exllamav3/exllamav3_ext/hc_mix.cu
@@ -9,6 +9,7 @@
#include <cstdlib>
#include <algorithm>
#include "hc_mix.cuh"
+#include "port.cuh"
#include <c10/cuda/CUDAGuard.h>
#include <ATen/cuda/CUDAContext.h>
#include "util.h"
@@ -2093,7 +2094,7 @@ __device__ __forceinline__ void unpack_s8x4(uint32_t v, float& f0, float& f1, fl
// The product must be rounded to fp32 BEFORE the half rounding (the fp16 twin sees half(fp32(q * sc))); without the barrier the compiler
// fuses mul + convert into one v_fma_mix and rounds once (differs on exact half ties).
#ifndef GS_NOFUSE
-#define GS_NOFUSE(p) asm volatile("" : "+v"(p))
+#define GS_NOFUSE(p) asm volatile("" : "+" PORT_ASM_F32(p))
#endif
__device__ __forceinline__ float gs_dq(float q, float sc) { float p = q * sc; GS_NOFUSE(p); return __half2float(__float2half_rn(p)); }
__device__ __forceinline__ void gs_unpack_s8x4(uint32_t v, float sc, float& f0, float& f1, float& f2, float& f3)
diff --git a/exllamav3/exllamav3_ext/hc_mix_q8r.cuh b/exllamav3/exllamav3_ext/hc_mix_q8r.cuh
index 0d1e5a0..7080eff 100644
--- a/exllamav3/exllamav3_ext/hc_mix_q8r.cuh
+++ b/exllamav3/exllamav3_ext/hc_mix_q8r.cuh
@@ -78,7 +78,7 @@ void gr_dots_q8r_kernel
#pragma unroll
for (int u = 0; u < JT; ++u)
f8[u] = (const int2*) (fn + ((size_t) min(j0 + u, M - 1) * H + h) * D); // clamped: tail rows are discarded
- #pragma unroll GRR_DOTS_UNROLL
+ PORT_UNROLL(GRR_DOTS_UNROLL)
for (int c = threadIdx.x; c < D4 / 2; c += GR_THREADS_A)
{
float wv[JT][8];
@@ -230,7 +230,7 @@ void gr_finalize_q8r_kernel
#pragma unroll
for (int h = 0; h < H; ++h) g[q][h] = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
float4 gsc[H];
- #pragma unroll GRR_FIN_UNROLL
+ PORT_UNROLL(GRR_FIN_UNROLL)
for (int i = lane; i < LR; i += 32)
{
float ti[RT];
diff --git a/exllamav3/exllamav3_ext/hgemm_f16acc.cu b/exllamav3/exllamav3_ext/hgemm_f16acc.cu
index 6fcae18..67397e5 100644
--- a/exllamav3/exllamav3_ext/hgemm_f16acc.cu
+++ b/exllamav3/exllamav3_ext/hgemm_f16acc.cu
@@ -458,6 +458,13 @@ static bool tuned_device(int device)
{
// The layout/shape sweep was measured on GeForce Blackwell. Other Ampere+ parts retain
// their existing layout; the rate probe still determines whether FP16 MMA is worthwhile.
+ return at::cuda::getDeviceProperties(device)->major >= 8;
+}
+
+// Which shapes take the fp16-accumulate kernel instead of cuBLAS (fp32 accumulate) is a numerics decision, kept per
+// architecture: the broader Blackwell coverage (M >= 64, small batched grids) stays Blackwell-only
+static bool wide_coverage(int device)
+{
return at::cuda::getDeviceProperties(device)->major == 12;
}
@@ -479,7 +486,7 @@ static bool worthwhile(const at::Tensor& a, const at::Tensor& b)
const auto* props = at::cuda::getDeviceProperties(device);
int64_t M = a.size(-2), N = b.size(-1), K = a.size(-1);
int64_t batch = a.dim() == 3 ? a.size(0) : 1;
- if (tuned_device(device) && M >= 64 && M * batch >= MIN_ROWS && N >= 1024 && K >= 512)
+ if (wide_coverage(device) && M >= 64 && M * batch >= MIN_ROWS && N >= 1024 && K >= 512)
{
const int tile_n = narrow_tile(a, b) ? 64 : 128;
int64_t blocks = ((M + BM - 1) / BM) * (N / tile_n) * batch;
diff --git a/exllamav3/exllamav3_ext/libtorch/attention.cpp b/exllamav3/exllamav3_ext/libtorch/attention.cpp
index d16978d..6a4c9f7 100644
--- a/exllamav3/exllamav3_ext/libtorch/attention.cpp
+++ b/exllamav3/exllamav3_ext/libtorch/attention.cpp
@@ -209,6 +209,7 @@ void BC_Attention::configure_slot
std::shared_ptr<TritonKernel> k_update,
int block_n,
int splits_cap,
+ int programs,
c10::optional<at::Tensor> xp,
c10::optional<at::Tensor> yp
)
@@ -308,11 +309,9 @@ void BC_Attention::configure_slot
s.qkv_c_ptrs = at::tensor(ptrs, at::TensorOptions().dtype(at::kLong)).to(s.q.device());
}
- int group_size = num_q_heads / num_kv_heads;
- int block_m = 1; while (block_m < q_len) block_m <<= 1;
- int block_h = MAX(16 / block_m, 1);
- int h_blocks = CEIL_DIVIDE(group_size, block_h);
- s.programs = bsz * num_kv_heads * h_blocks;
+ // Split / combine grid width: the row layout is the Python side's (triton_paged_cu.decode_row_layout, or the
+ // pre-1.6 layout under EXL3_ATTN16=0), which compiled the kernels for it (upstream exllamav3 1.6.0, MIT)
+ s.programs = programs;
s.upd_grid = dim3(bsz * q_len, num_kv_heads, 1);
s.graph = std::make_unique<Graph>();
@@ -385,11 +384,13 @@ void BC_Attention::configure_slot_qsa
// Live split configuration from the current block-table bound (same formula as the python
// dispatch path, so the two produce identical numerics)
+// key blocks per split (was 4): short contexts get more CTAs (upstream exllamav3 1.6.0, MIT)
+#define SPLIT_MIN_BLOCKS 1
static inline void split_config(int bt_width, int page_size, int q_len, int block_n, int splits_cap,
int* num_splits, int* split_len)
{
int bound = bt_width * page_size + q_len;
- *num_splits = MAX(1, MIN(splits_cap, CEIL_DIVIDE(bound, 4 * block_n)));
+ *num_splits = MAX(1, MIN(splits_cap, CEIL_DIVIDE(bound, SPLIT_MIN_BLOCKS * block_n)));
*split_len = CEIL_DIVIDE(CEIL_DIVIDE(bound, *num_splits), block_n) * block_n;
}
@@ -802,7 +803,7 @@ void BC_Attention::run_gr
// HAS_SINKS), dead arg otherwise
sinks ? (void*) sinks.value().data_ptr() : (void*) s.q.data_ptr(),
};
- s.k_combine->launch(s.programs, 1, 1, args, stream);
+ s.k_combine->launch(s.programs, s.k_combine->grid_y, 1, args, stream);
if (graph)
{
graph->record_param(s.k_combine->handle(), GP_attn_num_splits, 4, 4);
@@ -866,6 +867,11 @@ void BC_Attention::run
// First run per slot executes eagerly (GEMM autotune, kernel warmup); the second run is
// captured, then launched below like every later run, with only the I/O pointers patched
+ if (graph_outer_capture(stream))
+ {
+ run_gr(bsz, q_len, s, x, y, cache_seqlens, block_table, position, positions, position_ids, inv_freq_override, regime, t_total, nullptr);
+ return;
+ }
if (s.runs == 0)
{
run_gr(bsz, q_len, s, x, y, cache_seqlens, block_table, position, positions, position_ids, inv_freq_override, regime, t_total, nullptr);
diff --git a/exllamav3/exllamav3_ext/libtorch/attention.h b/exllamav3/exllamav3_ext/libtorch/attention.h
index 7c6e498..f3c48c0 100644
--- a/exllamav3/exllamav3_ext/libtorch/attention.h
+++ b/exllamav3/exllamav3_ext/libtorch/attention.h
@@ -285,6 +285,7 @@ struct BC_Attention
std::shared_ptr<TritonKernel> k_update,
int block_n,
int splits_cap,
+ int programs,
c10::optional<at::Tensor> xp,
c10::optional<at::Tensor> yp
);
diff --git a/exllamav3/exllamav3_ext/libtorch/attention_bc.h b/exllamav3/exllamav3_ext/libtorch/attention_bc.h
index 89c6235..3d01cef 100644
--- a/exllamav3/exllamav3_ext/libtorch/attention_bc.h
+++ b/exllamav3/exllamav3_ext/libtorch/attention_bc.h
@@ -1,4 +1,5 @@
-py::class_<TritonKernel, std::shared_ptr<TritonKernel>>(m, "TritonKernel").def
+py::class_<TritonKernel, std::shared_ptr<TritonKernel>>(m, "TritonKernel")
+ .def_readwrite("grid_y", &TritonKernel::grid_y).def
(
py::init<py::bytes, std::string, int, int>(),
py::arg("cubin"),
@@ -155,6 +156,7 @@ py::class_<BC_Attention, std::shared_ptr<BC_Attention>>(m, "BC_Attention").def
py::arg("k_update"),
py::arg("block_n"),
py::arg("splits_cap"),
+ py::arg("programs"),
py::arg("xp"),
py::arg("yp")
)
diff --git a/exllamav3/exllamav3_ext/libtorch/blocksparse_mlp.cpp b/exllamav3/exllamav3_ext/libtorch/blocksparse_mlp.cpp
index e5a90e0..2b44bfa 100644
--- a/exllamav3/exllamav3_ext/libtorch/blocksparse_mlp.cpp
+++ b/exllamav3/exllamav3_ext/libtorch/blocksparse_mlp.cpp
@@ -355,7 +355,7 @@ void BC_BlockSparseMLP::run_single_expert
c10::cuda::CUDAGuard device_guard(y.device());
cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream();
- if (graph_single[graphidx].disabled || (!graph_single[graphidx].ready && !graph_single[graphidx].ready_to_record))
+ if (graph_single[graphidx].disabled || graph_outer_capture(stream) || (!graph_single[graphidx].ready && !graph_single[graphidx].ready_to_record))
{
run_single_expert_gr(y, expert_idx, nullptr);
graph_single[graphidx].ready_to_record = true;
diff --git a/exllamav3/exllamav3_ext/libtorch/gated_delta_net.cpp b/exllamav3/exllamav3_ext/libtorch/gated_delta_net.cpp
index 9125d17..22769a2 100644
--- a/exllamav3/exllamav3_ext/libtorch/gated_delta_net.cpp
+++ b/exllamav3/exllamav3_ext/libtorch/gated_delta_net.cpp
@@ -348,7 +348,7 @@ void BC_GatedDeltaNetSplit::run_bszN
Slot& s = slot(bsz, seqlen, history);
TORCH_CHECK(s.configured, "BC_GatedDeltaNetSplit::run_bszN: slot not configured");
- if (s.graph->disabled || (!s.graph->ready && !s.graph->ready_to_record))
+ if (s.graph->disabled || graph_outer_capture(stream) || (!s.graph->ready && !s.graph->ready_to_record))
{
run_bszN_gr(x, y, conv_state, recurrent_state, recurrent_base, slots, history, s, nullptr);
s.graph->ready_to_record = true;
@@ -580,7 +580,7 @@ void BC_Mamba2::run_bszN
Slot& s = slot(bsz, seqlen, history);
TORCH_CHECK(s.configured, "BC_Mamba2::run_bszN: slot not configured");
- if (s.graph->disabled || (!s.graph->ready && !s.graph->ready_to_record))
+ if (s.graph->disabled || graph_outer_capture(stream) || (!s.graph->ready && !s.graph->ready_to_record))
{
run_bszN_gr(x, y, conv_state, recurrent_state, slots, history, s, nullptr);
s.graph->ready_to_record = true;
diff --git a/exllamav3/exllamav3_ext/libtorch/mla_attention.cpp b/exllamav3/exllamav3_ext/libtorch/mla_attention.cpp
index 9763570..abe2fab 100644
--- a/exllamav3/exllamav3_ext/libtorch/mla_attention.cpp
+++ b/exllamav3/exllamav3_ext/libtorch/mla_attention.cpp
@@ -846,6 +846,11 @@ void BC_MLAttention::run
// First run per slot executes eagerly (GEMM autotune, kernel warmup); the second run is
// captured, then launched below like every later run, with only the I/O pointers patched
+ if (graph_outer_capture(stream))
+ {
+ run_gr(bsz, q_len, s, x, y, cache_seqlens, block_table, position, positions, position_ids, regime, t_total, ext_indices, nullptr);
+ return;
+ }
if (s.runs == 0)
{
run_gr(bsz, q_len, s, x, y, cache_seqlens, block_table, position, positions, position_ids, regime, t_total, ext_indices, nullptr);
diff --git a/exllamav3/exllamav3_ext/libtorch/mlp.cpp b/exllamav3/exllamav3_ext/libtorch/mlp.cpp
index ac8c6c4..877a838 100644
--- a/exllamav3/exllamav3_ext/libtorch/mlp.cpp
+++ b/exllamav3/exllamav3_ext/libtorch/mlp.cpp
@@ -105,7 +105,7 @@ void BC_GatedMLP::run_bszN
Graph& g = graph_bszN[graphidx];
- if (g.disabled || (!g.ready && !g.ready_to_record))
+ if (g.disabled || graph_outer_capture(stream) || (!g.ready && !g.ready_to_record))
{
run_bszN_gr(x, d, num_tokens, nullptr);
g.ready_to_record = true;
@@ -194,7 +194,7 @@ void BC_MLP::run_bsz1
c10::cuda::CUDAGuard device_guard(x.device());
cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream();
- if (graph_bsz1.disabled || (!graph_bsz1.ready && !graph_bsz1.ready_to_record))
+ if (graph_bsz1.disabled || graph_outer_capture(stream) || (!graph_bsz1.ready && !graph_bsz1.ready_to_record))
{
run_bsz1_gr(x, d, nullptr);
graph_bsz1.ready_to_record = true;
diff --git a/exllamav3/exllamav3_ext/ngram.cu b/exllamav3/exllamav3_ext/ngram.cu
index b2b042b..13de04d 100644
--- a/exllamav3/exllamav3_ext/ngram.cu
+++ b/exllamav3/exllamav3_ext/ngram.cu
@@ -7,6 +7,7 @@
#include <unistd.h>
#endif
#include <algorithm>
+#include <cstdlib>
#include <thread>
#include <vector>
#include <mutex>
@@ -209,7 +210,11 @@ struct GatherPool
if (!started)
{
started = true;
- int n = (int) std::min(32u, std::max(4u, std::thread::hardware_concurrency()));
+ // A cold gather is bound by the queue depth the disk sees (one blocking pread per worker):
+ // 32 workers keep a consumer NVMe at ~45k random reads/s, 128 at ~85k
+ int cap = 128;
+ if (const char* e = std::getenv("EXL3_NGRAM_IO_THREADS")) cap = std::max(1, std::atoi(e));
+ int n = (int) std::min((unsigned) cap, std::max(4u, std::thread::hardware_concurrency() * 8));
for (int i = 0; i < n; ++i)
std::thread(&GatherPool::worker, this).detach();
}
@@ -288,11 +293,11 @@ void ngram_gather_cpu
return;
}
- // One span task per run keeps every cold read in flight at once; past ~64 runs, group
+ // One span task per run keeps every cold read in flight at once; past ~256 runs, group
// whole runs into span tasks so the queue overhead stays negligible (a worker issues its
// group's runs sequentially -- pool-width reads still in flight)
std::vector<std::pair<int64_t, int64_t>> tasks;
- size_t group = (n_runs + 63) / 64;
+ size_t group = (n_runs + 255) / 256;
tasks.reserve((n_runs + group - 1) / group);
for (size_t r = 0; r < n_runs; r += group)
{
diff --git a/exllamav3/exllamav3_ext/port.cuh b/exllamav3/exllamav3_ext/port.cuh
new file mode 100644
index 0000000..b605a43
--- /dev/null
+++ b/exllamav3/exllamav3_ext/port.cuh
@@ -0,0 +1,68 @@
+#pragma once
+
+// One-source portability layer for the Kyojin kernels (HIP / gfx11.5 and CUDA / sm_86).
+// Every macro expands to the exact construct the ROCm build used before, so the ROCm build is unchanged;
+// the CUDA side gets the nearest equivalent. Add a macro here instead of a new #if in a kernel.
+
+#define PORT_PRAGMA(x) _Pragma(#x)
+// nvcc does not macro-expand the count of "#pragma unroll N"; going through _Pragma expands it first (same pragma on HIP).
+#define PORT_UNROLL(n) PORT_PRAGMA(unroll n)
+
+// Inline-asm register class of a 32-bit float: VGPR on AMDGPU, .f32 register on NVPTX.
+#if defined(USE_ROCM)
+#define PORT_ASM_F32 "v"
+#else
+#define PORT_ASM_F32 "f"
+#endif
+
+// ------------------------------------------------------------------------------------------------
+// exl3_dec family (quant/exl3_dec.cu, RDNA wave32 code; one CUDA warp = one RDNA wave).
+// ROCm: the gfx11.5 builtins the kernels were written with. CUDA: nearest sm_86 equivalent; same
+// values everywhere except PORT_FDOT2_F32 (fp32 rounding of the pair sum may differ from v_dot2_f32_f16).
+#if defined(USE_ROCM)
+#define PORT_UBFE16(w, s) __builtin_amdgcn_ubfe(w, s, 16)
+#define PORT_ALIGNBIT(hi, lo, s) __builtin_amdgcn_alignbit(hi, lo, s)
+#define PORT_SAD_U8(a, acc) __builtin_amdgcn_sad_u8(a, 0u, acc)
+#define PORT_SAD_HI_U8(a, acc) __builtin_amdgcn_sad_hi_u8(a, 0u, acc)
+#define PORT_FDOT2_F32(a, b, acc) __builtin_amdgcn_fdot2(a, b, acc, false)
+#define PORT_HFMA2(a, b, c) __builtin_elementwise_fma(a, b, c)
+#define PORT_SCHED_BARRIER() __builtin_amdgcn_sched_barrier(0)
+#define PORT_LD_STREAM(p) __builtin_nontemporal_load(p)
+#define PORT_LD_COHERENT(p) __hip_atomic_load(p, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT)
+#define PORT_SHFL_XOR(v, m) __shfl_xor(v, m)
+#define PORT_TRAP() __builtin_trap()
+#define PORT_F16_BITS_TO_F32(u) ((float) __builtin_bit_cast(_Float16, (unsigned short) (u)))
+// u32 -> packed fp16 pair of the kernel's own f16x2 type
+#define PORT_AS_F16X2(u) __builtin_bit_cast(f16x2, u)
+#else
+// (w >> s) & 0xffff
+#define PORT_UBFE16(w, s) (((uint32_t) (w) >> (s)) & 0xffffu)
+// low 32 bits of ({hi, lo} >> s), s in 0..31: shf.r.wrap
+#define PORT_ALIGNBIT(hi, lo, s) __funnelshift_r(lo, hi, s)
+// sum of the 4 bytes of a + acc / (that sum << 16) + acc: dp4a against 0x01010101
+#define PORT_SAD_U8(a, acc) __dp4a((uint32_t) (a), 0x01010101u, (uint32_t) (acc))
+#define PORT_SAD_HI_U8(a, acc) ((__dp4a((uint32_t) (a), 0x01010101u, 0u) << 16) + (uint32_t) (acc))
+// acc + a.x * b.x + a.y * b.y in fp32 (fp16 x fp16 products are exact in fp32)
+__device__ __forceinline__ float port_fdot2_f32(__half2 a, __half2 b, float acc)
+{
+ const float2 fa = __half22float2(a), fb = __half22float2(b);
+ return fmaf(fa.y, fb.y, fmaf(fa.x, fb.x, acc));
+}
+#define PORT_FDOT2_F32(a, b, acc) port_fdot2_f32(a, b, acc)
+#define PORT_HFMA2(a, b, c) __hfma2(a, b, c)
+#define PORT_SCHED_BARRIER() ((void) 0)
+#define PORT_LD_STREAM(p) __ldcs(p)
+// L2 load, not served from a stale L1 line (reads of other blocks' partials after __threadfence)
+#define PORT_LD_COHERENT(p) __ldcg(p)
+#define PORT_SHFL_XOR(v, m) __shfl_xor_sync(0xffffffffu, v, m)
+#define PORT_TRAP() __trap()
+#define PORT_F16_BITS_TO_F32(u) __half2float(__ushort_as_half((unsigned short) (u)))
+// __half2 is not trivially copyable, so no __builtin_bit_cast
+__device__ __forceinline__ __half2 port_as_half2(uint32_t u)
+{
+ __half2 h;
+ memcpy(&h, &u, sizeof(h));
+ return h;
+}
+#define PORT_AS_F16X2(u) port_as_half2(u)
+#endif
diff --git a/exllamav3/exllamav3_ext/quant/codebook.cuh b/exllamav3/exllamav3_ext/quant/codebook.cuh
index 4898617..841a8b4 100644
--- a/exllamav3/exllamav3_ext/quant/codebook.cuh
+++ b/exllamav3/exllamav3_ext/quant/codebook.cuh
@@ -86,7 +86,14 @@ __device__ inline half2 decode_mul1_product_2_sad(uint32_t x0, uint32_t x1)
// Keep this expression portable instead of relying on inline PTX.
__device__ __forceinline__ uint32_t lop3_0x6a(uint32_t a, uint32_t b, uint32_t c)
{
+#if !defined(USE_ROCM) && defined(__CUDA_ARCH__)
+ // CUDA: one explicit lop3, as upstream exllamav3 1.6.0 issues it (EXL3_CB_LOP3, MIT); A/B against the C form
+ uint32_t r;
+ asm ("lop3.b32 %0, %1, %2, %3, 0x6a;" : "=r"(r) : "r"(a), "r"(b), "r"(c));
+ return r;
+#else
return c ^ (a & b);
+#endif
}
// Ditto mcg (cb 1)
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n128_cb0.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n128_cb0.cu
new file mode 100644
index 0000000..8f10365
--- /dev/null
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n128_cb0.cu
@@ -0,0 +1,6 @@
+// fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu
+#define EXL3_GEMM_NO_H_ACC
+#include "exl3_moe_instances.cuh"
+#include "../exl3_moe_kernel.cuh"
+
+fp_exl3_moe_kernel exl3_moe_kernel_k0_n128_cb0() { return exl3_moe_kernel<0, 128, 0>; }
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n128_cb1.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n128_cb1.cu
index 1c9a736..92f531f 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n128_cb1.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n128_cb1.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n128_cb2.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n128_cb2.cu
index b777ae9..ffe32b0 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n128_cb2.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n128_cb2.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n128_cb2_m32.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n128_cb2_m32.cu
index 9c8247e..8a743be 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n128_cb2_m32.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n128_cb2_m32.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n128_cb2_m64.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n128_cb2_m64.cu
index 3afe5f4..b8cc456 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n128_cb2_m64.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n128_cb2_m64.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n256_cb0.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n256_cb0.cu
new file mode 100644
index 0000000..e5c03dd
--- /dev/null
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n256_cb0.cu
@@ -0,0 +1,6 @@
+// fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu
+#define EXL3_GEMM_NO_H_ACC
+#include "exl3_moe_instances.cuh"
+#include "../exl3_moe_kernel.cuh"
+
+fp_exl3_moe_kernel exl3_moe_kernel_k0_n256_cb0() { return exl3_moe_kernel<0, 256, 0>; }
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n256_cb1.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n256_cb1.cu
index c7c1857..c8802b7 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n256_cb1.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n256_cb1.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n256_cb2.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n256_cb2.cu
index 498d0a0..7c944e5 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n256_cb2.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k0_n256_cb2.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k1_cb0.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k1_cb0.cu
new file mode 100644
index 0000000..67418cf
--- /dev/null
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k1_cb0.cu
@@ -0,0 +1,8 @@
+// fp32 MMA accumulation (no EXL3_GEMM_H_ACC): the fused kernel's expert groups give each block long k spans, where fp16
+// accumulation of 3INST experts measured ~1.4x the KLD of the unfused path on a 3090; no speed cost
+#define EXL3_GEMM_NO_H_ACC
+#include "exl3_moe_instances.cuh"
+#include "../exl3_moe_kernel.cuh"
+
+fp_exl3_moe_kernel exl3_moe_kernel_k1_n128_cb0() { return exl3_moe_kernel<1, 128, 0>; }
+fp_exl3_moe_kernel exl3_moe_kernel_k1_n256_cb0() { return exl3_moe_kernel<1, 256, 0>; }
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k1_cb1.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k1_cb1.cu
index ddcbf23..622680c 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k1_cb1.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k1_cb1.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k1_cb2.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k1_cb2.cu
index 7a89c1a..41b426c 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k1_cb2.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k1_cb2.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k1_cb2_m32.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k1_cb2_m32.cu
index 975a67a..02be9aa 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k1_cb2_m32.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k1_cb2_m32.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k1_cb2_m64.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k1_cb2_m64.cu
index 8b4a86b..875fe05 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k1_cb2_m64.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k1_cb2_m64.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k2_cb0.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k2_cb0.cu
new file mode 100644
index 0000000..1efd002
--- /dev/null
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k2_cb0.cu
@@ -0,0 +1,8 @@
+// fp32 MMA accumulation (no EXL3_GEMM_H_ACC): the fused kernel's expert groups give each block long k spans, where fp16
+// accumulation of 3INST experts measured ~1.4x the KLD of the unfused path on a 3090; no speed cost
+#define EXL3_GEMM_NO_H_ACC
+#include "exl3_moe_instances.cuh"
+#include "../exl3_moe_kernel.cuh"
+
+fp_exl3_moe_kernel exl3_moe_kernel_k2_n128_cb0() { return exl3_moe_kernel<2, 128, 0>; }
+fp_exl3_moe_kernel exl3_moe_kernel_k2_n256_cb0() { return exl3_moe_kernel<2, 256, 0>; }
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k2_cb1.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k2_cb1.cu
index 11d97a4..42d13b8 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k2_cb1.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k2_cb1.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k2_cb2.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k2_cb2.cu
index 81d48d5..23e776d 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k2_cb2.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k2_cb2.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k2_cb2_m32.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k2_cb2_m32.cu
index a23d3ce..678ea21 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k2_cb2_m32.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k2_cb2_m32.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k2_cb2_m64.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k2_cb2_m64.cu
index b30fdca..73d5c8c 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k2_cb2_m64.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k2_cb2_m64.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k3_cb0.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k3_cb0.cu
new file mode 100644
index 0000000..f486710
--- /dev/null
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k3_cb0.cu
@@ -0,0 +1,8 @@
+// fp32 MMA accumulation (no EXL3_GEMM_H_ACC): the fused kernel's expert groups give each block long k spans, where fp16
+// accumulation of 3INST experts measured ~1.4x the KLD of the unfused path on a 3090; no speed cost
+#define EXL3_GEMM_NO_H_ACC
+#include "exl3_moe_instances.cuh"
+#include "../exl3_moe_kernel.cuh"
+
+fp_exl3_moe_kernel exl3_moe_kernel_k3_n128_cb0() { return exl3_moe_kernel<3, 128, 0>; }
+fp_exl3_moe_kernel exl3_moe_kernel_k3_n256_cb0() { return exl3_moe_kernel<3, 256, 0>; }
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k3_cb1.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k3_cb1.cu
index 5407679..b398a80 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k3_cb1.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k3_cb1.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k3_cb2.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k3_cb2.cu
index 5d0fabb..8459629 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k3_cb2.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k3_cb2.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k3_cb2_m32.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k3_cb2_m32.cu
index 3d6a5ef..936609e 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k3_cb2_m32.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k3_cb2_m32.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k3_cb2_m64.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k3_cb2_m64.cu
index 518aba5..9a4d6d3 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k3_cb2_m64.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k3_cb2_m64.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k4_cb0.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k4_cb0.cu
new file mode 100644
index 0000000..3bef79f
--- /dev/null
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k4_cb0.cu
@@ -0,0 +1,8 @@
+// fp32 MMA accumulation (no EXL3_GEMM_H_ACC): the fused kernel's expert groups give each block long k spans, where fp16
+// accumulation of 3INST experts measured ~1.4x the KLD of the unfused path on a 3090; no speed cost
+#define EXL3_GEMM_NO_H_ACC
+#include "exl3_moe_instances.cuh"
+#include "../exl3_moe_kernel.cuh"
+
+fp_exl3_moe_kernel exl3_moe_kernel_k4_n128_cb0() { return exl3_moe_kernel<4, 128, 0>; }
+fp_exl3_moe_kernel exl3_moe_kernel_k4_n256_cb0() { return exl3_moe_kernel<4, 256, 0>; }
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k4_cb1.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k4_cb1.cu
index 9a05967..e5ed733 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k4_cb1.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k4_cb1.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k4_cb2.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k4_cb2.cu
index b54a0fe..d773e3f 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k4_cb2.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k4_cb2.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k4_cb2_m32.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k4_cb2_m32.cu
index f9719a9..dea9f5a 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k4_cb2_m32.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k4_cb2_m32.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k4_cb2_m64.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k4_cb2_m64.cu
index 242274e..fbe2c70 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k4_cb2_m64.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k4_cb2_m64.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k5_cb0.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k5_cb0.cu
new file mode 100644
index 0000000..8f87558
--- /dev/null
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k5_cb0.cu
@@ -0,0 +1,8 @@
+// fp32 MMA accumulation (no EXL3_GEMM_H_ACC): the fused kernel's expert groups give each block long k spans, where fp16
+// accumulation of 3INST experts measured ~1.4x the KLD of the unfused path on a 3090; no speed cost
+#define EXL3_GEMM_NO_H_ACC
+#include "exl3_moe_instances.cuh"
+#include "../exl3_moe_kernel.cuh"
+
+fp_exl3_moe_kernel exl3_moe_kernel_k5_n128_cb0() { return exl3_moe_kernel<5, 128, 0>; }
+fp_exl3_moe_kernel exl3_moe_kernel_k5_n256_cb0() { return exl3_moe_kernel<5, 256, 0>; }
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k5_cb1.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k5_cb1.cu
index 9e99403..31da7bb 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k5_cb1.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k5_cb1.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k5_cb2.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k5_cb2.cu
index f51c2ab..d64ef2c 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k5_cb2.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k5_cb2.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k5_cb2_m32.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k5_cb2_m32.cu
index 6c5bd59..c586760 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k5_cb2_m32.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k5_cb2_m32.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k5_cb2_m64.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k5_cb2_m64.cu
index 76e967d..63b1fc2 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k5_cb2_m64.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k5_cb2_m64.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k6_cb0.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k6_cb0.cu
new file mode 100644
index 0000000..441f23e
--- /dev/null
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k6_cb0.cu
@@ -0,0 +1,8 @@
+// fp32 MMA accumulation (no EXL3_GEMM_H_ACC): the fused kernel's expert groups give each block long k spans, where fp16
+// accumulation of 3INST experts measured ~1.4x the KLD of the unfused path on a 3090; no speed cost
+#define EXL3_GEMM_NO_H_ACC
+#include "exl3_moe_instances.cuh"
+#include "../exl3_moe_kernel.cuh"
+
+fp_exl3_moe_kernel exl3_moe_kernel_k6_n128_cb0() { return exl3_moe_kernel<6, 128, 0>; }
+fp_exl3_moe_kernel exl3_moe_kernel_k6_n256_cb0() { return exl3_moe_kernel<6, 256, 0>; }
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k6_cb1.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k6_cb1.cu
index ff1a22e..8a8ad4b 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k6_cb1.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k6_cb1.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k6_cb2.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k6_cb2.cu
index b3dde26..7df2b45 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k6_cb2.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k6_cb2.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k6_cb2_m32.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k6_cb2_m32.cu
index 9479cd2..1a39138 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k6_cb2_m32.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k6_cb2_m32.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k6_cb2_m64.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k6_cb2_m64.cu
index 24063de..20ae592 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k6_cb2_m64.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k6_cb2_m64.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k7_cb0.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k7_cb0.cu
new file mode 100644
index 0000000..d6e9cb5
--- /dev/null
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k7_cb0.cu
@@ -0,0 +1,8 @@
+// fp32 MMA accumulation (no EXL3_GEMM_H_ACC): the fused kernel's expert groups give each block long k spans, where fp16
+// accumulation of 3INST experts measured ~1.4x the KLD of the unfused path on a 3090; no speed cost
+#define EXL3_GEMM_NO_H_ACC
+#include "exl3_moe_instances.cuh"
+#include "../exl3_moe_kernel.cuh"
+
+fp_exl3_moe_kernel exl3_moe_kernel_k7_n128_cb0() { return exl3_moe_kernel<7, 128, 0>; }
+fp_exl3_moe_kernel exl3_moe_kernel_k7_n256_cb0() { return exl3_moe_kernel<7, 256, 0>; }
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k7_cb1.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k7_cb1.cu
index f62d1ed..7e521ad 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k7_cb1.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k7_cb1.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k7_cb2.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k7_cb2.cu
index 8e00888..900f4e8 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k7_cb2.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k7_cb2.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k7_cb2_m32.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k7_cb2_m32.cu
index 5dd3fe3..67b33c3 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k7_cb2_m32.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k7_cb2_m32.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k7_cb2_m64.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k7_cb2_m64.cu
index 11ac9c0..097fc3c 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k7_cb2_m64.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k7_cb2_m64.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k8_cb0.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k8_cb0.cu
new file mode 100644
index 0000000..6eb64ff
--- /dev/null
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k8_cb0.cu
@@ -0,0 +1,8 @@
+// fp32 MMA accumulation (no EXL3_GEMM_H_ACC): the fused kernel's expert groups give each block long k spans, where fp16
+// accumulation of 3INST experts measured ~1.4x the KLD of the unfused path on a 3090; no speed cost
+#define EXL3_GEMM_NO_H_ACC
+#include "exl3_moe_instances.cuh"
+#include "../exl3_moe_kernel.cuh"
+
+fp_exl3_moe_kernel exl3_moe_kernel_k8_n128_cb0() { return exl3_moe_kernel<8, 128, 0>; }
+fp_exl3_moe_kernel exl3_moe_kernel_k8_n256_cb0() { return exl3_moe_kernel<8, 256, 0>; }
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k8_cb1.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k8_cb1.cu
index 95ed81d..a1b4ea6 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k8_cb1.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k8_cb1.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k8_cb2.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k8_cb2.cu
index 17881ea..d99c222 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k8_cb2.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k8_cb2.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k8_cb2_m32.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k8_cb2_m32.cu
index 3663fea..44b3a0c 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k8_cb2_m32.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k8_cb2_m32.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k8_cb2_m64.cu b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k8_cb2_m64.cu
index 635be61..b5963c3 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k8_cb2_m64.cu
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_inst_k8_cb2_m64.cu
@@ -1,3 +1,4 @@
+#define EXL3_GEMM_NO_H_ACC // fp32 MMA accumulation: see exl3_moe_inst_k1_cb0.cu (halves the block error, no speed cost)
#include "exl3_moe_instances.cuh"
#include "../exl3_moe_kernel.cuh"
diff --git a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_instances.cuh b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_instances.cuh
index b94c550..9280cbe 100644
--- a/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_instances.cuh
+++ b/exllamav3/exllamav3_ext/quant/comp_units/exl3_moe_instances.cuh
@@ -5,6 +5,8 @@
typedef void (*fp_exl3_moe_kernel) (EXL3_MOE_KERNEL_ARGS);
#define EXL3_MOE_DECLARE_GETTERS(K) \
+ fp_exl3_moe_kernel exl3_moe_kernel_k##K##_n128_cb0(); \
+ fp_exl3_moe_kernel exl3_moe_kernel_k##K##_n256_cb0(); \
fp_exl3_moe_kernel exl3_moe_kernel_k##K##_n128_cb1(); \
fp_exl3_moe_kernel exl3_moe_kernel_k##K##_n256_cb1(); \
fp_exl3_moe_kernel exl3_moe_kernel_k##K##_n128_cb2(); \
diff --git a/exllamav3/exllamav3_ext/quant/exl3_dec.cu b/exllamav3/exllamav3_ext/quant/exl3_dec.cu
index c3e8289..099fd8a 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_dec.cu
+++ b/exllamav3/exllamav3_ext/quant/exl3_dec.cu
@@ -12,7 +12,7 @@
// - mul1 codebook: v = fp16(0x6400 + bytesum(w * 0x83DCD12D)) * fp16(0x1eee) + fp16(0xc931)
// - W = diag(suh) H128 W_hat H128 diag(svh), H128 the normalised Sylvester Hadamard per 128 block
-#if defined(USE_ROCM)
+#if defined(USE_ROCM) || defined(EXL3_PORT_DEC)
#include <cuda_runtime.h>
#include <cuda_fp16.h>
@@ -30,6 +30,7 @@
#include <ATen/ops/empty.h>
#include "exl3_dec.cuh"
#include "../util.cuh"
+#include "../port.cuh"
// QWG_ABLATE=1 compiles runtime ablation arms into the dense gemv (env EXL3_QWG_DABL; timing only, garbage results by design):
// bit 1 = no trellis decode (loads kept alive by an xor), bit 2 = no DRAM stream (every k-tile read is k-row 0..ktw-1), bit 4 = no epilogue
@@ -39,8 +40,13 @@
namespace exl3dec {
+#if defined(USE_ROCM)
typedef _Float16 f16x2 __attribute__((ext_vector_type(2)));
typedef uint32_t u32x4 __attribute__((ext_vector_type(4)));
+#else
+typedef __half2 f16x2;
+typedef uint4 u32x4;
+#endif
constexpr int WPB = 8; // waves per block
constexpr int THREADS = WPB * 32;
@@ -96,11 +102,11 @@ __device__ __forceinline__ uint32_t window(const uint32_t* w)
constexpr int o = s & 31;
constexpr int W = Fmt<KB2>::WORDS;
if constexpr (o <= 16)
- return __builtin_amdgcn_ubfe(w[i], 16 - o, 16);
+ return PORT_UBFE16(w[i], 16 - o);
else if constexpr (MASK)
- return __builtin_amdgcn_alignbit(w[i], w[(i + 1) % W], 48 - o) & 0xffffu;
+ return PORT_ALIGNBIT(w[i], w[(i + 1) % W], 48 - o) & 0xffffu;
else
- return __builtin_amdgcn_alignbit(w[i], w[(i + 1) % W], 48 - o);
+ return PORT_ALIGNBIT(w[i], w[(i + 1) % W], 48 - o);
}
// Product variants for p = (x & 0xffff) * 0x83DCD12D mod 2^32:
@@ -121,8 +127,10 @@ constexpr bool PROD_MASK = EXL3_DEC_PROD != 2;
// carrying a 32-bit literal (the fully unrolled tile decode is instruction-cache bound on gfx1151,
// bytes matter). The mcg codebook's decode yields the final fp16 weight directly, so its affine
// fold (kinv2/kbias2, applied in pair_dot/block_reduce) is the identity.
-#if !defined(EXL3_DEC_SCONST)
+#if !defined(EXL3_DEC_SCONST) && defined(USE_ROCM)
#define EXL3_DEC_SCONST 1
+#elif !defined(EXL3_DEC_SCONST)
+#define EXL3_DEC_SCONST 0 // CUDA: the s_mov asm is AMDGPU only
#endif
struct DecConst
{
@@ -196,8 +204,8 @@ __device__ __forceinline__ uint32_t mul1_pair(uint32_t w0, uint32_t w1, const De
#else
const uint32_t p0 = mul1_prod(w0, c);
const uint32_t p1 = mul1_prod(w1, c);
- const uint32_t s0 = __builtin_amdgcn_sad_u8(p0, 0u, c.sadacc);
- return __builtin_amdgcn_sad_hi_u8(p1, 0u, s0);
+ const uint32_t s0 = PORT_SAD_U8(p0, c.sadacc);
+ return PORT_SAD_HI_U8(p1, s0);
#endif
}
@@ -243,6 +251,20 @@ __device__ __forceinline__ uint32_t pair_decode(uint32_t w0, uint32_t w1, const
// at the noise floor (-0.015 +- 0.068 %, 8 x 1024 tok @4K). EXL3_DEC_MOE_FOLD=0 restores the exact path.
template <int CB> constexpr bool dec_exact() { return CB == 3 ? false : (bool) EXL3_DEC_EXACT; }
+// Which (K, codebook) pairs get the fully unrolled decode. ROCm: all. CUDA: cicc needs minutes and GBs per pair, so an
+// EXL3_PORT_DEC build compiles the masks below (bit kb2 / bit cb; default K3 and K4, mul1) and traps on the others
+#if defined(USE_ROCM)
+template <int KB2, int CB> constexpr bool dec_built() { return true; }
+#else
+#if !defined(EXL3_PORT_DEC_KB2_MASK)
+#define EXL3_PORT_DEC_KB2_MASK ((1 << 6) | (1 << 8))
+#endif
+#if !defined(EXL3_PORT_DEC_CB_MASK)
+#define EXL3_PORT_DEC_CB_MASK (1 << 2)
+#endif
+template <int KB2, int CB> constexpr bool dec_built() { return ((EXL3_PORT_DEC_KB2_MASK >> KB2) & 1) && ((EXL3_PORT_DEC_CB_MASK >> CB) & 1); }
+#endif
+
template <int KB2, int M, int CB = 2>
__device__ __forceinline__ void pair_dot(const uint32_t* w, const f16x2* xp, float* acc, const DecConst& c)
{
@@ -253,17 +275,17 @@ __device__ __forceinline__ void pair_dot(const uint32_t* w, const f16x2* xp, flo
// multiplies the full 32-bit window, so it always needs the masked form.
constexpr bool MASK = (CB >= 2) ? PROD_MASK : true;
const uint32_t h2 = pair_decode<CB>(window<KB2, 2 * M, MASK>(w), window<KB2, 2 * M + 1, MASK>(w), c);
- f16x2 h = __builtin_bit_cast(f16x2, h2);
+ f16x2 h = PORT_AS_F16X2(h2);
if constexpr (dec_exact<CB>())
- h = __builtin_elementwise_fma(h, __builtin_bit_cast(f16x2, c.kinv2), __builtin_bit_cast(f16x2, c.kbias2));
+ h = PORT_HFMA2(h, PORT_AS_F16X2(c.kinv2), PORT_AS_F16X2(c.kbias2));
constexpr int t = M >> 2;
constexpr int jj = M & 3;
constexpr int q = (t & 3) + ((jj & 1) ? 4 : 0);
constexpr int col = (t >> 2) + ((jj & 2) ? 8 : 0);
- acc[col] = __builtin_amdgcn_fdot2(h, xp[q], acc[col], false);
+ acc[col] = PORT_FDOT2_F32(h, xp[q], acc[col]);
// Scheduling fence every SB pairs: left free, the scheduler hoists the window/product work of a
// whole tile ahead of the dot products and spills (hundreds of VGPRs)
- if constexpr ((M % EXL3_DEC_SB) == EXL3_DEC_SB - 1) __builtin_amdgcn_sched_barrier(0);
+ if constexpr ((M % EXL3_DEC_SB) == EXL3_DEC_SB - 1) PORT_SCHED_BARRIER();
if constexpr (M + 1 < 128) pair_dot<KB2, M + 1, CB>(w, xp, acc, c);
}
@@ -282,7 +304,8 @@ __device__ __forceinline__ void tile_dot(const uint32_t* w, const f16x2* xp, flo
for (int i = 0; i < Fmt<KB2>::WORDS; ++i) t ^= w[i];
acc[0] += (float) (t & 0xff) * (float) xp[0][0];
#else
- pair_dot<KB2, 0, CB>(w, xp, acc, c);
+ if constexpr (dec_built<KB2, CB>()) pair_dot<KB2, 0, CB>(w, xp, acc, c);
+ else PORT_TRAP();
#endif
}
@@ -296,23 +319,23 @@ __device__ __forceinline__ void pair_dot_r(const uint32_t* w, const f16x2 (*xp)[
{
constexpr bool MASK = (CB >= 2) ? PROD_MASK : true;
const uint32_t h2 = pair_decode<CB>(window<KB2, 2 * M, MASK>(w), window<KB2, 2 * M + 1, MASK>(w), c);
- f16x2 h = __builtin_bit_cast(f16x2, h2);
+ f16x2 h = PORT_AS_F16X2(h2);
if constexpr (dec_exact<CB>())
- h = __builtin_elementwise_fma(h, __builtin_bit_cast(f16x2, c.kinv2), __builtin_bit_cast(f16x2, c.kbias2));
+ h = PORT_HFMA2(h, PORT_AS_F16X2(c.kinv2), PORT_AS_F16X2(c.kbias2));
constexpr int t = M >> 2;
constexpr int jj = M & 3;
constexpr int q = (t & 3) + ((jj & 1) ? 4 : 0);
constexpr int col = (t >> 2) + ((jj & 2) ? 8 : 0);
#pragma unroll
for (int j = 0; j < RM; ++j)
- acc[j][col] = __builtin_amdgcn_fdot2(h, xp[j][q], acc[j][col], false);
- if constexpr ((M % EXL3_DEC_SB) == EXL3_DEC_SB - 1) __builtin_amdgcn_sched_barrier(0);
+ acc[j][col] = PORT_FDOT2_F32(h, xp[j][q], acc[j][col]);
+ if constexpr ((M % EXL3_DEC_SB) == EXL3_DEC_SB - 1) PORT_SCHED_BARRIER();
if constexpr (M + 1 < 128) pair_dot_r<KB2, M + 1, CB, RM>(w, xp, acc, c);
}
// fp16 codebook constants (codebook.cuh decode_3inst<2>)
-__device__ __forceinline__ float cb_kinv() { return (float) __builtin_bit_cast(_Float16, (unsigned short) 0x1eee); }
-__device__ __forceinline__ float cb_kbias() { return (float) __builtin_bit_cast(_Float16, (unsigned short) 0xc931); }
+__device__ __forceinline__ float cb_kinv() { return PORT_F16_BITS_TO_F32(0x1eee); }
+__device__ __forceinline__ float cb_kbias() { return PORT_F16_BITS_TO_F32(0xc931); }
// The mcg decode is its own affine map (identity), so EXL3_DEC_EXACT 0 (affine folded into the
// block sums) and 1 (folded per value) coincide there.
@@ -327,10 +350,10 @@ __device__ __forceinline__ void load_tile(const u32x4* p, u32x4* r)
const int ln = threadIdx.x & 31;
const u32x4* base = p - ln * Fmt<KB2>::VEC;
#pragma unroll
- for (int v = 0; v < Fmt<KB2>::VEC; ++v) r[v] = __builtin_nontemporal_load(base + v * 32 + ln);
+ for (int v = 0; v < Fmt<KB2>::VEC; ++v) r[v] = PORT_LD_STREAM(base + v * 32 + ln);
#else
#pragma unroll
- for (int v = 0; v < Fmt<KB2>::VEC; ++v) r[v] = __builtin_nontemporal_load(p + v);
+ for (int v = 0; v < Fmt<KB2>::VEC; ++v) r[v] = PORT_LD_STREAM(p + v);
#endif
}
@@ -375,7 +398,7 @@ __device__ __forceinline__ void lane_gemv(const u32x4* tiles, size_t tstride, co
#pragma unroll
for (int q = 0; q < 8; ++q) xp[q] = xq[q];
tile_dot<KB2, CB>(reinterpret_cast<const uint32_t*>(cur), xp, acc, dc);
- __builtin_amdgcn_sched_barrier(0);
+ PORT_SCHED_BARRIER();
}
return;
}
@@ -397,7 +420,7 @@ __device__ __forceinline__ void lane_gemv(const u32x4* tiles, size_t tstride, co
if constexpr (NODEC) { uint32_t xx = 0; for (int v = 0; v < VEC; ++v) xx ^= buf[r][v].x ^ buf[r][v].y ^ buf[r][v].z ^ buf[r][v].w; acc[0] += __uint_as_float(xx & 0x3fffffff); }
else tile_dot<KB2, CB>(reinterpret_cast<const uint32_t*>(buf[r]), xp, acc, dc);
if (i + RING < n) load_tile<KB2>(tiles + (i + RING) * tstride, buf[r]);
- __builtin_amdgcn_sched_barrier(0); // keep the scheduler from interleaving tiles (VGPR blowup)
+ PORT_SCHED_BARRIER(); // keep the scheduler from interleaving tiles (VGPR blowup)
}
}
}
@@ -440,7 +463,7 @@ __device__ __forceinline__ void lane_gemv_r(const u32x4* tiles, size_t tstride,
tile_dot<KB2, CB>(reinterpret_cast<const uint32_t*>(buf[r]), xp, acc[j], dc);
}
if (i + RING < n) load_tile<KB2>(tiles + (i + RING) * tstride, buf[r]);
- __builtin_amdgcn_sched_barrier(0);
+ PORT_SCHED_BARRIER();
}
}
}
@@ -470,9 +493,10 @@ __device__ __forceinline__ void lane_gemv_r1(const u32x4* tiles, size_t tstride,
#pragma unroll
for (int q = 0; q < 8; ++q) xp[j][q] = xq[q];
}
- pair_dot_r<KB2, 0, CB, RM>(reinterpret_cast<const uint32_t*>(buf[r]), xp, acc, dc);
+ if constexpr (dec_built<KB2, CB>()) pair_dot_r<KB2, 0, CB, RM>(reinterpret_cast<const uint32_t*>(buf[r]), xp, acc, dc);
+ else PORT_TRAP();
if (i + RING < n) load_tile<KB2>(tiles + (i + RING) * tstride, buf[r]);
- __builtin_amdgcn_sched_barrier(0);
+ PORT_SCHED_BARRIER();
}
}
}
@@ -489,7 +513,7 @@ __device__ __forceinline__ void fwht128(float* v, int lane)
#pragma unroll
for (int i = 0; i < 4; ++i)
{
- const float o = __shfl_xor(v[i], m);
+ const float o = PORT_SHFL_XOR(v[i], m);
v[i] = (lane & m) ? (o - v[i]) : (v[i] + o);
}
}
@@ -503,7 +527,7 @@ __device__ __forceinline__ half sat_half(float f)
__device__ __forceinline__ float wave_sum(float v)
{
#pragma unroll
- for (int m = 1; m < 32; m <<= 1) v += __shfl_xor(v, m);
+ for (int m = 1; m < 32; m <<= 1) v += PORT_SHFL_XOR(v, m);
return v;
}
@@ -620,7 +644,7 @@ __device__ __forceinline__ void k_split(int G, int kb, int kbs, int& k0, int& kt
__device__ __forceinline__ float ld_coherent(const float* p)
{
- return __hip_atomic_load(p, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
+ return PORT_LD_COHERENT(p);
}
// ------------------------------------------------------------------------------------------------
@@ -1589,8 +1613,8 @@ void router_kernel(const half* __restrict__ x, RouterNorm rn, const half* __rest
#pragma unroll
for (int m = 16; m >= 1; m >>= 1)
{
- const float ov = __shfl_xor(bv, m);
- const int oi = __shfl_xor(bi, m);
+ const float ov = PORT_SHFL_XOR(bv, m);
+ const int oi = PORT_SHFL_XOR(bi, m);
if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; }
}
const int pb = j & 1;
@@ -1761,8 +1785,8 @@ void router_rows_kernel(const half* __restrict__ x, const half* __restrict__ G,
#pragma unroll
for (int m = 16; m >= 1; m >>= 1)
{
- const float ov = __shfl_xor(bv, m);
- const int oi = __shfl_xor(bi, m);
+ const float ov = PORT_SHFL_XOR(bv, m);
+ const int oi = PORT_SHFL_XOR(bi, m);
if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; }
}
const int pb = j & 1;
@@ -1945,6 +1969,9 @@ inline int kb2_of(double K)
{
const int kb2 = (int) (K * 2.0 + 0.5);
TORCH_CHECK(kb2 >= 4 && kb2 <= 14 && (double) kb2 == K * 2.0, "exl3_dec: unsupported K ", K);
+#if !defined(USE_ROCM)
+ TORCH_CHECK((EXL3_PORT_DEC_KB2_MASK >> kb2) & 1, "exl3_dec: K ", K, " not in this build's EXL3_PORT_DEC_KB2_MASK");
+#endif
return kb2;
}
diff --git a/exllamav3/exllamav3_ext/quant/exl3_dec.cuh b/exllamav3/exllamav3_ext/quant/exl3_dec.cuh
index 85d3b81..44d4b35 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_dec.cuh
+++ b/exllamav3/exllamav3_ext/quant/exl3_dec.cuh
@@ -13,7 +13,7 @@
// The two templates decode bit-identically to their codebook's reference decode; only the
// summation order differs from the reconstruct+hgemm path.
-#if defined(USE_ROCM)
+#if defined(USE_ROCM) || defined(EXL3_PORT_DEC)
// y[N] = x[K] @ W, x fp16 [1, K], out fp16 or fp32 [1, N]. `scratch` is a float32 workspace and
// `counters` an int32 workspace (zeroed once, left zeroed by every call), see exl3_dec_workspace.
diff --git a/exllamav3/exllamav3_ext/quant/exl3_gemm.cu b/exllamav3/exllamav3_ext/quant/exl3_gemm.cu
index b53d4d8..b7fc9cc 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_gemm.cu
+++ b/exllamav3/exllamav3_ext/quant/exl3_gemm.cu
@@ -69,7 +69,7 @@ uint64_t gemm_autotune_hash
h ^= v;
h *= 1099511628211ull;
};
- mix((uint64_t) MIN(roundup_pow2(size_m), 16));
+ mix((uint64_t) (size_m <= 16 ? roundup_pow2(size_m) : MIN(CEIL_DIVIDE(size_m, 16) * 16, 64)));
mix((uint64_t) size_k);
mix((uint64_t) size_n);
mix((uint64_t) K);
diff --git a/exllamav3/exllamav3_ext/quant/exl3_gemm_inner.cuh b/exllamav3/exllamav3_ext/quant/exl3_gemm_inner.cuh
index 05bcaaa..97e585b 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_gemm_inner.cuh
+++ b/exllamav3/exllamav3_ext/quant/exl3_gemm_inner.cuh
@@ -13,7 +13,8 @@
// faster at bsz 1 on RTX 3090 together with the codebook.cuh IMUL change (see benchmarks/exl3_m1_bench).
// Max observed error vs fp32 accumulation is ~1% of output RMS at k=4096, well below quantization noise.
// Only enabled for sm_86 for now; unvalidated on other archs where fp32-acc HMMA is also half rate.
-#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ == 860)
+// EXL3_GEMM_NO_H_ACC (per translation unit): keep fp32 accumulation, e.g. for the fused 3INST MoE instances
+#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ == 860) && !defined(EXL3_GEMM_NO_H_ACC)
#define EXL3_GEMM_H_ACC 1
#else
#define EXL3_GEMM_H_ACC 0
@@ -49,7 +50,19 @@ void exl3_gemm_kernel_inner
// const int FRAGS_M = TILEBLOCKS_M;
const int FRAGS_N_PER_WARP = 2 * TILEBLOCKS_N / (EXL3_GEMM_BASE_THREADS / 32);
- const int sh_a_stage_size = TILESIZE_M * TILESIZE_K; // in halfs
+ // Warp-private pipeline (CUDA, 16x16 tiles). Each warp only ever decodes its own FRAGS_N_PER_WARP / 2 B blocks,
+ // contiguous in smem and in global, so it copies exactly those (lane-indexed) plus its own copy of the A tile, and waits for
+ // its stage with cp.async.wait_group + __syncwarp: no block-wide barrier in the main loop. Same data, same smem slots for B,
+ // same arithmetic and order (bitwise). The column-end reduce keeps its barriers
+#if !defined(USE_ROCM) && !defined(EXL3_GEMM_NO_PW)
+ constexpr bool PW = TILESIZE_M == 16 && TILESIZE_K == 16;
+#else
+ constexpr bool PW = false;
+#endif
+ constexpr int PW_WARPS = PW ? EXL3_GEMM_BASE_THREADS / 32 : 1;
+ constexpr int PW_B_INT4 = FRAGS_N_PER_WARP / 2 * 256 / 16 * bits / 8; // B int4 chunks per warp per stage
+
+ const int sh_a_stage_size = TILESIZE_M * TILESIZE_K * PW_WARPS; // in halfs
const int sh_b_stage_size = TILEBLOCKS_K * TILEBLOCKS_N * 256 / 16 * bits; // in uint16s
const int sh_c_size = MAX // in floats
(
@@ -121,16 +134,18 @@ void exl3_gemm_kernel_inner
const half* gl_a_ptr = A + slice_m * gl_a_stride_m + slice0_k * gl_a_stride_k;
half* sh0_a_ptr = sh_a + (slice0_iters % SH_STAGES) * sh_a_stage_size;
- const int load_a_iters = CEIL_DIVIDE(sh0_a_stride_m / 8, EXL3_GEMM_BASE_THREADS);
+ // PW: the 32 lanes of each warp copy the whole 16x16 A tile (32 int4) into the warp's own A slot
+ const int load_a_iters = PW ? 1 : CEIL_DIVIDE(sh0_a_stride_m / 8, EXL3_GEMM_BASE_THREADS);
+ const int a_t = PW ? lane_id : t;
bool pred_a_gl[load_a_iters];
int load_a_gl[load_a_iters];
int load_a_sh[load_a_iters];
for (int i = 0; i < load_a_iters; ++i)
{
- int k = (i * EXL3_GEMM_BASE_THREADS + t) % (gl_a_stride_k / 8);
- int m = (i * EXL3_GEMM_BASE_THREADS + t) / (gl_a_stride_k / 8);
+ int k = (i * EXL3_GEMM_BASE_THREADS + a_t) % (gl_a_stride_k / 8);
+ int m = (i * EXL3_GEMM_BASE_THREADS + a_t) / (gl_a_stride_k / 8);
load_a_gl[i] = m * size_k / 8 + k;
- load_a_sh[i] = m * A_COLS + (k ^ ((m >> A_SWIZZLE_SHIFT) & A_SWIZZLE_MASK));
+ load_a_sh[i] = m * A_COLS + (k ^ ((m >> A_SWIZZLE_SHIFT) & A_SWIZZLE_MASK)) + (PW ? warp_id * (TILESIZE_M * TILESIZE_K / 8) : 0);
pred_a_gl[i] = m < size_m;
}
@@ -140,37 +155,66 @@ void exl3_gemm_kernel_inner
const uint16_t* gl_b_ptr = B + slice0_k * gl_b_stride_k + slice0_n * gl_b_stride_n;
uint16_t* sh0_b_ptr = sh_b + (slice0_iters % SH_STAGES) * sh_b_stage_size;
- const int load_b_iters = CEIL_DIVIDE(sh0_b_stride_k / 8, EXL3_GEMM_BASE_THREADS);
+ // PW: chunk c of the stage row is copied by warp c / PW_B_INT4 (the warp that decodes it), lane (c % PW_B_INT4) % 32
+ const int load_b_iters = PW ? CEIL_DIVIDE(PW_B_INT4, 32) : CEIL_DIVIDE(sh0_b_stride_k / 8, EXL3_GEMM_BASE_THREADS);
bool pred_b_gl[load_b_iters];
int load_b_gl[load_b_iters];
+ int load_b_c[load_b_iters];
for (int i = 0; i < load_b_iters; ++i)
{
- int n = (i * EXL3_GEMM_BASE_THREADS + t) % (gl_b_stride_n / 8);
- int k = (i * EXL3_GEMM_BASE_THREADS + t) / (gl_b_stride_n / 8);
+ int c = PW ? warp_id * PW_B_INT4 + i * 32 + lane_id : i * EXL3_GEMM_BASE_THREADS + t;
+ int n = c % (gl_b_stride_n / 8);
+ int k = c / (gl_b_stride_n / 8);
+ load_b_c[i] = c;
load_b_gl[i] = k * (blocks_n_full * 256 / 16 * bits / 8) + n;
- pred_b_gl[i] = i * EXL3_GEMM_BASE_THREADS + t < sh0_b_stride_k / 8;
+ pred_b_gl[i] = PW ? i * 32 + lane_id < PW_B_INT4 : c < sh0_b_stride_k / 8;
+ }
+
+ // Per-thread copy addresses are loop-carried (advanced by a step, or by a precomputed wrap delta at the
+ // end of a k column) so ptxas keeps them in registers instead of rematerializing the row / column / swizzle split
+ // from t on every iteration. Same addresses as gl_a_ptr / gl_b_ptr / sh0_*_ptr + the per-thread offsets above
+ const int4* a_src[load_a_iters];
+ int4* a_dst[load_a_iters];
+ for (int i = 0; i < load_a_iters; ++i)
+ {
+ a_src[i] = (const int4*) gl_a_ptr + load_a_gl[i];
+ a_dst[i] = (int4*) sh0_a_ptr + load_a_sh[i];
+ }
+ const int4* b_src[load_b_iters];
+ int4* b_dst[load_b_iters];
+ for (int i = 0; i < load_b_iters; ++i)
+ {
+ b_src[i] = (const int4*) gl_b_ptr + load_b_gl[i];
+ b_dst[i] = (int4*) sh0_b_ptr + load_b_c[i];
}
+ const int a_step = gl_a_stride_k / 8; // int4 units
+ const int a_wrap = -(tiles_k - 1) * (gl_a_stride_k / 8); // back to k = 0 (slice_m fixed)
+ const int b_step = gl_b_stride_k / 8;
+ const int b_wrap = (gl_b_stride_n - (tiles_k - 1) * gl_b_stride_k) / 8; // k = 0 of the next column
+ const int sh_a_back = -sh_a_stage_size / 8, sh_a_wrap = (SH_STAGES - 1) * sh_a_stage_size / 8;
+ const int sh_b_back = -sh_b_stage_size / 8, sh_b_wrap = (SH_STAGES - 1) * sh_b_stage_size / 8;
auto advance0 = [&] ()
{
slice0_k++;
slice0_iters--;
- int stage = slice0_iters % SH_STAGES;
- sh0_a_ptr = sh_a + stage * sh_a_stage_size;
- sh0_b_ptr = sh_b + stage * sh_b_stage_size;
+ // stage = slice0_iters % SH_STAGES steps down by one and wraps from 0 to SH_STAGES - 1
+ const bool sw = (unsigned) slice0_iters % SH_STAGES == SH_STAGES - 1;
+ const bool kw = slice0_k >= tiles_k;
+ if (kw) { slice0_k = 0; slice0_n++; }
- if (slice0_k >= tiles_k)
+ #pragma unroll
+ for (int i = 0; i < load_a_iters; ++i)
{
- slice0_k = 0;
- slice0_n++;
- gl_a_ptr = A + slice_m * gl_a_stride_m + slice0_k * gl_a_stride_k;
- gl_b_ptr = B + slice0_k * gl_b_stride_k + slice0_n * gl_b_stride_n;
+ a_src[i] += kw ? a_wrap : a_step;
+ a_dst[i] += sw ? sh_a_wrap : sh_a_back;
}
- else
+ #pragma unroll
+ for (int i = 0; i < load_b_iters; ++i)
{
- gl_a_ptr += gl_a_stride_k;
- gl_b_ptr += gl_b_stride_k;
+ b_src[i] += kw ? b_wrap : b_step;
+ b_dst[i] += sw ? sh_b_wrap : sh_b_back;
}
};
@@ -182,14 +226,31 @@ void exl3_gemm_kernel_inner
half* sh1_a_ptr = sh_a + (slice1_iters % SH_STAGES) * sh_a_stage_size;
uint16_t* sh1_b_ptr = sh_b + (slice1_iters % SH_STAGES) * sh_b_stage_size;
+ // Fragment read addresses, loop-carried like the copy addresses
+ const int4* a_frag[TILEBLOCKS_M];
+ {
+ int r = (lane_id % 8) + 8 * ((lane_id / 8) % 2);
+ int base_c = lane_id / 16 + sub_k * 2;
+ for (int m = 0; m < TILEBLOCKS_M; ++m)
+ {
+ int R = r + m * 16;
+ int c_swizzled = base_c ^ ((R >> A_SWIZZLE_SHIFT) & A_SWIZZLE_MASK);
+ a_frag[m] = (const int4*) sh1_a_ptr + R * A_COLS + c_swizzled + (PW ? warp_id * (TILESIZE_M * TILESIZE_K / 8) : 0);
+ }
+ }
+ const uint32_t* b_frag = (const uint32_t*) (sh1_b_ptr + (sub_k * TILEBLOCKS_N + warp_id * FRAGS_N_PER_WARP / 2) * 256 / 16 * bits);
+ const int shf_b_back = -sh_b_stage_size / 2, shf_b_wrap = (SH_STAGES - 1) * sh_b_stage_size / 2; // uint32 units
+
auto advance1 = [&] ()
{
slice1_k++;
slice1_iters--;
- int stage = slice1_iters % SH_STAGES;
- sh1_a_ptr = sh_a + stage * sh_a_stage_size;
- sh1_b_ptr = sh_b + stage * sh_b_stage_size;
+ const bool sw = (unsigned) slice1_iters % SH_STAGES == SH_STAGES - 1;
+ #pragma unroll
+ for (int m = 0; m < TILEBLOCKS_M; ++m)
+ a_frag[m] += sw ? sh_a_wrap : sh_a_back;
+ b_frag += sw ? shf_b_wrap : shf_b_back;
if (slice1_k >= tiles_k)
{
@@ -240,7 +301,7 @@ void exl3_gemm_kernel_inner
// Schedule load of the next A, B tiles to shared memory and advance the pipeline
auto async_load_gl = [&] ()
{
- if (sub_k)
+ if (TILESIZE_K > 16 && sub_k) // sub_k is 0 for 16-wide k tiles (256 threads)
{
cp_async_fence();
return;
@@ -249,26 +310,17 @@ void exl3_gemm_kernel_inner
if (slice0_iters)
{
// Copy tile from row-major A matrix (XOR-swizzled for bank-conflict-free ldmatrix)
+ #pragma unroll
+ for (int i = 0; i < load_a_iters; ++i)
{
- const int4* gl = (const int4*) gl_a_ptr;
- int4* sh = (int4*) sh0_a_ptr;
- #pragma unroll
- for (int i = 0; i < load_a_iters; ++i)
- {
- if (pred_a_gl[i]) cp_async(sh + load_a_sh[i], gl + load_a_gl[i]);
- }
+ if (pred_a_gl[i]) cp_async(a_dst[i], a_src[i]);
}
// Copy tile of 256-element blocks from quantized B matrix
+ #pragma unroll
+ for (int i = 0; i < load_b_iters; ++i)
{
- const int4* gl = (const int4*) gl_b_ptr;
- int4* sh = (int4*) sh0_b_ptr;
- #pragma unroll
- for (int i = 0; i < load_b_iters; ++i)
- {
- // cp_async_pred(sh + EXL3_GEMM_BASE_THREADS * i + t, gl + load_b_gl[i], pred_b_gl[i]);
- if (pred_b_gl[i]) cp_async(sh + EXL3_GEMM_BASE_THREADS * i + t, gl + load_b_gl[i]);
- }
+ if (pred_b_gl[i]) cp_async(b_dst[i], b_src[i]);
}
advance0();
}
@@ -285,29 +337,27 @@ void exl3_gemm_kernel_inner
if (!slice1_iters) return;
// A fragments (XOR-swizzled shared memory layout)
- {
- int r = (lane_id % 8) + 8 * ((lane_id / 8) % 2);
- int base_c = lane_id / 16 + sub_k * 2;
- #pragma unroll
- for (int m = 0; m < TILEBLOCKS_M; ++m)
- {
- int R = r + m * 16;
- int c_swizzled = base_c ^ ((R >> A_SWIZZLE_SHIFT) & A_SWIZZLE_MASK);
- ldsm4(frag_a[TILEBLOCKS_M == 1 ? buf : m], (int4*) sh1_a_ptr + R * A_COLS + c_swizzled);
- }
- }
+ #pragma unroll
+ for (int m = 0; m < TILEBLOCKS_M; ++m)
+ ldsm4(frag_a[TILEBLOCKS_M == 1 ? buf : m], (int4*) a_frag[m]);
// B fragments
#pragma unroll
for (int n2 = 0; n2 < FRAGS_N_PER_WARP; n2 += 2)
{
- int sub_n2 = warp_id * FRAGS_N_PER_WARP / 2 + n2 / 2;
- const uint32_t* shb = (const uint32_t*) (sh1_b_ptr + (sub_k * TILEBLOCKS_N + sub_n2) * 256 / 16 * bits);
+ const uint32_t* shb = b_frag + (n2 / 2) * ((256 / 16 * bits / 2));
dq_dispatch<bits, cb>(shb, lane_id << 3, frag_b[buf][n2], frag_b[buf][n2 + 1]);
}
+ // Redundant for SH_STAGES >= 3 (wait_stage() orders these reads before the next cp.async overwrite).
+ // CUDA sm_86, 16-wide k tiles: +4..12 % K3 / ~+1 % K4 per call, bitwise identical;
+ // kept for other tiles (-1 % without it) and on ROCm (unmeasured)
+#if defined(USE_ROCM)
__syncthreads();
+#else
+ if constexpr (TILESIZE_K != 16 || SH_STAGES < 3) __syncthreads();
+#endif
advance1();
};
@@ -877,7 +927,12 @@ void exl3_gemm_kernel_inner
auto wait_stage = [&] ()
{
cp_async_wait<SH_STAGES - 2>();
+#if defined(USE_ROCM)
__syncthreads();
+#else
+ if constexpr (PW) __syncwarp();
+ else __syncthreads();
+#endif
};
// Perform tensor core matmul on current tile
diff --git a/exllamav3/exllamav3_ext/quant/exl3_gemm_kernel.cuh b/exllamav3/exllamav3_ext/quant/exl3_gemm_kernel.cuh
index ee97afe..3591819 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_gemm_kernel.cuh
+++ b/exllamav3/exllamav3_ext/quant/exl3_gemm_kernel.cuh
@@ -38,12 +38,12 @@ void exl3_gemm_kernel(EXL3_GEMM_ARGS)
{
exl3_gemm_kernel_inner
<bits, c_fp32, cb, TILESIZE_M, TILESIZE_K, TILESIZE_N, SH_STAGES, FRAG_STAGES, true>
- (A_, B, C_, MIN(size_m_, 16), size_k, size_n, locks, svh);
+ (A_, B, C_, MIN(size_m_, TILESIZE_M), size_k, size_n, locks, svh);
- A_ += 16 * size_k;
- if constexpr (c_fp32) C_ = (void*) (((float*) C_) + 16 * size_n);
- else C_ = (void*) (((half*) C_) + 16 * size_n);
- size_m_ -= 16;
+ A_ += TILESIZE_M * size_k;
+ if constexpr (c_fp32) C_ = (void*) (((float*) C_) + TILESIZE_M * size_n);
+ else C_ = (void*) (((half*) C_) + TILESIZE_M * size_n);
+ size_m_ -= TILESIZE_M;
if (size_m_ > 0 || svh)
grid.sync();
@@ -233,13 +233,13 @@ void exl3_mgemm_kernel(EXL3_MGEMM_ARGS)
exl3_gemm_kernel_inner
<bits, c_fp32, cb, TILESIZE_M, TILESIZE_K, TILESIZE_N, SH_STAGES, FRAG_STAGES, false>
- (A_, B, C_, MIN(size_m_, 16), size_k, n_j, locks + lock_offs, nullptr, n_stride_j);
+ (A_, B, C_, MIN(size_m_, TILESIZE_M), size_k, n_j, locks + lock_offs, nullptr, n_stride_j);
}
- A_ += 16 * size_k;
- if constexpr (c_fp32) C_ = (void*) (((float*) C_) + 16 * n_stride_j);
- else C_ = (void*) (((half*) C_) + 16 * n_stride_j);
- size_m_ -= 16;
+ A_ += TILESIZE_M * size_k;
+ if constexpr (c_fp32) C_ = (void*) (((float*) C_) + TILESIZE_M * n_stride_j);
+ else C_ = (void*) (((half*) C_) + TILESIZE_M * n_stride_j);
+ size_m_ -= TILESIZE_M;
#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ > 890)
group_barrier(blockIdx.z, gridDim.x, barrier_counters_sense);
diff --git a/exllamav3/exllamav3_ext/quant/exl3_gemv_int8.cu b/exllamav3/exllamav3_ext/quant/exl3_gemv_int8.cu
index 12beb87..a5d1ff1 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_gemv_int8.cu
+++ b/exllamav3/exllamav3_ext/quant/exl3_gemv_int8.cu
@@ -159,6 +159,8 @@ static bool exl3_gemv_int8_sq
if (!fn) return false;
int rows_max = gemv_int8_sq_rows_max(M, residual);
+ static const int rows_ovr = [] { const char* e = getenv("EXL3_GEMV_ROWS"); return e ? atoi(e) : 0; }();
+ static const int policy = [] { const char* e = getenv("EXL3_GEMV_POLICY"); return e ? atoi(e) : 1; }();
// Mirror of the kernel's work decomposition (single-wave rule with a half-wave floor)
auto decomp = [&] (int grid_, int& ksplit, int& rows_per)
@@ -170,6 +172,18 @@ static bool exl3_gemv_int8_sq
rows_per = MAX(rows_per, SQ_MINROWS);
rows_per = MIN(rows_per, rows_max);
rows_per = MIN(rows_per, (rows_total + 7) & ~7);
+ if (rows_ovr > 0) rows_per = MIN(MIN(rows_ovr, rows_max), (rows_total + 7) & ~7);
+ else if (policy && (K == 4 || K == 5))
+ {
+ // Taller slices than the single-wave rule picks: units well below the grid but >= ~2 per SM keep DRAM
+ // saturated while the per-slice prologue, partial traffic and serial epilogue combine shrink
+ // (3090 sweep: 5120x17408 K4 72 -> 63 us, K5 88 -> 76 us; flat for shapes already near 2 units/SM)
+ int ks_t = MAX(1, CEIL_DIVIDE(2 * num_sms, nb256));
+ int rp_new = (CEIL_DIVIDE(rows_total, ks_t) + 7) & ~7;
+ rp_new = MIN(rp_new, rows_max);
+ rp_new = MIN(rp_new, (rows_total + 7) & ~7);
+ rows_per = MAX(rows_per, rp_new);
+ }
ksplit = CEIL_DIVIDE(rows_total, rows_per);
};
auto smem_for = [&] (int rows_per) -> size_t
@@ -221,6 +235,7 @@ static bool exl3_gemv_int8_sq
}
#endif
decomp(grid, ksplit, rows_per);
+ int rows_eff = rows_per; // the kernel takes the host's slice height (single source of truth)
size_t smem = smem_for(rows_per);
if (ksplit > SQ_KSPLIT_CAP) return false;
if (size_n / 256 > SQ_COUNTERS_CAP) return false;
@@ -240,7 +255,8 @@ static bool exl3_gemv_int8_sq
(void*) &ws_ptr,
(void*) &suh_ptr,
(void*) &A_had_ptr,
- (void*) &svh_ptr
+ (void*) &svh_ptr,
+ (void*) &rows_eff
};
cudaError_t err = cudaLaunchKernel(fn, dim3(grid), dim3(NUM_THREADS), kernelArgs, smem, stream);
diff --git a/exllamav3/exllamav3_ext/quant/exl3_gemv_int8_kernel.cuh b/exllamav3/exllamav3_ext/quant/exl3_gemv_int8_kernel.cuh
index ca401f1..9a8fc7a 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_gemv_int8_kernel.cuh
+++ b/exllamav3/exllamav3_ext/quant/exl3_gemv_int8_kernel.cuh
@@ -1031,7 +1031,8 @@ void exl3_gemv_int8_sq_kernel
int* __restrict__ locks,
const half* __restrict__ suh,
half* __restrict__ A_had,
- const half* __restrict__ svh
+ const half* __restrict__ svh,
+ const int rows_ovr // 0 = automatic slice height, else forced (multiple of 8)
)
{
extern __shared__ uint32_t shmem[];
@@ -1048,6 +1049,7 @@ void exl3_gemv_int8_sq_kernel
rows_per = MAX(rows_per, SQ_MINROWS);
rows_per = MIN(rows_per, gemv_int8_sq_rows_max(M, residual));
rows_per = MIN(rows_per, (rows_total + 7) & ~7);
+ if (rows_ovr > 0) rows_per = MIN(rows_ovr, (rows_total + 7) & ~7);
int ksplit = CEIL_DIVIDE(rows_total, rows_per);
int units = nb256_total * ksplit;
int slice_stride = rows_per * 16;
diff --git a/exllamav3/exllamav3_ext/quant/exl3_gemv_kernel.cuh b/exllamav3/exllamav3_ext/quant/exl3_gemv_kernel.cuh
index a6727f2..a03247b 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_gemv_kernel.cuh
+++ b/exllamav3/exllamav3_ext/quant/exl3_gemv_kernel.cuh
@@ -373,6 +373,25 @@ void exl3_gemv_kernel(EXL3_GEMM_ARGS)
for (int group = blockIdx.x; group < num_groups; group += gridDim.x)
{
const uint32_t* bp = B32 + (size_t) ks0 * slice_stride + group * WNT * TWORDS + lane;
+#if !defined(USE_ROCM) && !defined(__HIPCC__) && !defined(EXL3_HIP_A_RING)
+ // Running pointers instead of per-slice 64-bit index math (same addresses, same loads):
+ // bq = next B slice row to prefetch, aq0 / aq1 = A fragment rows of the slice being consumed
+ const uint32_t* bq = bp;
+ // m = 1: every lane reads row 0 (rows 1..7 of the A fragment become copies of row 0; their C rows are never stored,
+ // HMMA rows are independent, so row 0 is unchanged and no select / predicate is needed)
+ const half2* aq0 = A2 + (MMODE == 0 ? 0 : a_row0) + (size_t) ks0 * 8 + (lane & 3);
+ const half2* aq1 = A2 + a_row1 + (size_t) ks0 * 8 + (lane & 3);
+ auto ld_bq = [&] (int l) -> uint32_t
+ {
+ if constexpr (bits == 3)
+ return lane < 24 ? __ldcs(bq + l * LSTRIDE) : 0;
+ else
+ return __ldcs(bq + l * LSTRIDE);
+ };
+ #define EXL3_GEMV_RUNPTR 1
+#else
+ #define EXL3_GEMV_RUNPTR 0
+#endif
// Prefetch ring (indices must be compile-time or pf lands in local memory)
auto ld_b = [&] (int i, int l) -> uint32_t
@@ -395,9 +414,18 @@ void exl3_gemv_kernel(EXL3_GEMM_ARGS)
#pragma unroll
for (int d = 0; d < PF; ++d)
if (d < myn)
+ {
+#if EXL3_GEMV_RUNPTR
+ #pragma unroll
+ for (int l = 0; l < LOADS; ++l)
+ pf[d][l] = ld_bq(l);
+ bq += slice_stride;
+#else
#pragma unroll
for (int l = 0; l < LOADS; ++l)
pf[d][l] = ld_b(d, l);
+#endif
+ }
#if defined(EXL3_HIP_A_RING)
// A fragment prefetch ring, same depth as B. Without it every k-slice issues its A loads
@@ -448,9 +476,16 @@ void exl3_gemv_kernel(EXL3_GEMM_ARGS)
#if !defined(EXL3_HIP_PF_AFTER_STAGE)
if (i + PF < myn)
{
+#if EXL3_GEMV_RUNPTR
+ #pragma unroll
+ for (int l = 0; l < LOADS; ++l)
+ pf[d][l] = ld_bq(l);
+ bq += slice_stride;
+#else
#pragma unroll
for (int l = 0; l < LOADS; ++l)
pf[d][l] = ld_b(i + PF, l);
+#endif
#if defined(EXL3_HIP_A_RING)
ld_a(i + PF, pa01[d], pa23[d]);
#endif
@@ -497,13 +532,29 @@ void exl3_gemv_kernel(EXL3_GEMM_ARGS)
#if !defined(EXL3_HIP_A_RING)
// A fragment: lane covers row lane/4, k pairs (2(lane%4), +1) and (+8, +9)
- const size_t a_col = (size_t) (ks0 + i) * 8 + (lane & 3);
FragB a01, a23;
+#if EXL3_GEMV_RUNPTR
+ if constexpr (MMODE == 0)
+ {
+ a01[0] = __ldg(aq0);
+ a23[0] = __ldg(aq0 + 4);
+ }
+ else
+ {
+ a01[0] = r0_ok ? aq0[0] : hzero;
+ a23[0] = r0_ok ? aq0[4] : hzero;
+ }
+ a01[1] = r1_ok ? aq1[0] : hzero;
+ a23[1] = r1_ok ? aq1[4] : hzero;
+ aq0 += 8; aq1 += 8;
+#else
+ const size_t a_col = (size_t) (ks0 + i) * 8 + (lane & 3);
a01[0] = r0_ok ? A2[a_row0 + a_col] : hzero;
a23[0] = r0_ok ? A2[a_row0 + a_col + 4] : hzero;
a01[1] = r1_ok ? A2[a_row1 + a_col] : hzero;
a23[1] = r1_ok ? A2[a_row1 + a_col + 4] : hzero;
#endif
+#endif
#if defined(EXL3_HIP_WMMA_GFX12)
// Every adjacent N tile uses the same A rows for this K slice. Assemble the full
@@ -600,6 +651,7 @@ void exl3_gemv_kernel(EXL3_GEMM_ARGS)
}
}
+ #undef EXL3_GEMV_RUNPTR
#if defined(USE_ROCM) || defined(__HIPCC__)
// Cross-warp reduction over the k splits, HIP C-fragment layout (oracle-verified):
// C(lane, reg) = C[row = (lane>>4)*8 + reg][col = lane & 15]
diff --git a/exllamav3/exllamav3_ext/quant/exl3_kernel_map.cu b/exllamav3/exllamav3_ext/quant/exl3_kernel_map.cu
index c191271..4e3cc11 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_kernel_map.cu
+++ b/exllamav3/exllamav3_ext/quant/exl3_kernel_map.cu
@@ -79,6 +79,7 @@ int exl3_gemm_num_kernel_shapes()
return EXL3_GEMM_NUM_SHAPES;
}
+int exl3_gemm_tilesize_m[] = {EXL3_GEMM_TILESIZE_M};
int exl3_gemm_tilesize_k[] = {EXL3_GEMM_TILESIZE_K};
int exl3_gemm_tilesize_n[] = {EXL3_GEMM_TILESIZE_N};
int exl3_gemm_blockdim[] = {EXL3_GEMM_BLOCKDIM};
@@ -87,6 +88,8 @@ bool exl3_gemm_shape_compat(int shape_idx, int size_m, int size_k, int size_n, i
{
int tilesize_k = exl3_gemm_tilesize_k[shape_idx];
int tilesize_n = exl3_gemm_tilesize_n[shape_idx];
+ // A wider row tile only pays once it replaces at least two 16-row passes
+ if (exl3_gemm_tilesize_m[shape_idx] > 16 && size_m <= exl3_gemm_tilesize_m[shape_idx] / 2) return false;
return (size_k % tilesize_k == 0) && (size_n % tilesize_n == 0);
}
diff --git a/exllamav3/exllamav3_ext/quant/exl3_kernel_map.cuh b/exllamav3/exllamav3_ext/quant/exl3_kernel_map.cuh
index 58cde38..5bbec5b 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_kernel_map.cuh
+++ b/exllamav3/exllamav3_ext/quant/exl3_kernel_map.cuh
@@ -57,12 +57,19 @@ typedef void (*fp_exl3_mgemm_kernel) (EXL3_MGEMM_ARGS);
#define EXL3_GEMM_SHAPE_2 16, 32, 128, 4, 3
#define EXL3_GEMM_SHAPE_3 16, 32, 256, 4, 3
#define EXL3_GEMM_SHAPE_4 16, 16, 512, 4, 3
+// Multi-row tile: all 32 rows share each decoded B fragment, where the 16-row shapes decode the whole
+// weight matrix again for every 16 rows (17..144-row calls: batched decode, wide verify, short prefill chunks).
+// N = 256 as shape 3, the best 16-row tile on GA102: at equal grid it is bitwise equal to shape 3 (same k-slicing,
+// same fp16 accumulation span); the N = 128 multi-row tiles of upstream 1.6.0 double each block's fp16 span
+// (2x KLD at 120 rows) and are left out. The CUDA inner implements TILESIZE_M > 16; ROCm builds none of this
+#define EXL3_GEMM_SHAPE_5 32, 32, 256, 4, 3
-#define EXL3_GEMM_TILESIZE_K 0, 16, 32, 32, 16
-#define EXL3_GEMM_TILESIZE_N 0, 128, 128, 256, 512
-#define EXL3_GEMM_BLOCKDIM 0, 256, 512, 512, 256
+#define EXL3_GEMM_TILESIZE_M 0, 16, 16, 16, 16, 32
+#define EXL3_GEMM_TILESIZE_K 0, 16, 32, 32, 16, 32
+#define EXL3_GEMM_TILESIZE_N 0, 128, 128, 256, 512, 256
+#define EXL3_GEMM_BLOCKDIM 0, 256, 512, 512, 256, 512
-#define EXL3_GEMM_NUM_SHAPES 4
+#define EXL3_GEMM_NUM_SHAPES 5
// Shape 1 not currently used anywhere
#define EXL3_GEMM_KERNEL_INSTANCES(_bits, _c_fp32, cb) \
@@ -70,14 +77,16 @@ typedef void (*fp_exl3_mgemm_kernel) (EXL3_MGEMM_ARGS);
exl3_gemm_kernel<_bits, _c_fp32, cb, EXL3_GEMM_SHAPE_1>, \
exl3_gemm_kernel<_bits, _c_fp32, cb, EXL3_GEMM_SHAPE_2>, \
exl3_gemm_kernel<_bits, _c_fp32, cb, EXL3_GEMM_SHAPE_3>, \
- exl3_gemm_kernel<_bits, _c_fp32, cb, EXL3_GEMM_SHAPE_4>
+ exl3_gemm_kernel<_bits, _c_fp32, cb, EXL3_GEMM_SHAPE_4>, \
+ exl3_gemm_kernel<_bits, _c_fp32, cb, EXL3_GEMM_SHAPE_5>
#define EXL3_MGEMM_KERNEL_INSTANCES(_bits, _c_fp32, cb) \
nullptr, \
exl3_mgemm_kernel<_bits, _c_fp32, cb, EXL3_GEMM_SHAPE_1>, \
exl3_mgemm_kernel<_bits, _c_fp32, cb, EXL3_GEMM_SHAPE_2>, \
exl3_mgemm_kernel<_bits, _c_fp32, cb, EXL3_GEMM_SHAPE_3>, \
- exl3_mgemm_kernel<_bits, _c_fp32, cb, EXL3_GEMM_SHAPE_4>
+ exl3_mgemm_kernel<_bits, _c_fp32, cb, EXL3_GEMM_SHAPE_4>, \
+ exl3_mgemm_kernel<_bits, _c_fp32, cb, EXL3_GEMM_SHAPE_5>
#define EXL3_GEMM_BASE_THREADS 256
diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe.cu b/exllamav3/exllamav3_ext/quant/exl3_moe.cu
index 1ce680f..f2d6193 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_moe.cu
+++ b/exllamav3/exllamav3_ext/quant/exl3_moe.cu
@@ -34,16 +34,17 @@ static int moe_tile_n_override()
fp_exl3_moe_kernel exl3_moe_kernel_instances[] =
{
- // [K][cb - 1][N_off]: K = 0 switches Kg/Ku/Kd at runtime, K > 0 = compile-time Kg = Ku = Kd
- exl3_moe_kernel_k0_n128_cb1(), exl3_moe_kernel_k0_n256_cb1(), exl3_moe_kernel_k0_n128_cb2(), exl3_moe_kernel_k0_n256_cb2(),
- exl3_moe_kernel_k1_n128_cb1(), exl3_moe_kernel_k1_n256_cb1(), exl3_moe_kernel_k1_n128_cb2(), exl3_moe_kernel_k1_n256_cb2(),
- exl3_moe_kernel_k2_n128_cb1(), exl3_moe_kernel_k2_n256_cb1(), exl3_moe_kernel_k2_n128_cb2(), exl3_moe_kernel_k2_n256_cb2(),
- exl3_moe_kernel_k3_n128_cb1(), exl3_moe_kernel_k3_n256_cb1(), exl3_moe_kernel_k3_n128_cb2(), exl3_moe_kernel_k3_n256_cb2(),
- exl3_moe_kernel_k4_n128_cb1(), exl3_moe_kernel_k4_n256_cb1(), exl3_moe_kernel_k4_n128_cb2(), exl3_moe_kernel_k4_n256_cb2(),
- exl3_moe_kernel_k5_n128_cb1(), exl3_moe_kernel_k5_n256_cb1(), exl3_moe_kernel_k5_n128_cb2(), exl3_moe_kernel_k5_n256_cb2(),
- exl3_moe_kernel_k6_n128_cb1(), exl3_moe_kernel_k6_n256_cb1(), exl3_moe_kernel_k6_n128_cb2(), exl3_moe_kernel_k6_n256_cb2(),
- exl3_moe_kernel_k7_n128_cb1(), exl3_moe_kernel_k7_n256_cb1(), exl3_moe_kernel_k7_n128_cb2(), exl3_moe_kernel_k7_n256_cb2(),
- exl3_moe_kernel_k8_n128_cb1(), exl3_moe_kernel_k8_n256_cb1(), exl3_moe_kernel_k8_n128_cb2(), exl3_moe_kernel_k8_n256_cb2()
+ // [K][cb][N_off]: K = 0 switches Kg/Ku/Kd at runtime, K > 0 = compile-time Kg = Ku = Kd;
+ // cb 0 = 3INST, 1 = mcg, 2 = mul1 (the codebook template argument of exl3_gemm_kernel_inner)
+ exl3_moe_kernel_k0_n128_cb0(), exl3_moe_kernel_k0_n256_cb0(), exl3_moe_kernel_k0_n128_cb1(), exl3_moe_kernel_k0_n256_cb1(), exl3_moe_kernel_k0_n128_cb2(), exl3_moe_kernel_k0_n256_cb2(),
+ exl3_moe_kernel_k1_n128_cb0(), exl3_moe_kernel_k1_n256_cb0(), exl3_moe_kernel_k1_n128_cb1(), exl3_moe_kernel_k1_n256_cb1(), exl3_moe_kernel_k1_n128_cb2(), exl3_moe_kernel_k1_n256_cb2(),
+ exl3_moe_kernel_k2_n128_cb0(), exl3_moe_kernel_k2_n256_cb0(), exl3_moe_kernel_k2_n128_cb1(), exl3_moe_kernel_k2_n256_cb1(), exl3_moe_kernel_k2_n128_cb2(), exl3_moe_kernel_k2_n256_cb2(),
+ exl3_moe_kernel_k3_n128_cb0(), exl3_moe_kernel_k3_n256_cb0(), exl3_moe_kernel_k3_n128_cb1(), exl3_moe_kernel_k3_n256_cb1(), exl3_moe_kernel_k3_n128_cb2(), exl3_moe_kernel_k3_n256_cb2(),
+ exl3_moe_kernel_k4_n128_cb0(), exl3_moe_kernel_k4_n256_cb0(), exl3_moe_kernel_k4_n128_cb1(), exl3_moe_kernel_k4_n256_cb1(), exl3_moe_kernel_k4_n128_cb2(), exl3_moe_kernel_k4_n256_cb2(),
+ exl3_moe_kernel_k5_n128_cb0(), exl3_moe_kernel_k5_n256_cb0(), exl3_moe_kernel_k5_n128_cb1(), exl3_moe_kernel_k5_n256_cb1(), exl3_moe_kernel_k5_n128_cb2(), exl3_moe_kernel_k5_n256_cb2(),
+ exl3_moe_kernel_k6_n128_cb0(), exl3_moe_kernel_k6_n256_cb0(), exl3_moe_kernel_k6_n128_cb1(), exl3_moe_kernel_k6_n256_cb1(), exl3_moe_kernel_k6_n128_cb2(), exl3_moe_kernel_k6_n256_cb2(),
+ exl3_moe_kernel_k7_n128_cb0(), exl3_moe_kernel_k7_n256_cb0(), exl3_moe_kernel_k7_n128_cb1(), exl3_moe_kernel_k7_n256_cb1(), exl3_moe_kernel_k7_n128_cb2(), exl3_moe_kernel_k7_n256_cb2(),
+ exl3_moe_kernel_k8_n128_cb0(), exl3_moe_kernel_k8_n256_cb0(), exl3_moe_kernel_k8_n128_cb1(), exl3_moe_kernel_k8_n256_cb1(), exl3_moe_kernel_k8_n128_cb2(), exl3_moe_kernel_k8_n256_cb2()
};
// 32-row tile instances, [K], N = 128 shape, mul1 codebook only
@@ -235,8 +236,8 @@ void exl3_moe
// TORCH_CHECK(!(down_mcg && down_mul1), "Specified both mcg and mul1 (down)");
TORCH_CHECK(gate_mcg == up_mcg && up_mcg == down_mcg && gate_mul1 == up_mul1 && up_mul1 == down_mul1,
"MoE kernel: gate/up/down must share the same codebook");
- TORCH_CHECK(gate_mcg != gate_mul1, "MoE kernel: Only mcg and mul1 codebooks are supported");
- const int cb_idx = gate_mul1 ? 1 : 0;
+ TORCH_CHECK(!(gate_mcg && gate_mul1), "MoE kernel: Specified both mcg and mul1");
+ const int cb_idx = gate_mul1 ? 2 : (gate_mcg ? 1 : 0);
// TORCH_CHECK(act_function == MOE_ACT_SILU, "MoE kernel: Only SiLU is currently supported");
@@ -280,7 +281,7 @@ void exl3_moe
fp_exl3_moe_kernel kernel;
if (m_tile <= 16)
{
- kernel = exl3_moe_kernel_instances[4 * K + 2 * cb_idx + N_off];
+ kernel = exl3_moe_kernel_instances[6 * K + 2 * cb_idx + N_off];
}
else
{
@@ -288,7 +289,7 @@ void exl3_moe
// multiples of 128: for dims that are multiples of 256 they still beat the N = 256
// 16-row tiling by ~20% at 24+ rows per expert (the N = 256 instance stays the faster
// one for the <= 16-row launch, which the caller issues with m_tile 16)
- TORCH_CHECK(cb_idx == 1, "exl3_moe: row tiles above 16 are instantiated for the mul1 codebook only");
+ TORCH_CHECK(cb_idx == 2, "exl3_moe: row tiles above 16 are instantiated for the mul1 codebook only");
TORCH_CHECK(max_tokens_per_expert >= (size_t) m_tile, "exl3_moe: temp buffers hold fewer rows than the tile");
kernel = m_tile >= 64 ? exl3_moe_kernel_instances_m64[K] : exl3_moe_kernel_instances_m32[K];
}
diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_coop.cu b/exllamav3/exllamav3_ext/quant/exl3_moe_coop.cu
index 505355e..ed61a3f 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_moe_coop.cu
+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_coop.cu
@@ -6,6 +6,8 @@
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <map>
+#include <tuple>
+#include <utility>
#include <cmath>
#include "../util.h"
@@ -59,6 +61,42 @@ static int moe_coop_pick_ksplit(int max_split)
return forced > 0 ? std::min(forced, max_split) : 1;
}
+// Stream-K for the gate/up stage (exl3_moe_coop_kernel.cuh, SkGeom), grid = resident blocks x SMs:
+// EXL3_MOE_COOP_SK = 0 off, 1 hybrid (whole units on SMs blocks, the remainder shared; CUDA default),
+// 2 pure stream-K. The down stage's short units gain nothing from it. Not measured on
+// ROCm: off there unless set
+static int moe_coop_sk_mode()
+{
+ static int mode = -2;
+ if (mode == -2)
+ {
+ const char* env = std::getenv("EXL3_MOE_COOP_SK");
+#ifdef USE_ROCM
+ mode = env ? atoi(env) : 0;
+#else
+ mode = env ? atoi(env) : 1;
+#endif
+ }
+ return mode;
+}
+
+// Grid (resident blocks x SMs) and SM count, per (kernel, smem, device), queried once
+static int moe_coop_sk_grid(const MoeCoopKernel& k, int device, int& sms)
+{
+ static std::map<std::tuple<void*, int, int>, std::pair<int, int>> grid;
+ const auto key = std::make_tuple(k.kernel, k.smem, device);
+ auto it = grid.find(key);
+ if (it == grid.end())
+ {
+ int per_sm = 0, n = 0;
+ cuda_check(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm, k.kernel, MOE_COOP_THREADS, k.smem));
+ cuda_check(cudaDeviceGetAttribute(&n, cudaDevAttrMultiProcessorCount, device));
+ it = grid.emplace(key, std::make_pair(std::max(1, per_sm) * n, n)).first;
+ }
+ sms = it->second.second;
+ return it->second.first;
+}
+
// Tile geometry per stage: the wide (128-column, 4-way k-split) tile for long k, the narrow one
// otherwise. EXL3_MOE_COOP_WIDE = 0 / 1 forces one geometry for every stage (testing)
static int moe_coop_wide_mode()
@@ -111,8 +149,18 @@ void exl3_moe_coop_launch(const MoeCoopParams& p_in, int K_gu, int K_d, int cb,
const int max_split = std::max(1, p.slots_max / slots);
p.ksplit_a = moe_coop_pick_ksplit(max_split);
p.ksplit_b = moe_coop_pick_ksplit(max_split);
- const int grid_a = base_a * p.ksplit_a;
+ int grid_a = base_a * p.ksplit_a;
const int grid_b = base_b * p.ksplit_b;
+ // Stream-K gate/up stage (wide tile; bsz <= 2 at MAX_BSZN 8, i.e. max_split >= 4: slower at 4
+ // rows; room for >= 2 fp32 partial rows per projection in d_out): ksplit = -(whole-unit blocks + 1).
+ // The hybrid needs a second resident block per SM for the shared remainder, else pure stream-K
+ const int sk = moe_coop_sk_mode();
+ if (sk > 0 && wide_a && max_split >= 4 && exl3_moe_coop_ns::sk_rows(p.slots_max, slots, nproj, p.I, p.Ho) >= 2)
+ {
+ int sms;
+ grid_a = moe_coop_sk_grid(ka, device, sms);
+ p.ksplit_a = -((sk == 2 || grid_a <= sms ? 0 : sms) + 1);
+ }
void* args[] = { (void*) &p };
if (p.a_global)
diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_coop.cuh b/exllamav3/exllamav3_ext/quant/exl3_moe_coop.cuh
index 69e5856..1ef66ec 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_moe_coop.cuh
+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_coop.cuh
@@ -59,7 +59,8 @@ struct MoeCoopParams
int* ctr_b; // (MAX_BSZN, Ho / 128) completion counters of the down stage
int ctr_a_len;
int ctr_b_len;
- int ksplit_a; // split-k blocks per chunk per stage (launcher; partial rows at slot + q * slots)
+ int ksplit_a; // split-k blocks per chunk per stage (launcher; partial rows at slot + q * slots);
+ // -G: stream-K over a grid of G blocks
int ksplit_b;
int dbg; // diagnostics (EXL3_MOE_COOP_DBG): 1 skip A epilogue, 2 skip B reduction
int* runs; // run table (bsz > 1): [n_runs, -, run_start[slots_max + 1], order[slots_max]]
diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_coop_kernel.cuh b/exllamav3/exllamav3_ext/quant/exl3_moe_coop_kernel.cuh
index ae4dd19..09c0f14 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_moe_coop_kernel.cuh
+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_coop_kernel.cuh
@@ -20,6 +20,7 @@
//
// The grid is sized for the no-duplicates case (slots x groups x projections); blocks past the
// actual run count exit at once.
+// Stream-K (gate/up stage, ksplit < 0, SkGeom below): a fixed grid shares the (unit, k-slice) work evenly.
#include <cuda_fp16.h>
#include "../util.h"
@@ -542,21 +543,108 @@ __device__ __forceinline__ void gemv_tile
__syncthreads();
}
-// Completion counter: every thread fences its own stores, then one thread arrives. Returns true
-// (block-uniform) for the last arriving block, which may then read the other blocks' results
-// through L2 (load_*_cg)
-__device__ __forceinline__ bool arrive_last(int* counter, int expected, int* sh_flag)
+// Completion counter: every thread fences its own stores, then one thread arrives (adding a
+// positive weight). Returns true (block-uniform) for the last arriving block, which may then read
+// the other blocks' results through L2 (load_*_cg)
+__device__ __forceinline__ bool arrive_last(int* counter, int expected, int* sh_flag, int add = 1)
{
__threadfence();
__syncthreads();
if (threadIdx.x == 0)
- *sh_flag = (atomicAdd(counter, 1) == expected - 1);
+ *sh_flag = (atomicAdd(counter, add) == expected - add);
__syncthreads();
bool last = *sh_flag;
if (last) __threadfence();
return last;
}
+// ---------------------------------------------------------------------------------------------
+// Stream-K hybrid, kernel A (launcher ksplit_a = -(S + 1), grid = resident blocks x SMs): the per-unit grid
+// leaves most SMs with half the work of the busiest at bsz 1 (96..128 units on 82 SMs, 2 resident).
+// Blocks [0, S) (S = SMs) take whole units b, b + S, ... below D = U - U % S, one segment each;
+// blocks [S, grid) share the k-slices of the R = U - D remaining units in equal contiguous shares.
+// U <= S: whole units only. S = 0: every unit shared (pure stream-K). A shared unit's k-range spans
+// n_seg blocks; segment q (= block - the unit's first block) writes an fp32 partial row (sk_rows) and
+// the last arrival sums them in q order (a whole unit writes its gu row as on the per-unit grid). Arrivals are weighted (segment 0 adds SK_C - n_seg + 1, the
+// others 1) so the expected count is SK_C per unit whatever the split. WIDE geometry only
+
+constexpr int SK_C = 1 << 16;
+
+struct SkGeom
+{
+ int G; // blocks sharing the remainder (0: per-unit grid)
+ int KS; // k-slices per unit
+ long long T; // R * KS
+ int S; // whole-unit blocks = first sharing block
+ int D; // first shared unit
+ // Sharing block (relative) owning slice s: the largest b with floor(b * T / G) <= s
+ __device__ __forceinline__ int owner(long long s) const { return (int) (((s + 1) * G - 1) / T); }
+ __device__ __forceinline__ int first(int u) const { return owner((long long) u * KS); }
+ __device__ __forceinline__ int nseg(int u) const { return owner((long long) (u + 1) * KS - 1) - first(u) + 1; }
+ __device__ __forceinline__ long long start(int b) const { return (long long) b * T / G; }
+ // Segments of unit u (absolute)
+ __device__ __forceinline__ int nseg_u(int u) const { return u < D ? 1 : nseg(u - D); }
+};
+
+// Partial rows per projection for the shared units: their k-segment partials are kept in fp32 in
+// the down stage's d_out scratch (idle until kernel B runs), laid out [projection][q][slot][I]
+__host__ __device__ inline int sk_rows(int slots_max, int slots, int nproj, int I, int Ho)
+{
+ return (int) (((long long) slots_max * Ho) / ((long long) nproj * slots * I));
+}
+
+// Shares of at least pmin slices keep n_seg <= sk_rows (launched only with sk_rows >= 2), and >= 4
+// slices per share (one per k-warp)
+__device__ __forceinline__ SkGeom sk_geom(const MoeCoopParams& p, int S, int grid, int U, int KS)
+{
+ SkGeom g;
+ g.S = S;
+ g.D = S == 0 ? 0 : (U <= S ? U : U - U % S);
+ g.KS = KS;
+ g.T = (long long) (U - g.D) * KS;
+ const int nq = sk_rows(p.slots_max, p.bsz * p.topk, p.gated ? 2 : 1, p.I, p.Ho);
+ const int pmin = max(4, CEIL_DIVIDE(KS, nq - 1));
+ g.G = (int) max(1LL, min((long long) (grid - S), g.T / pmin));
+ return g;
+}
+
+// The block's current unit segment, written by thread 0 of the driver into shared memory and read
+// by every thread; read again after the GEMV so that none of it stays live across the main loop
+enum
+{
+ SEG_RUN, SEG_GROUP, SEG_PROJ, SEG_K0, SEG_K1, SEG_Q, // unit, k-slice range (K0 < 0: done), partial row
+ SEG_ADD, SEG_EXP, SEG_NPG, SEG_NPU, // arrival weight / expected sum, partial rows to sum
+ SEG_NEXT, // stream-K: next unit / slice of the block (-1: first)
+ SEG_N
+};
+
+// Stream-K: the block's next unit and k-range [k0, k1), its partial row q and segment count;
+// false when the block is done. prev: SEG_NEXT (-1 first, else the unit / slice after the last)
+__device__ __forceinline__ bool sk_next(const SkGeom& g, int prev, int& u, int& k0, int& k1, int& q, int& ns, int& next)
+{
+ if ((int) blockIdx.x < g.S)
+ {
+ u = prev < 0 ? (int) blockIdx.x : prev;
+ if (u >= g.D) return false;
+ k0 = 0; k1 = g.KS; q = 0; ns = 1;
+ next = u + g.S;
+ return true;
+ }
+ const int b = blockIdx.x - g.S;
+ const long long end = b < g.G ? g.start(b + 1) : 0;
+ const long long x = prev < 0 ? g.start(min(b, g.G)) : prev;
+ if (x >= end) return false;
+ const int ur = (int) (x / g.KS);
+ const long long u_end = (long long) (ur + 1) * g.KS;
+ u = g.D + ur;
+ k0 = (int) (x - (long long) ur * g.KS);
+ k1 = (int) (min(u_end, end) - (long long) ur * g.KS);
+ q = b - g.first(ur);
+ ns = g.nseg(ur);
+ next = (int) u_end;
+ return true;
+}
+
// Number of active slots of a token
__device__ __forceinline__ int token_active_slots(const MoeCoopParams& p, int row)
{
@@ -672,90 +760,137 @@ __global__ void exl3_moe_coop_rot_kernel(const MoeCoopParams p);
// Kernel A: gate/up GEMV per (expert run, group, projection) with the chunk epilogue (rotation,
// bias, activation, down-input rotation) by the last arrival per (slot, chunk)
+// Thread 0: the block's next segment into seg[] (one per block on the per-unit grid; the shares of
+// stream-K, unit u = (run * ng + group) * nproj + projection)
+template <bool WIDE>
+__device__ __forceinline__ void a_next_seg(const MoeCoopParams& p, int* seg)
+{
+ const int nproj = p.gated ? 2 : 1;
+ const int ng = p.I / tile_cols<WIDE>();
+ const int KS = p.Hi / 16;
+ const int prev = seg[SEG_NEXT];
+ if (p.ksplit_a > 0)
+ {
+ if (prev >= 0) { seg[SEG_K0] = -1; return; }
+ const int item = blockIdx.x;
+ const int rem = item / nproj;
+ const int ks = rem % p.ksplit_a; // split-k index: partial output rows
+ const int rem2 = rem / p.ksplit_a;
+ seg[SEG_RUN] = rem2 / ng;
+ seg[SEG_GROUP] = rem2 % ng;
+ seg[SEG_PROJ] = item % nproj;
+ seg[SEG_K0] = KS * ks / p.ksplit_a;
+ seg[SEG_K1] = KS * (ks + 1) / p.ksplit_a;
+ seg[SEG_Q] = ks;
+ seg[SEG_ADD] = 1;
+ seg[SEG_EXP] = tile_gpc<WIDE>() * nproj * p.ksplit_a;
+ seg[SEG_NPG] = p.ksplit_a;
+ seg[SEG_NPU] = p.ksplit_a;
+ seg[SEG_NEXT] = 0;
+ return;
+ }
+ const int n_runs = p.a_global ? p.runs[0] : p.bsz * p.topk;
+ const SkGeom g = sk_geom(p, -p.ksplit_a - 1, gridDim.x, n_runs * ng * nproj, KS);
+ int u, k0, k1, q, ns, next;
+ if (!sk_next(g, prev, u, k0, k1, q, ns, next)) { seg[SEG_K0] = -1; return; }
+ const int proj = u % nproj;
+ seg[SEG_RUN] = u / nproj / ng;
+ seg[SEG_GROUP] = (u / nproj) % ng;
+ seg[SEG_PROJ] = proj;
+ seg[SEG_K0] = k0;
+ seg[SEG_K1] = k1;
+ seg[SEG_Q] = q;
+ seg[SEG_ADD] = q == 0 ? SK_C - (ns - 1) : 1;
+ seg[SEG_EXP] = nproj * SK_C;
+ seg[SEG_NPG] = p.gated ? g.nseg_u(u - proj) : 0;
+ seg[SEG_NPU] = g.nseg_u(u - proj + nproj - 1);
+ seg[SEG_NEXT] = next;
+}
+
+// One segment: a unit's k-range into partial rows q, arrivals, chunk epilogue of the last arrival
template <int bits, int cb, bool WIDE>
-__global__ __launch_bounds__(THREADS)
-void exl3_moe_coop_a_kernel(const MoeCoopParams p)
+__device__ __forceinline__ void a_unit
+(
+ const MoeCoopParams& p, const int* seg,
+ half* sh_A, float* sh_red, uint32_t* sh_stage, int* sh_flag, int* sh_res, int* sh_rows
+)
{
- constexpr int TCOLS = tile_cols<WIDE>();
constexpr int GPC = tile_gpc<WIDE>();
constexpr int CPB = tile_cpb<WIDE>();
- extern __shared__ uint32_t smem_dyn[];
- half* sh_A = (half*) smem_dyn;
- float* sh_red = (float*) (smem_dyn + p.Hi / 2);
- uint32_t* sh_stage = smem_dyn + p.Hi / 2 + WK * ROWS * COLS;
- __shared__ int sh_flag;
- __shared__ int sh_res[4];
- __shared__ int sh_rows[ROWS];
-
const int warp = threadIdx.x / 32;
const int lane = threadIdx.x % 32;
- const int nproj = p.gated ? 2 : 1;
- const int ng = p.I / TCOLS;
+ const int ng = p.I / tile_cols<WIDE>();
- // Reset the down stage's counters for this call (its previous use finished in stream order)
- for (int i = blockIdx.x * THREADS + threadIdx.x; i < p.ctr_b_len; i += gridDim.x * THREADS)
- p.ctr_b[i] = 0;
-
- const int item = blockIdx.x;
- const bool is_gate = p.gated && (item % nproj) == 0;
- const int rem = item / nproj;
- const int ks = rem % p.ksplit_a; // split-k index: partial output rows
- const int rem2 = rem / p.ksplit_a;
- const int run_idx = rem2 / ng;
- const int group = rem2 % ng;
+ const bool is_gate = p.gated && seg[SEG_PROJ] == 0;
+ const int run_idx = seg[SEG_RUN];
int nrows = 0;
if (!read_run(p, run_idx, sh_rows, nrows, sh_res))
{
// bsz 1: an inactive slot's blocks (up projection, split 0) write the output chunks of an
// empty token row, one warp per chunk, strided by the number of gate/up groups
- if (!p.a_global && run_idx < p.bsz * p.topk && !is_gate && ks == 0 && run_idx % p.topk == 0)
+ if (!p.a_global && run_idx < p.bsz * p.topk && !is_gate && seg[SEG_Q] == 0 && run_idx % p.topk == 0)
{
const int row = run_idx / p.topk;
if (token_active_slots(p, row) == 0)
- for (int oc = group + warp * ng; oc < p.Ho / 128; oc += ng * WK)
+ for (int oc = seg[SEG_GROUP] + warp * ng; oc < p.Ho / 128; oc += ng * WK)
write_empty_row_chunk(p, row, oc, lane);
}
return;
}
- const int local = slot_info(p, sh_rows[0]).local;
- const int kslices_all = p.Hi / 16;
- const int k_begin = kslices_all * ks / p.ksplit_a;
- const int k_end = kslices_all * (ks + 1) / p.ksplit_a;
-
- const half* suh = (const half*) (is_gate ? p.g_suh : p.u_suh)[local];
- const half2* A2;
- size_t a_stride2;
- if (p.a_global)
- {
- A2 = (const half2*) (is_gate ? p.had_g : p.had_u);
- a_stride2 = (size_t) p.Hi / 2;
- }
- else
- {
- // bsz 1: every run is a single slot; rotate its input into shared memory here. A zero
- // row stride makes the tile read it whatever the slot index (which still selects the C row)
- const SlotInfo si = slot_info(p, sh_rows[0]);
- for (int c = warp; c < p.Hi / 128; c += WK)
- rotate_chunk(p, si.row, suh, c, sh_A, lane);
- __syncthreads();
- A2 = (const half2*) sh_A;
- a_stride2 = 0;
- }
{
+ const int local = slot_info(p, sh_rows[0]).local;
+ const int k_begin = seg[SEG_K0];
+ const int k_end = seg[SEG_K1];
+ const half* suh = (const half*) (is_gate ? p.g_suh : p.u_suh)[local];
+ const half2* A2;
+ size_t a_stride2;
+ if (p.a_global)
+ {
+ A2 = (const half2*) (is_gate ? p.had_g : p.had_u);
+ a_stride2 = (size_t) p.Hi / 2;
+ }
+ else
+ {
+ // bsz 1: every run is a single slot; rotate the input chunks of the k-range into shared
+ // memory here. A zero row stride makes the tile read it whatever the slot index (which
+ // still selects the C row)
+ const SlotInfo si = slot_info(p, sh_rows[0]);
+ for (int c = k_begin / 8 + warp; c < CEIL_DIVIDE(k_end, 8); c += WK)
+ rotate_chunk(p, si.row, suh, c, sh_A, lane);
+ __syncthreads();
+ A2 = (const half2*) sh_A;
+ a_stride2 = 0;
+ }
+
const uint32_t* B32 = (const uint32_t*) (is_gate ? p.g_trellis : p.u_trellis)[local];
- // Partial output rows of split ks live at slot + ks * slots (ksplit * slots <= slots_max)
- const size_t part = (size_t) ks * (p.bsz * p.topk) * p.I * (p.gu_f32 ? 4 : 2);
- void* C = (void*) (((char*) (is_gate ? p.gu_g : p.gu_u)) + part);
- gemv_tile<bits, cb, WIDE>(B32, A2, a_stride2, sh_rows, nrows, C, p.I, p.gu_f32, k_begin, k_end, p.I / 16, group, sh_red, sh_stage);
+ const int slots = p.bsz * p.topk;
+ void* C;
+ bool c_f32 = p.gu_f32;
+ if (p.ksplit_a < 0 && seg[is_gate ? SEG_NPG : SEG_NPU] > 1)
+ {
+ // Stream-K segment of a shared unit: fp32 partial row in the d_out scratch
+ const int nproj = p.gated ? 2 : 1;
+ const int pi = is_gate ? 0 : nproj - 1;
+ C = (void*) (p.d_out + (size_t) (pi * sk_rows(p.slots_max, slots, nproj, p.I, p.Ho) + seg[SEG_Q]) * slots * p.I);
+ c_f32 = true;
+ }
+ else
+ {
+ // Partial output rows of split q live at slot + q * slots (splits * slots <= slots_max)
+ const size_t part = (size_t) seg[SEG_Q] * slots * p.I * (p.gu_f32 ? 4 : 2);
+ C = (void*) (((char*) (is_gate ? p.gu_g : p.gu_u)) + part);
+ }
+ gemv_tile<bits, cb, WIDE>(B32, A2, a_stride2, sh_rows, nrows, C, p.I, c_f32, k_begin, k_end, p.I / 16, seg[SEG_GROUP], sh_red, sh_stage);
}
+ const int local = slot_info(p, sh_rows[0]).local;
for (int r = 0; r < nrows; ++r)
for (int j = 0; j < CPB; ++j)
{
const int s = sh_rows[r];
- const int chunk = (group * CPB + j) / GPC;
- if (!arrive_last(p.ctr_a + (size_t) s * (p.I / 128) + chunk, GPC * nproj * p.ksplit_a, &sh_flag)) continue;
+ const int chunk = (seg[SEG_GROUP] * CPB + j) / GPC;
+ if (!arrive_last(p.ctr_a + (size_t) s * (p.I / 128) + chunk, seg[SEG_EXP], sh_flag, seg[SEG_ADD])) continue;
if (p.dbg & 1) continue;
if (warp == 0)
{
@@ -763,20 +898,33 @@ void exl3_moe_coop_a_kernel(const MoeCoopParams p)
const size_t off = (size_t) s * p.I + col;
const size_t pstride = (size_t) (p.bsz * p.topk) * p.I;
- // Sum of the split-k partials (fixed order)
- auto load_sum = [&] (const void* buf, float& v0, float& v1, float& v2, float& v3)
+ // Sum of the split-k partials (fixed order); stream-K shared units: fp32 rows in d_out
+ auto load_sum = [&] (const void* buf, int np, int pi, float& v0, float& v1, float& v2, float& v3)
{
v0 = v1 = v2 = v3 = 0.0f;
- for (int q = 0; q < p.ksplit_a; ++q)
+ if (p.ksplit_a < 0 && np > 1)
+ {
+ const int nproj = p.gated ? 2 : 1;
+ const int slots = p.bsz * p.topk;
+ const float* part = p.d_out + (size_t) pi * sk_rows(p.slots_max, slots, nproj, p.I, p.Ho) * pstride + off;
+ for (int qq = 0; qq < np; ++qq)
+ {
+ float t0, t1, t2, t3;
+ load_f4_cg(part + qq * pstride, t0, t1, t2, t3);
+ v0 += t0; v1 += t1; v2 += t2; v3 += t3;
+ }
+ return;
+ }
+ for (int qq = 0; qq < np; ++qq)
{
float t0, t1, t2, t3;
- if (p.gu_f32) load_f4_cg(((const float*) buf) + q * pstride + off, t0, t1, t2, t3);
- else load_h4_cg(((const half*) buf) + q * pstride + off, t0, t1, t2, t3);
+ if (p.gu_f32) load_f4_cg(((const float*) buf) + qq * pstride + off, t0, t1, t2, t3);
+ else load_h4_cg(((const half*) buf) + qq * pstride + off, t0, t1, t2, t3);
v0 += t0; v1 += t1; v2 += t2; v3 += t3;
}
};
float u0, u1, u2, u3;
- load_sum(p.gu_u, u0, u1, u2, u3);
+ load_sum(p.gu_u, seg[SEG_NPU], p.gated ? 1 : 0, u0, u1, u2, u3);
had128(u0, u1, u2, u3, lane);
scale_h4(((const half*) p.u_svh[local]) + col, u0, u1, u2, u3);
if (p.u_bias) add_h4(((const half*) p.u_bias[local]) + col, u0, u1, u2, u3);
@@ -784,7 +932,7 @@ void exl3_moe_coop_a_kernel(const MoeCoopParams p)
float g0 = u0, g1 = u1, g2 = u2, g3 = u3;
if (p.gated)
{
- load_sum(p.gu_g, g0, g1, g2, g3);
+ load_sum(p.gu_g, seg[SEG_NPG], 0, g0, g1, g2, g3);
had128(g0, g1, g2, g3, lane);
scale_h4(((const half*) p.g_svh[local]) + col, g0, g1, g2, g3);
if (p.g_bias) add_h4(((const half*) p.g_bias[local]) + col, g0, g1, g2, g3);
@@ -803,6 +951,34 @@ void exl3_moe_coop_a_kernel(const MoeCoopParams p)
}
}
+template <int bits, int cb, bool WIDE>
+__global__ __launch_bounds__(THREADS, 2) // 2 resident blocks per SM (<= 64 registers)
+void exl3_moe_coop_a_kernel(const MoeCoopParams p)
+{
+ extern __shared__ uint32_t smem_dyn[];
+ half* sh_A = (half*) smem_dyn;
+ float* sh_red = (float*) (smem_dyn + p.Hi / 2);
+ uint32_t* sh_stage = smem_dyn + p.Hi / 2 + WK * ROWS * COLS;
+ __shared__ int sh_flag;
+ __shared__ int sh_res[4];
+ __shared__ int sh_rows[ROWS];
+ __shared__ int sh_seg[SEG_N];
+
+ // Reset the down stage's counters for this call (its previous use finished in stream order)
+ for (int i = blockIdx.x * THREADS + threadIdx.x; i < p.ctr_b_len; i += gridDim.x * THREADS)
+ p.ctr_b[i] = 0;
+
+ if (threadIdx.x == 0) sh_seg[SEG_NEXT] = -1;
+ for (;;)
+ {
+ if (threadIdx.x == 0) a_next_seg<WIDE>(p, sh_seg);
+ __syncthreads();
+ if (sh_seg[SEG_K0] < 0) break;
+ a_unit<bits, cb, WIDE>(p, sh_seg, sh_A, sh_red, sh_stage, &sh_flag, sh_res, sh_rows);
+ __syncthreads();
+ }
+}
+
// ---------------------------------------------------------------------------------------------
// Kernel B: down GEMV per (expert run, group); the last arrival of a (token, chunk) reduces the
// token's slots (rotation * svh, down bias, routing weight) in a fixed order, merges the shared
diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_gemm.cuh b/exllamav3/exllamav3_ext/quant/exl3_moe_gemm.cuh
new file mode 100644
index 0000000..658522d
--- /dev/null
+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_gemm.cuh
@@ -0,0 +1,187 @@
+#pragma once
+
+#include <cuda_fp16.h>
+#include <stdint.h>
+#include "../util.cuh"
+#include "../ptx.cuh"
+#include "exl3_dq.cuh"
+
+// Grouped prefill GEMM for the exl3 MoE tier: C[e rows] = A[e rows] @ W_e for every expert e of
+// [count_lo, count_hi] rows, A / C addressed by the expert-sorted row position. One CTA owns one
+// (expert, BM-row tile, 128-column tile) output block and runs the whole K loop itself (no split-K
+// across CTAs, no group barriers): 8 warps, each decoding one 16x16 trellis block per k16 and feeding
+// it to BM/16 row fragments, fp32 accumulation, cp.async multi-stage pipeline. Same B decode
+// (dq_dispatch) and A fragment layout as exl3_gemm_kernel_inner. Output is rounded to fp16 once.
+#define MOEG_THREADS 256
+#define MOEG_BN 128
+
+template<int BITS, int BM>
+constexpr int moeg_stage_bytes() { return BM * 64 + 512 * BITS; }
+
+template<int BITS, int BM, int STAGES, int MINB>
+__global__ __launch_bounds__(MOEG_THREADS, MINB)
+void exl3_moe_gemm_kernel
+(
+ const half* __restrict__ A0, const half* __restrict__ A1,
+ half* __restrict__ C0, half* __restrict__ C1,
+ const uint16_t** __restrict__ B0, const uint16_t** __restrict__ B1,
+ const int64_t* __restrict__ counts, // [E]
+ const int64_t* __restrict__ starts, // [E] first sorted row of expert
+ const int num_experts,
+ const int K, const int N,
+ const int count_lo, const int count_hi
+)
+{
+ const int z = blockIdx.z;
+ const int which = z >= num_experts;
+ const int e = which ? z - num_experts : z;
+ const int cnt = (int) counts[e];
+ if (cnt < count_lo || cnt > count_hi) return;
+ const int m0 = blockIdx.y * BM;
+ if (m0 >= cnt) return;
+ const int rows = min(BM, cnt - m0);
+ const int n0 = blockIdx.x * MOEG_BN;
+
+ const half* A = (which ? A1 : A0) + (size_t) (starts[e] + m0) * K;
+ half* C = (which ? C1 : C0) + (size_t) (starts[e] + m0) * N + n0;
+ const uint16_t* B = (which ? B1 : B0)[e];
+
+ extern __shared__ __align__(16) uint8_t moeg_smem[];
+ constexpr int A_BYTES = BM * 64;
+ constexpr int STAGE_BYTES = moeg_stage_bytes<BITS, BM>();
+
+ const int tid = threadIdx.x;
+ const int warp = tid >> 5, lane = tid & 31;
+ const int KT = K / 32;
+ const int NBf = N / 16; // 16-col blocks across the full matrix
+ const int nb0 = n0 / 16;
+
+ // per-thread copy descriptors
+ constexpr int A_ITERS = BM * 4 / MOEG_THREADS > 0 ? BM * 4 / MOEG_THREADS : 1;
+ constexpr bool A_PART = BM * 4 < MOEG_THREADS;
+ const half* a_src[A_ITERS];
+ uint32_t a_dst[A_ITERS];
+ bool a_ok[A_ITERS];
+ #pragma unroll
+ for (int i = 0; i < A_ITERS; ++i)
+ {
+ int c = tid + i * MOEG_THREADS;
+ int row = c >> 2, col = c & 3;
+ int colsw = col ^ ((row >> 1) & 3);
+ a_ok[i] = (!A_PART || c < BM * 4) && row < rows;
+ a_src[i] = A + (size_t) row * K + col * 8;
+ a_dst[i] = row * 64 + colsw * 16;
+ }
+ constexpr int B_CHUNKS = 32 * BITS; // 16B chunks per stage (2 k16 rows)
+ const bool b_ok = tid < B_CHUNKS;
+ const int b_kr = tid / (16 * BITS), b_j = tid % (16 * BITS);
+ const uint16_t* b_src = B + ((size_t) b_kr * NBf + nb0) * (16 * BITS) + b_j * 8;
+ const size_t b_step = (size_t) 2 * NBf * (16 * BITS); // per k32 tile, in u16
+ const uint32_t b_dst = A_BYTES + b_kr * (8 * 16 * BITS * 2) + b_j * 16;
+
+ const uint32_t smem_base = (uint32_t) __cvta_generic_to_shared(moeg_smem);
+
+ auto load_stage = [&] (int kt, int st)
+ {
+ uint32_t sb = smem_base + st * STAGE_BYTES;
+ #pragma unroll
+ for (int i = 0; i < A_ITERS; ++i)
+ if (a_ok[i])
+ {
+ const half* src = a_src[i] + kt * 32;
+ asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" :: "r"(sb + a_dst[i]), "l"(src));
+ }
+ if (b_ok)
+ {
+ const uint16_t* src = b_src + (size_t) kt * b_step;
+ asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" :: "r"(sb + b_dst), "l"(src));
+ }
+ };
+
+ FragC acc[BM / 16][2];
+ #pragma unroll
+ for (int m = 0; m < BM / 16; ++m)
+ #pragma unroll
+ for (int n = 0; n < 2; ++n) acc[m][n] = {};
+
+ #pragma unroll
+ for (int s = 0; s < STAGES - 1; ++s)
+ {
+ if (s < KT) load_stage(s, s);
+ cp_async_fence();
+ }
+
+ // ldmatrix lane addressing (same as exl3_gemm_kernel_inner)
+ const int lr = (lane & 7) + 8 * ((lane >> 3) & 1);
+ const int lc = lane >> 4;
+
+ for (int kt = 0; kt < KT; ++kt)
+ {
+ cp_async_wait<STAGES - 2>();
+ __syncthreads();
+ {
+ int nk = kt + STAGES - 1;
+ if (nk < KT) load_stage(nk, nk % STAGES);
+ cp_async_fence();
+ }
+ const int st = kt % STAGES;
+ const uint32_t sa = smem_base + st * STAGE_BYTES;
+ const uint16_t* sb16 = (const uint16_t*) (moeg_smem + st * STAGE_BYTES + A_BYTES);
+ #pragma unroll
+ for (int s = 0; s < 2; ++s)
+ {
+ FragB fb0, fb1;
+ const uint32_t* shb = (const uint32_t*) (sb16 + (s * 8 + warp) * (16 * BITS));
+ dq_dispatch<BITS, 2>(shb, lane << 3, fb0, fb1);
+ FragA fa[BM / 16];
+ #pragma unroll
+ for (int m = 0; m < BM / 16; ++m)
+ {
+ int R = m * 16 + lr;
+ int c = (lc + s * 2) ^ ((R >> 1) & 3);
+ uint32_t addr = sa + R * 64 + c * 16;
+ uint32_t* a = reinterpret_cast<uint32_t*>(&fa[m]);
+ asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n"
+ : "=r"(a[0]), "=r"(a[1]), "=r"(a[2]), "=r"(a[3]) : "r"(addr));
+ }
+ #pragma unroll
+ for (int m = 0; m < BM / 16; ++m)
+ {
+ ptx_mma_m16n8k16(fa[m], fb0, acc[m][0]);
+ ptx_mma_m16n8k16(fa[m], fb1, acc[m][1]);
+ }
+ }
+ }
+ cp_async_wait<0>();
+
+ // epilogue: fp32 -> fp16, direct from fragments
+ #pragma unroll
+ for (int m = 0; m < BM / 16; ++m)
+ {
+ const int r0 = m * 16 + (lane >> 2), r1 = r0 + 8;
+ #pragma unroll
+ for (int n = 0; n < 2; ++n)
+ {
+ const int col = warp * 16 + n * 8 + (lane & 3) * 2;
+ if (r0 < rows) *(half2*) (C + (size_t) r0 * N + col) = __floats2half2_rn(acc[m][n][0], acc[m][n][1]);
+ if (r1 < rows) *(half2*) (C + (size_t) r1 * N + col) = __floats2half2_rn(acc[m][n][2], acc[m][n][3]);
+ }
+ }
+}
+
+template<int BITS, int BM, int STAGES, int MINB>
+static void exl3_moe_gemm_launch
+(
+ const half* A0, const half* A1, half* C0, half* C1,
+ const uint16_t** B0, const uint16_t** B1,
+ const int64_t* counts, const int64_t* starts, int num_experts, int nmat,
+ int K, int N, int count_lo, int count_hi, int max_rows, cudaStream_t stream
+)
+{
+ constexpr int smem = STAGES * moeg_stage_bytes<BITS, BM>();
+ auto kern = exl3_moe_gemm_kernel<BITS, BM, STAGES, MINB>;
+ static bool attr = false;
+ if (!attr) { cudaFuncSetAttribute(kern, cudaFuncAttributeMaxDynamicSharedMemorySize, smem); attr = true; }
+ dim3 grid(N / MOEG_BN, (max_rows + BM - 1) / BM, num_experts * nmat);
+ kern<<<grid, MOEG_THREADS, smem, stream>>>(A0, A1, C0, C1, B0, B1, counts, starts, num_experts, K, N, count_lo, count_hi);
+}
diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_grouped.cu b/exllamav3/exllamav3_ext/quant/exl3_moe_grouped.cu
new file mode 100644
index 0000000..b444f9e
--- /dev/null
+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_grouped.cu
@@ -0,0 +1,277 @@
+#include <cuda_fp16.h>
+#include <c10/cuda/CUDAGuard.h>
+#include <ATen/cuda/CUDAContext.h>
+#include <ATen/ATen.h>
+#include "../util.h"
+#include "../util.cuh"
+#include "../ptx.cuh"
+#include "exl3_moe_common.cuh"
+#include "hadamard_inner.cuh"
+#include "exl3_moe_gemm.cuh"
+#include "exl3_moe_grouped.cuh"
+
+// Grouped prefill tier of the fused MoE: the same math as exl3_moe_kernel (input hadamard, gate/up
+// GEMMs, activation + hadamards, down GEMM, output hadamard into the per-assignment fp32 slots that
+// exl3_moe_gather sums), split into token-parallel hadamard kernels and two grouped GEMM launches
+// (exl3_moe_gemm.cuh) instead of one persistent kernel with expert groups of cooperating CTAs
+
+#define MOEG_ROW_THREADS 256
+
+// Expert of sorted row r: the last expert whose start is <= r (empty experts share their successor's
+// start, so the last of equal starts is the non-empty one)
+__device__ __forceinline__ int moeg_expert_of(const int64_t* __restrict__ starts, int num_experts, int64_t r)
+{
+ int lo = 0, hi = num_experts;
+ while (lo < hi)
+ {
+ int mid = (lo + hi) >> 1;
+ if (starts[mid] <= r) lo = mid + 1; else hi = mid;
+ }
+ return lo - 1;
+}
+
+__global__ __launch_bounds__(MOEG_ROW_THREADS)
+void exl3_moe_grouped_in_kernel
+(
+ const half* __restrict__ hidden_state,
+ half* __restrict__ buf_g, half* __restrict__ buf_u,
+ const half** __restrict__ gate_suh, const half** __restrict__ up_suh,
+ const int64_t* __restrict__ token_sorted,
+ const int64_t* __restrict__ counts, const int64_t* __restrict__ starts, const int64_t* __restrict__ fused_base,
+ const int num_experts, const int hidden_dim, const int count_lo, const int count_hi
+)
+{
+ const int wpt = hidden_dim / 128;
+ const int64_t gw = (int64_t) blockIdx.x * (MOEG_ROW_THREADS / 32) + threadIdx.x / 32;
+ const int64_t r = gw / wpt;
+ const int chunk = gw % wpt;
+ const int e = moeg_expert_of(starts, num_experts, r);
+ if (e < 0) return;
+ const int cnt = (int) counts[e];
+ if (cnt < count_lo || cnt > count_hi || r >= starts[e] + cnt) return;
+ const int64_t slot = fused_base[e] + (r - starts[e]);
+ const half* in_ptr = hidden_state + token_sorted[r] * hidden_dim + chunk * 128;
+ had_hf_r_128_inner<true, false>(in_ptr, buf_g + slot * hidden_dim + chunk * 128, gate_suh[e] + chunk * 128, 0.088388347648f);
+ had_hf_r_128_inner<true, false>(in_ptr, buf_u + slot * hidden_dim + chunk * 128, up_suh[e] + chunk * 128, 0.088388347648f);
+}
+
+__global__ __launch_bounds__(MOEG_ROW_THREADS)
+void exl3_moe_grouped_act_kernel
+(
+ half* __restrict__ inter_g, const half* __restrict__ inter_u,
+ const half** __restrict__ gate_svh, const half** __restrict__ up_svh, const half** __restrict__ down_suh,
+ const int64_t* __restrict__ counts, const int64_t* __restrict__ starts, const int64_t* __restrict__ fused_base,
+ const int num_experts, const int intermediate_dim, const int count_lo, const int count_hi,
+ const float act_limit, const int act_function
+)
+{
+ const int wpt = intermediate_dim / 128;
+ const int64_t gw = (int64_t) blockIdx.x * (MOEG_ROW_THREADS / 32) + threadIdx.x / 32;
+ const int64_t r = gw / wpt;
+ const int chunk = gw % wpt;
+ const int e = moeg_expert_of(starts, num_experts, r);
+ if (e < 0) return;
+ const int cnt = (int) counts[e];
+ if (cnt < count_lo || cnt > count_hi || r >= starts[e] + cnt) return;
+ const int64_t slot = fused_base[e] + (r - starts[e]);
+ const int64_t o = slot * intermediate_dim + chunk * 128;
+ had_hf_r_128_guad_inner
+ (
+ inter_g + o, inter_u + o, inter_g + o,
+ gate_svh[e] + chunk * 128, up_svh[e] + chunk * 128, down_suh[e] + chunk * 128,
+ 0.088388347648f, act_limit, act_function
+ );
+}
+
+// Output hadamard of the down GEMM rows fused with the per-token combine: one warp per (token, 128 columns) sums the token's
+// grouped-tier assignments in k order and adds the total to the fp32 output row (exl3_moe_gather handles the other tiers)
+__global__ __launch_bounds__(MOEG_ROW_THREADS)
+void exl3_moe_grouped_out_kernel
+(
+ const half* __restrict__ down_out, float* __restrict__ out_state,
+ const half** __restrict__ down_svh, const half* __restrict__ weight_sorted,
+ const int64_t* __restrict__ flat_expert, const int64_t* __restrict__ inv_order,
+ const int64_t* __restrict__ counts, const int64_t* __restrict__ starts, const int64_t* __restrict__ gbase,
+ const int num_tokens, const int topk, const int num_experts, const int hidden_dim, const int count_lo, const int count_hi
+)
+{
+ const int wpt = hidden_dim / 128;
+ const int64_t gw = (int64_t) blockIdx.x * (MOEG_ROW_THREADS / 32) + threadIdx.x / 32;
+ const int64_t token = gw / wpt;
+ const int chunk = gw % wpt;
+ if (token >= num_tokens) return;
+ const int t = threadIdx.x & 31;
+ float s0 = 0.f, s1 = 0.f, s2 = 0.f, s3 = 0.f;
+ bool any = false;
+ for (int k = 0; k < topk; ++k)
+ {
+ const int64_t a = token * topk + k;
+ const int64_t e64 = flat_expert[a];
+ if (e64 < 0 || e64 >= num_experts) continue;
+ const int e = (int) e64;
+ const int cnt = (int) counts[e];
+ if (cnt < count_lo || cnt > count_hi) continue;
+ const int64_t pos = inv_order[a];
+ const int64_t slot = gbase[e] + (pos - starts[e]);
+ const float w = __half2float(weight_sorted[pos]);
+ any = true;
+ half4 v = ((const half4*) (down_out + slot * hidden_dim + chunk * 128))[t];
+ float v0 = __half2float(__low2half(v.x)), v1 = __half2float(__high2half(v.x));
+ float v2 = __half2float(__low2half(v.y)), v3 = __half2float(__high2half(v.y));
+ float p0 = v0 + v1, d0 = v0 - v1, p1 = v2 + v3, d1 = v2 - v3;
+ float h0 = p0 + p1, h1 = d0 + d1, h2 = p0 - p1, h3 = d0 - d1;
+ shuffle_had_f4x32(h0, h1, h2, h3, t);
+ const float rs = 0.088388347648f * w;
+ const half4 sc = ((const half4*) (down_svh[e] + chunk * 128))[t];
+ s0 += h0 * rs * __low2float(sc.x);
+ s1 += h1 * rs * __high2float(sc.x);
+ s2 += h2 * rs * __low2float(sc.y);
+ s3 += h3 * rs * __high2float(sc.y);
+ }
+ if (!any) return;
+ float4* o = (float4*) (out_state + token * hidden_dim + chunk * 128) + t;
+ float4 cur = *o;
+ cur.x += s0; cur.y += s1; cur.z += s2; cur.w += s3;
+ *o = cur;
+}
+
+#define MOEG_CASE(BITS) \
+ case BITS: if (bm == 64) exl3_moe_gemm_launch<BITS, 64, STAGES, 2>(A0, A1, C0, C1, B0, B1, counts, starts, E, nmat, K, N, lo, hi, max_rows, stream); \
+ else exl3_moe_gemm_launch<BITS, 32, STAGES, 2>(A0, A1, C0, C1, B0, B1, counts, starts, E, nmat, K, N, lo, hi, max_rows, stream); \
+ break;
+
+template<int STAGES>
+static void moeg_gemm
+(
+ int bits, int bm,
+ const half* A0, const half* A1, half* C0, half* C1, const uint16_t** B0, const uint16_t** B1,
+ const int64_t* counts, const int64_t* starts, int E, int nmat, int K, int N, int lo, int hi, int max_rows,
+ cudaStream_t stream
+)
+{
+ switch (bits)
+ {
+ MOEG_CASE(2) MOEG_CASE(3) MOEG_CASE(4) MOEG_CASE(5) MOEG_CASE(6)
+ default: TORCH_CHECK(false, "exl3_moe_grouped: unsupported bitrate ", bits);
+ }
+}
+
+bool exl3_moe_grouped_supported(int K_gate, int K_up, int K_down)
+{
+ auto ok = [](int k) { return k >= 2 && k <= 6; };
+ return ok(K_gate) && ok(K_up) && ok(K_down);
+}
+
+void exl3_moe_grouped
+(
+ const at::Tensor& hidden_state,
+ const at::Tensor& expert_count,
+ const at::Tensor& expert_start,
+ const at::Tensor& token_sorted,
+ const at::Tensor& weight_sorted,
+ const int act_function,
+ const int K_gate,
+ const int K_up,
+ const int K_down,
+ const at::Tensor& gate_ptrs_trellis,
+ const at::Tensor& gate_ptrs_suh,
+ const at::Tensor& gate_ptrs_svh,
+ const at::Tensor& up_ptrs_trellis,
+ const at::Tensor& up_ptrs_suh,
+ const at::Tensor& up_ptrs_svh,
+ const at::Tensor& down_ptrs_trellis,
+ const at::Tensor& down_ptrs_suh,
+ const at::Tensor& down_ptrs_svh,
+ const float act_limit,
+ const at::Tensor& output_state,
+ const at::Tensor& flat_expert,
+ const at::Tensor& inv_order,
+ const at::Tensor& group_base,
+ const int64_t n_rows,
+ const int count_lo,
+ const int count_hi,
+ const int m_tile,
+ const int intermediate_dim
+)
+{
+ const at::cuda::OptionalCUDAGuard device_guard(hidden_state.device());
+ cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream();
+ TORCH_CHECK_DTYPE(hidden_state, kHalf);
+ TORCH_CHECK_DTYPE(expert_count, kLong);
+ TORCH_CHECK_DTYPE(expert_start, kLong);
+ TORCH_CHECK_DTYPE(token_sorted, kLong);
+ TORCH_CHECK_DTYPE(weight_sorted, kHalf);
+ TORCH_CHECK_DTYPE(output_state, kFloat);
+ TORCH_CHECK_DTYPE(flat_expert, kLong);
+ TORCH_CHECK_DTYPE(inv_order, kLong);
+ TORCH_CHECK_DTYPE(group_base, kLong);
+ TORCH_CHECK(m_tile == 32 || m_tile == 64, "exl3_moe_grouped: m_tile");
+ TORCH_CHECK(exl3_moe_grouped_supported(K_gate, K_up, K_down), "exl3_moe_grouped: bitrate");
+ const int H = hidden_state.size(1);
+ const int I = intermediate_dim;
+ TORCH_CHECK(H % 128 == 0 && I % 128 == 0, "exl3_moe_grouped: dims must be multiples of 128");
+ const int E = gate_ptrs_trellis.size(0);
+ const int64_t rows_total = token_sorted.size(0);
+ const int64_t n_slots = n_rows;
+ const int num_tokens = output_state.size(0);
+ const int topk = rows_total / num_tokens;
+ if (!rows_total || !n_slots) return;
+ const int max_rows = count_hi;
+
+ auto opt = hidden_state.options();
+ at::Tensor buf = at::empty({2, n_slots, H}, opt);
+ at::Tensor inter = at::empty({2, n_slots, I}, opt);
+ half* buf_g = (half*) buf.data_ptr();
+ half* buf_u = buf_g + n_slots * H;
+ half* inter_g = (half*) inter.data_ptr();
+ half* inter_u = inter_g + n_slots * I;
+ // The down GEMM output reuses the gate input buffer: gate/up have fully consumed it by then (stream order)
+ half* down_out = buf_g;
+
+ const int64_t* counts = (const int64_t*) expert_count.data_ptr();
+ const int64_t* starts = (const int64_t*) expert_start.data_ptr();
+ const int64_t* fbase = (const int64_t*) group_base.data_ptr();
+
+ auto grid_for = [&](int dim) { return (unsigned) ((rows_total * (dim / 128) + 7) / 8); };
+
+ exl3_moe_grouped_in_kernel<<<grid_for(H), MOEG_ROW_THREADS, 0, stream>>>
+ (
+ (const half*) hidden_state.data_ptr(), buf_g, buf_u,
+ (const half**) gate_ptrs_suh.data_ptr(), (const half**) up_ptrs_suh.data_ptr(),
+ (const int64_t*) token_sorted.data_ptr(), counts, starts, fbase, E, H, count_lo, count_hi
+ );
+
+ if (K_gate == K_up)
+ moeg_gemm<3>(K_gate, m_tile, buf_g, buf_u, inter_g, inter_u,
+ (const uint16_t**) gate_ptrs_trellis.data_ptr(), (const uint16_t**) up_ptrs_trellis.data_ptr(),
+ counts, fbase, E, 2, H, I, count_lo, count_hi, max_rows, stream);
+ else
+ {
+ moeg_gemm<3>(K_gate, m_tile, buf_g, buf_g, inter_g, inter_g,
+ (const uint16_t**) gate_ptrs_trellis.data_ptr(), (const uint16_t**) gate_ptrs_trellis.data_ptr(),
+ counts, fbase, E, 1, H, I, count_lo, count_hi, max_rows, stream);
+ moeg_gemm<3>(K_up, m_tile, buf_u, buf_u, inter_u, inter_u,
+ (const uint16_t**) up_ptrs_trellis.data_ptr(), (const uint16_t**) up_ptrs_trellis.data_ptr(),
+ counts, fbase, E, 1, H, I, count_lo, count_hi, max_rows, stream);
+ }
+
+ exl3_moe_grouped_act_kernel<<<grid_for(I), MOEG_ROW_THREADS, 0, stream>>>
+ (
+ inter_g, inter_u,
+ (const half**) gate_ptrs_svh.data_ptr(), (const half**) up_ptrs_svh.data_ptr(), (const half**) down_ptrs_suh.data_ptr(),
+ counts, starts, fbase, E, I, count_lo, count_hi, act_limit, act_function
+ );
+
+ moeg_gemm<4>(K_down, m_tile, inter_g, inter_g, down_out, down_out,
+ (const uint16_t**) down_ptrs_trellis.data_ptr(), (const uint16_t**) down_ptrs_trellis.data_ptr(),
+ counts, fbase, E, 1, I, H, count_lo, count_hi, max_rows, stream);
+
+ exl3_moe_grouped_out_kernel<<<(unsigned) (((int64_t) num_tokens * (H / 128) + 7) / 8), MOEG_ROW_THREADS, 0, stream>>>
+ (
+ down_out, (float*) output_state.data_ptr(),
+ (const half**) down_ptrs_svh.data_ptr(), (const half*) weight_sorted.data_ptr(),
+ (const int64_t*) flat_expert.data_ptr(), (const int64_t*) inv_order.data_ptr(),
+ counts, starts, fbase, num_tokens, topk, E, H, count_lo, count_hi
+ );
+ cuda_check(cudaPeekAtLastError());
+}
diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_grouped.cuh b/exllamav3/exllamav3_ext/quant/exl3_moe_grouped.cuh
new file mode 100644
index 0000000..bf916fb
--- /dev/null
+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_grouped.cuh
@@ -0,0 +1,39 @@
+#pragma once
+
+#include <ATen/Tensor.h>
+
+bool exl3_moe_grouped_supported(int K_gate, int K_up, int K_down);
+
+// Grouped prefill tier: experts with count in [count_lo, count_hi] (m_tile 32 or 64 row tiles). Their rows live in compact
+// work buffers at group_base[e] + row (n_rows in all); the weighted outputs are summed per token in k order and added to output_state
+void exl3_moe_grouped
+(
+ const at::Tensor& hidden_state,
+ const at::Tensor& expert_count,
+ const at::Tensor& expert_start,
+ const at::Tensor& token_sorted,
+ const at::Tensor& weight_sorted,
+ const int act_function,
+ const int K_gate,
+ const int K_up,
+ const int K_down,
+ const at::Tensor& gate_ptrs_trellis,
+ const at::Tensor& gate_ptrs_suh,
+ const at::Tensor& gate_ptrs_svh,
+ const at::Tensor& up_ptrs_trellis,
+ const at::Tensor& up_ptrs_suh,
+ const at::Tensor& up_ptrs_svh,
+ const at::Tensor& down_ptrs_trellis,
+ const at::Tensor& down_ptrs_suh,
+ const at::Tensor& down_ptrs_svh,
+ const float act_limit,
+ const at::Tensor& output_state,
+ const at::Tensor& flat_expert,
+ const at::Tensor& inv_order,
+ const at::Tensor& group_base,
+ const int64_t n_rows,
+ const int count_lo,
+ const int count_hi,
+ const int m_tile,
+ const int intermediate_dim
+);
diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_prefill.cu b/exllamav3/exllamav3_ext/quant/exl3_moe_prefill.cu
index f3da7d2..2f85ea4 100644
--- a/exllamav3/exllamav3_ext/quant/exl3_moe_prefill.cu
+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_prefill.cu
@@ -25,6 +25,8 @@
#include "hadamard_inner.cuh"
#if defined(USE_ROCM)
#include "../hip/hip_mma.cuh"
+#else
+#include "../ptx.cuh"
#endif
#include "exl3_dq.cuh"
#include "exl3_moe_prefill.cuh"
diff --git a/exllamav3/exllamav3_ext/triton_kernel.h b/exllamav3/exllamav3_ext/triton_kernel.h
index 1fc8c63..3ed8a1a 100644
--- a/exllamav3/exllamav3_ext/triton_kernel.h
+++ b/exllamav3/exllamav3_ext/triton_kernel.h
@@ -25,6 +25,7 @@ struct TritonKernel
std::string name;
int num_warps;
int shared_bytes;
+ int grid_y = 1; // second launch-grid axis chosen at compile time (sub-tiles), read by the graph launch sites
TritonKernel(py::bytes cubin, std::string name, int num_warps, int shared_bytes);
~TritonKernel();
diff --git a/exllamav3/foreign_quant/__init__.py b/exllamav3/foreign_quant/__init__.py
new file mode 100644
index 0000000..84889df
--- /dev/null
+++ b/exllamav3/foreign_quant/__init__.py
@@ -0,0 +1,14 @@
+"""Foreign-quant dequant reference (numpy, torch-free).
+
+Decodes the non-EXL3 quantization formats shipped in third-party checkpoints
+(NVIDIA Nemotron-3.5-Bolt: ggml IQ2_XXS / Q8_0 via ModelOpt + NVFP4 W4A16) to
+float32, e.g. to stream-dequant weights for the EXL3 converter. GENERIC:
+usable for any ggml/NVFP4 checkpoint, on CUDA or HIP hosts.
+
+Layout conventions follow the sources cited in each submodule. All entry
+points take raw little-endian payload bytes as uint8 numpy arrays and return
+float32 arrays; no torch, no compiled extension, no GPU.
+"""
+from __future__ import annotations
+
+__all__ = ["q8_0", "iq2_xxs", "nvfp4"]
diff --git a/exllamav3/foreign_quant/iq2_xxs.py b/exllamav3/foreign_quant/iq2_xxs.py
new file mode 100644
index 0000000..76a5e49
--- /dev/null
+++ b/exllamav3/foreign_quant/iq2_xxs.py
@@ -0,0 +1,178 @@
+"""IQ2_XXS dequant reference (ggml, numpy-only).
+
+"Almost true" 2-bit quantization at 2.0625 bits/weight: each super-block of
+256 values is 66 bytes. After llama.cpp ``ggml/src/ggml-common.h``
+(MIT License, Copyright (c) llama.cpp contributors,
+https://github.com/ggml-org/llama.cpp)::
+
+ typedef struct { ggml_half d; uint16_t qs[QK_K/8]; } block_iq2_xxs; // QK_K = 256
+
+i.e. a little-endian fp16 scale followed by 32 little-endian uint16 indices
+into the 256-entry ``iq2xxs_grid`` codebook (each grid entry holds eight
+{8, 25, 43}-valued magnitudes; per-group signs come from ``ksigns_iq2xs`` /
+``kmask_iq2xs``). Decoded by ``dequantize_row_iq2_xxs``
+(``ggml/src/ggml-quants.c``), ported here op-for-op in float32.
+
+In the Bolt safetensors, IQ2_XXS tensors are stored as raw bytes with shape
+``[..., num_256_blocks, 66]`` (e.g. an expert ``up_proj`` is
+U8 ``[2048, 4, 66]`` for latent dim 1024 = 4 x 256).
+"""
+from __future__ import annotations
+
+import numpy as np
+
+IQ2_XXS_GROUP_SIZE = 256
+IQ2_XXS_BLOCK_BYTES = 66
+
+# Codebook + sign tables, verbatim from llama.cpp ggml/src/ggml-common.h
+# (iq2xxs_grid, ksigns_iq2xs, kmask_iq2xs). MIT License, see module docstring.
+_IQ2XXS_GRID = (
+ 0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08,
+ 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x08080808082b0808,
+ 0x08080808082b082b, 0x08080808082b2b08, 0x08080808082b2b2b, 0x0808080819080819,
+ 0x0808080819081908, 0x0808080819190808, 0x0808080819192b08, 0x08080808192b0819,
+ 0x08080808192b1908, 0x080808082b080808, 0x080808082b08082b, 0x080808082b082b2b,
+ 0x080808082b2b082b, 0x0808081908080819, 0x0808081908081908, 0x0808081908190808,
+ 0x0808081908191919, 0x0808081919080808, 0x080808192b081908, 0x080808192b192b08,
+ 0x0808082b08080808, 0x0808082b0808082b, 0x0808082b082b082b, 0x0808082b2b08082b,
+ 0x0808190808080819, 0x0808190808081908, 0x0808190808190808, 0x08081908082b0819,
+ 0x08081908082b1908, 0x0808190819080808, 0x080819081908082b, 0x0808190819082b08,
+ 0x08081908192b0808, 0x080819082b080819, 0x080819082b081908, 0x080819082b190808,
+ 0x080819082b2b1908, 0x0808191908080808, 0x080819190808082b, 0x0808191908082b08,
+ 0x08081919082b0808, 0x080819191908192b, 0x08081919192b2b19, 0x080819192b080808,
+ 0x080819192b190819, 0x0808192b08082b19, 0x0808192b08190808, 0x0808192b19080808,
+ 0x0808192b2b081908, 0x0808192b2b2b1908, 0x08082b0808080808, 0x08082b0808081919,
+ 0x08082b0808082b08, 0x08082b0808191908, 0x08082b08082b2b08, 0x08082b0819080819,
+ 0x08082b0819081908, 0x08082b0819190808, 0x08082b081919082b, 0x08082b082b082b08,
+ 0x08082b1908081908, 0x08082b1919080808, 0x08082b2b0808082b, 0x08082b2b08191908,
+ 0x0819080808080819, 0x0819080808081908, 0x0819080808190808, 0x08190808082b0819,
+ 0x0819080819080808, 0x08190808192b0808, 0x081908082b081908, 0x081908082b190808,
+ 0x081908082b191919, 0x0819081908080808, 0x0819081908082b08, 0x08190819082b0808,
+ 0x0819081919190808, 0x0819081919192b2b, 0x081908192b080808, 0x0819082b082b1908,
+ 0x0819082b19081919, 0x0819190808080808, 0x0819190808082b08, 0x08191908082b0808,
+ 0x08191908082b1919, 0x0819190819082b19, 0x081919082b080808, 0x0819191908192b08,
+ 0x08191919192b082b, 0x0819192b08080808, 0x0819192b0819192b, 0x08192b0808080819,
+ 0x08192b0808081908, 0x08192b0808190808, 0x08192b0819080808, 0x08192b082b080819,
+ 0x08192b1908080808, 0x08192b1908081919, 0x08192b192b2b0808, 0x08192b2b19190819,
+ 0x082b080808080808, 0x082b08080808082b, 0x082b080808082b2b, 0x082b080819081908,
+ 0x082b0808192b0819, 0x082b08082b080808, 0x082b08082b08082b, 0x082b0819082b2b19,
+ 0x082b081919082b08, 0x082b082b08080808, 0x082b082b0808082b, 0x082b190808080819,
+ 0x082b190808081908, 0x082b190808190808, 0x082b190819080808, 0x082b19081919192b,
+ 0x082b191908080808, 0x082b191919080819, 0x082b1919192b1908, 0x082b192b2b190808,
+ 0x082b2b0808082b08, 0x082b2b08082b0808, 0x082b2b082b191908, 0x082b2b2b19081908,
+ 0x1908080808080819, 0x1908080808081908, 0x1908080808190808, 0x1908080808192b08,
+ 0x19080808082b0819, 0x19080808082b1908, 0x1908080819080808, 0x1908080819082b08,
+ 0x190808081919192b, 0x19080808192b0808, 0x190808082b080819, 0x190808082b081908,
+ 0x190808082b190808, 0x1908081908080808, 0x19080819082b0808, 0x19080819192b0819,
+ 0x190808192b080808, 0x190808192b081919, 0x1908082b08080819, 0x1908082b08190808,
+ 0x1908082b19082b08, 0x1908082b1919192b, 0x1908082b192b2b08, 0x1908190808080808,
+ 0x1908190808082b08, 0x19081908082b0808, 0x190819082b080808, 0x190819082b192b19,
+ 0x190819190819082b, 0x19081919082b1908, 0x1908192b08080808, 0x19082b0808080819,
+ 0x19082b0808081908, 0x19082b0808190808, 0x19082b0819080808, 0x19082b0819081919,
+ 0x19082b1908080808, 0x19082b1919192b08, 0x19082b19192b0819, 0x19082b192b08082b,
+ 0x19082b2b19081919, 0x19082b2b2b190808, 0x1919080808080808, 0x1919080808082b08,
+ 0x1919080808190819, 0x1919080808192b19, 0x19190808082b0808, 0x191908082b080808,
+ 0x191908082b082b08, 0x1919081908081908, 0x191908191908082b, 0x191908192b2b1908,
+ 0x1919082b2b190819, 0x191919082b190808, 0x191919082b19082b, 0x1919191908082b2b,
+ 0x1919192b08080819, 0x1919192b19191908, 0x19192b0808080808, 0x19192b0808190819,
+ 0x19192b0808192b19, 0x19192b08192b1908, 0x19192b1919080808, 0x19192b2b08082b08,
+ 0x192b080808081908, 0x192b080808190808, 0x192b080819080808, 0x192b0808192b2b08,
+ 0x192b081908080808, 0x192b081919191919, 0x192b082b08192b08, 0x192b082b192b0808,
+ 0x192b190808080808, 0x192b190808081919, 0x192b191908190808, 0x192b19190819082b,
+ 0x192b19192b081908, 0x192b2b081908082b, 0x2b08080808080808, 0x2b0808080808082b,
+ 0x2b08080808082b2b, 0x2b08080819080819, 0x2b0808082b08082b, 0x2b08081908081908,
+ 0x2b08081908192b08, 0x2b08081919080808, 0x2b08082b08190819, 0x2b08190808080819,
+ 0x2b08190808081908, 0x2b08190808190808, 0x2b08190808191919, 0x2b08190819080808,
+ 0x2b081908192b0808, 0x2b08191908080808, 0x2b0819191908192b, 0x2b0819192b191908,
+ 0x2b08192b08082b19, 0x2b08192b19080808, 0x2b08192b192b0808, 0x2b082b080808082b,
+ 0x2b082b1908081908, 0x2b082b2b08190819, 0x2b19080808081908, 0x2b19080808190808,
+ 0x2b190808082b1908, 0x2b19080819080808, 0x2b1908082b2b0819, 0x2b1908190819192b,
+ 0x2b1908192b080808, 0x2b19082b19081919, 0x2b19190808080808, 0x2b191908082b082b,
+ 0x2b19190819081908, 0x2b19191919190819, 0x2b192b082b080819, 0x2b192b19082b0808,
+ 0x2b2b08080808082b, 0x2b2b080819190808, 0x2b2b08082b081919, 0x2b2b081908082b19,
+ 0x2b2b082b08080808, 0x2b2b190808192b08, 0x2b2b2b0819190808, 0x2b2b2b1908081908,
+)
+_KSIGNS_IQ2XS = (
+ 0, 129, 130, 3, 132, 5, 6, 135, 136, 9, 10, 139, 12, 141, 142, 15,
+ 144, 17, 18, 147, 20, 149, 150, 23, 24, 153, 154, 27, 156, 29, 30, 159,
+ 160, 33, 34, 163, 36, 165, 166, 39, 40, 169, 170, 43, 172, 45, 46, 175,
+ 48, 177, 178, 51, 180, 53, 54, 183, 184, 57, 58, 187, 60, 189, 190, 63,
+ 192, 65, 66, 195, 68, 197, 198, 71, 72, 201, 202, 75, 204, 77, 78, 207,
+ 80, 209, 210, 83, 212, 85, 86, 215, 216, 89, 90, 219, 92, 221, 222, 95,
+ 96, 225, 226, 99, 228, 101, 102, 231, 232, 105, 106, 235, 108, 237, 238, 111,
+ 240, 113, 114, 243, 116, 245, 246, 119, 120, 249, 250, 123, 252, 125, 126, 255,
+)
+_KMASK_IQ2XS = (1, 2, 4, 8, 16, 32, 64, 128)
+
+assert len(_IQ2XXS_GRID) == 256 and len(_KSIGNS_IQ2XS) == 128 and len(_KMASK_IQ2XS) == 8
+
+# Grid entries as (256, 8) little-endian magnitude bytes, like the C cast
+# ``(const uint8_t *)(iq2xxs_grid + idx)``.
+_GRID_BYTES = np.array(
+ [[(g >> (8 * j)) & 0xFF for j in range(8)] for g in _IQ2XXS_GRID],
+ dtype=np.uint8,
+)
+_KSIGNS = np.array(_KSIGNS_IQ2XS, dtype=np.uint8)
+_KMASK = np.array(_KMASK_IQ2XS, dtype=np.uint8)
+
+_F32 = np.float32
+
+
+def _dequant_block(b66: np.ndarray, out: np.ndarray) -> None:
+ """Port of llama.cpp ``dequantize_row_iq2_xxs`` for one block.
+
+ Same op order in float32 (``db`` then ``db * grid * sign``) so output is
+ bit-identical to the C reference; verified by tests/test_foreign_quant_cpu.py
+ against the compiled C oracle.
+ """
+ d = _F32(b66[:2].view("<f2").astype(_F32)[0])
+ # 32 little-endian uint16 indices, assembled explicitly (endian-safe,
+ # no alignment-sensitive wider view).
+ lo = b66[2::2].astype(np.uint32)
+ hi = b66[3::2].astype(np.uint32)
+ qs = lo | (hi << np.uint32(8))
+ pos = 0
+ for ib32 in range(8): # QK_K / 32 sub-blocks of 32 values
+ a0 = qs[4 * ib32] | (qs[4 * ib32 + 1] << np.uint32(16))
+ a1 = qs[4 * ib32 + 2] | (qs[4 * ib32 + 3] << np.uint32(16))
+ a1 = int(a1)
+ db = _F32(d * _F32(0.5 + (a1 >> 28)) * _F32(0.25))
+ aux = (int(a0) & 0xFFFFFFFF).to_bytes(4, "little")
+ for elle in range(4):
+ grid = _GRID_BYTES[aux[elle]]
+ signs = int(_KSIGNS[(a1 >> (7 * elle)) & 127])
+ for j in range(8):
+ mag = _F32(int(grid[j]))
+ sgn = _F32(-1.0) if (signs & int(_KMASK[j])) else _F32(1.0)
+ out[pos] = _F32(db * mag * sgn)
+ pos += 1
+
+
+def _as_bytes(data: object) -> np.ndarray:
+ if isinstance(data, (bytes, bytearray, memoryview)):
+ return np.frombuffer(data, dtype=np.uint8)
+ return np.asarray(data, dtype=np.uint8)
+
+
+def dequant_iq2_xxs_block(block: object) -> np.ndarray:
+ """Dequantize one 66-byte IQ2_XXS block to float32 shape (256,)."""
+ b = np.ascontiguousarray(_as_bytes(block)).reshape(IQ2_XXS_BLOCK_BYTES)
+ out = np.empty(IQ2_XXS_GROUP_SIZE, dtype=_F32)
+ _dequant_block(b, out)
+ return out
+
+
+def dequant_iq2_xxs(data: object) -> np.ndarray:
+ """Dequantize IQ2_XXS payload(s) to float32.
+
+ :param data: uint8 array of shape (..., 66); one 256-value group per block.
+ :return: float32 array of shape (..., 256).
+ """
+ a = np.ascontiguousarray(_as_bytes(data))
+ if a.shape[-1] != IQ2_XXS_BLOCK_BYTES:
+ raise ValueError(f"IQ2_XXS trailing dim must be 66, got shape {a.shape}")
+ flat = a.reshape(-1, IQ2_XXS_BLOCK_BYTES)
+ out = np.empty((flat.shape[0], IQ2_XXS_GROUP_SIZE), dtype=_F32)
+ for i in range(flat.shape[0]):
+ _dequant_block(flat[i], out[i])
+ return out.reshape(np.shape(data)[:-1] + (IQ2_XXS_GROUP_SIZE,))
diff --git a/exllamav3/foreign_quant/k_quants.py b/exllamav3/foreign_quant/k_quants.py
new file mode 100644
index 0000000..98fd8ff
--- /dev/null
+++ b/exllamav3/foreign_quant/k_quants.py
@@ -0,0 +1,409 @@
+"""K-quant + IQ4_XS dequant references (ggml, numpy-only).
+
+Block layouts after llama.cpp ``ggml/src/ggml-common.h`` (MIT, ggml-org),
+decoded by ``dequantize_row_*`` in ``ggml/src/ggml-quants.c``. All formats
+use QK_K = 256 elements per super-block:
+
+- Q4_K (144 B): half dm[2] (d, dmin), scales[12] (6-bit sc/min pairs via
+ get_scale_min_k4), qs[128] (4-bit nibbles, 8 groups of 32).
+- Q5_K (176 B): dm[2], scales[12], qh[32] (extra high bit), qs[128].
+- Q6_K (210 B): ql[128] (low 4 bits), qh[64] (high 2 bits), scales[16]
+ (int8), d (half). y = d * sc * (q - 32).
+- IQ4_XS (136 B): d (half), scales_h (u16), scales_l[4], qs[128] (nibbles
+ into kvalues_iq4nl, per-32 scale ls-32).
+
+These mirror the CUDA dots in fq_gemv.cuh bit-for-bit at the integer level
+(the gate compares the CUDA q8_1-activation integer dot against
+``q8_dot_numpy`` below, which replicates the dp4a arithmetic exactly), and
+provide the fp32 dequant path for the q8-noise tolerance check.
+"""
+from __future__ import annotations
+
+import numpy as np
+
+QK_K = 256
+
+KVALUES_IQ4NL = np.array(
+ [-127, -104, -83, -65, -49, -35, -22, -10,
+ 1, 13, 25, 38, 53, 69, 89, 113], dtype=np.int32)
+
+
+def _f16(b0: int, b1: int) -> float:
+ return float(np.frombuffer(bytes((b0, b1)), dtype=np.float16)[0])
+
+
+def _get_scale_min_k4(scales: np.ndarray, j: int) -> tuple[int, int]:
+ q = [int(v) for v in scales]
+ if j < 4:
+ return q[j] & 63, q[j + 4] & 63
+ return ((q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4)), \
+ ((q[j + 4] >> 4) | ((q[j - 0] >> 6) << 4))
+
+
+def dequant_q4_K_block(block: bytes) -> np.ndarray:
+ b = np.frombuffer(block, dtype=np.uint8)
+ assert len(b) == 144
+ d = _f16(int(b[0]), int(b[1]))
+ dmin = _f16(int(b[2]), int(b[3]))
+ scales = b[4:16]
+ qs = b[16:144]
+ y = np.empty(QK_K, dtype=np.float32)
+ is_ = 0
+ p = 0
+ q = [int(v) for v in qs]
+ for j in range(0, QK_K, 64):
+ sc, m = _get_scale_min_k4(scales, is_ + 0)
+ d1, m1 = d * sc, dmin * m
+ sc, m = _get_scale_min_k4(scales, is_ + 1)
+ d2, m2 = d * sc, dmin * m
+ for l in range(32):
+ y[p] = d1 * (q[l] & 0xF) - m1
+ p += 1
+ for l in range(32):
+ y[p] = d2 * (q[l] >> 4) - m2
+ p += 1
+ qs = qs[32:]
+ q = [int(v) for v in qs]
+ is_ += 2
+ return y
+
+
+def dequant_q5_K_block(block: bytes) -> np.ndarray:
+ b = np.frombuffer(block, dtype=np.uint8)
+ assert len(b) == 176
+ d = _f16(int(b[0]), int(b[1]))
+ dmin = _f16(int(b[2]), int(b[3]))
+ scales = b[4:16]
+ qh = b[16:48]
+ qs = b[48:176]
+ y = np.empty(QK_K, dtype=np.float32)
+ is_ = 0
+ p = 0
+ u1, u2 = 1, 2
+ qhb = [int(v) for v in qh] # 32 high-bit bytes, shared across groups (u1/u2 shift)
+ for j in range(0, QK_K, 64):
+ sc, m = _get_scale_min_k4(scales, is_ + 0)
+ d1, m1 = d * sc, dmin * m
+ sc, m = _get_scale_min_k4(scales, is_ + 1)
+ d2, m2 = d * sc, dmin * m
+ ql = [int(v) for v in qs[:32]]
+ for l in range(32):
+ y[p] = d1 * ((ql[l] & 0xF) + (16 if qhb[l] & u1 else 0)) - m1
+ p += 1
+ for l in range(32):
+ y[p] = d2 * ((ql[l] >> 4) + (16 if qhb[l] & u2 else 0)) - m2
+ p += 1
+ qs = qs[32:]
+ u1 <<= 2
+ u2 <<= 2
+ is_ += 2
+ return y
+
+
+def dequant_q6_K_block(block: bytes) -> np.ndarray:
+ b = np.frombuffer(block, dtype=np.uint8)
+ assert len(b) == 210
+ ql = b[0:128]
+ qh = b[128:192]
+ sc = np.frombuffer(bytes(b[192:208]), dtype=np.int8).astype(np.int32)
+ d = _f16(int(b[208]), int(b[209]))
+ y = np.empty(QK_K, dtype=np.float32)
+ p = 0
+ for n in range(0, QK_K, 128):
+ for l in range(32):
+ is_ = l // 16
+ q1 = ((int(ql[l]) & 0xF) | (((int(qh[l]) >> 0) & 3) << 4)) - 32
+ q2 = ((int(ql[l + 32]) & 0xF) | (((int(qh[l]) >> 2) & 3) << 4)) - 32
+ q3 = ((int(ql[l]) >> 4) | (((int(qh[l]) >> 4) & 3) << 4)) - 32
+ q4 = ((int(ql[l + 32]) >> 4) | (((int(qh[l]) >> 6) & 3) << 4)) - 32
+ y[p] = d * int(sc[is_ + 0]) * q1
+ y[p + 32] = d * int(sc[is_ + 2]) * q2
+ y[p + 64] = d * int(sc[is_ + 4]) * q3
+ y[p + 96] = d * int(sc[is_ + 6]) * q4
+ p += 1
+ p += 96
+ ql, qh, sc = ql[64:], qh[32:], sc[8:]
+ return y
+
+
+def dequant_iq4_xs_block(block: bytes) -> np.ndarray:
+ b = np.frombuffer(block, dtype=np.uint8)
+ assert len(b) == 136
+ d = _f16(int(b[0]), int(b[1]))
+ scales_h = int(b[2]) | (int(b[3]) << 8)
+ scales_l = b[4:8]
+ qs = b[8:136]
+ y = np.empty(QK_K, dtype=np.float32)
+ p = 0
+ for ib in range(QK_K // 32):
+ ls = ((int(scales_l[ib // 2]) >> (4 * (ib % 2))) & 0xF) | \
+ (((scales_h >> (2 * ib)) & 3) << 4)
+ dl = d * (ls - 32)
+ for j in range(16):
+ y[p + j] = dl * int(KVALUES_IQ4NL[int(qs[j]) & 0xF])
+ y[p + j + 16] = dl * int(KVALUES_IQ4NL[int(qs[j]) >> 4])
+ p += 32
+ qs = qs[16:]
+ return y
+
+
+def dequant_row(blocks: list[bytes], fmt: str) -> np.ndarray:
+ fn = {"q4_k": dequant_q4_K_block, "q5_k": dequant_q5_K_block,
+ "q6_k": dequant_q6_K_block, "iq4_xs": dequant_iq4_xs_block}[fmt]
+ return np.concatenate([fn(b) for b in blocks]).astype(np.float32)
+
+
+def dequant_iq4_xs_bulk(raw: np.ndarray) -> np.ndarray:
+ """Vectorized IQ4_XS dequant: raw uint8 [nb, 136] -> float16 [nb, 256].
+
+ Same math as dequant_iq4_xs_block (kvalues table, per-32 ls-32 scale),
+ no per-block Python (the embedding table is ~1M blocks).
+ """
+ raw = np.ascontiguousarray(raw).reshape(-1, 136)
+ nb = raw.shape[0]
+ d = raw[:, 0:2].view(np.float16).astype(np.float32).reshape(nb, 1, 1)
+ sh = (raw[:, 2].astype(np.uint16) | (raw[:, 3].astype(np.uint16) << 8))
+ sl = raw[:, 4:8]
+ qs = raw[:, 8:136].reshape(nb, 8, 16)
+ grp = np.arange(8).reshape(1, 8)
+ ls = (((sl[:, (grp // 2).ravel()] >> (4 * (grp % 2)).ravel()) & 0xF).reshape(nb, 8) |
+ ((((sh[:, None] >> (2 * grp)) & 3) << 4).reshape(nb, 8)))
+ dl = d.reshape(nb, 1) * (ls.astype(np.float32) - 32.0)
+ lo = KVALUES_IQ4NL[(qs & 0xF).ravel()].reshape(nb, 8, 16).astype(np.float32)
+ hi = KVALUES_IQ4NL[(qs >> 4).ravel()].reshape(nb, 8, 16).astype(np.float32)
+ y = np.empty((nb, 8, 32), dtype=np.float32)
+ y[:, :, 0:16] = lo
+ y[:, :, 16:32] = hi
+ y *= dl[:, :, None]
+ return y.reshape(nb, 256).astype(np.float16)
+
+
+def dequant_q4_K_bulk(raw: np.ndarray) -> np.ndarray:
+ """Vectorized Q4_K dequant: raw uint8 [nb, 144] -> float16 [nb, 256].
+
+ Same math as dequant_q4_K_block (per-32 d*sc/m*m, 4-bit lo/hi nibbles),
+ no per-block Python (the Q4_K embedding table is ~2M blocks).
+ """
+ raw = np.ascontiguousarray(raw).reshape(-1, 144)
+ nb = raw.shape[0]
+ d = raw[:, 0:2].view(np.float16).astype(np.float32).reshape(nb)
+ dmin = raw[:, 2:4].view(np.float16).astype(np.float32).reshape(nb)
+ sc8 = raw[:, 4:16].astype(np.int32)
+ sc = np.empty((nb, 8), dtype=np.float32)
+ mn = np.empty((nb, 8), dtype=np.float32)
+ sc[:, 0:4] = sc8[:, 0:4] & 63
+ mn[:, 0:4] = sc8[:, 4:8] & 63
+ sc[:, 4:8] = ((sc8[:, 8:12] & 0xF) | ((sc8[:, 0:4] >> 6) << 4))
+ mn[:, 4:8] = ((sc8[:, 8:12] >> 4) | ((sc8[:, 4:8] >> 6) << 4))
+ dl = d[:, None] * sc
+ ml = dmin[:, None] * mn
+ qs = raw[:, 16:144].reshape(nb, 4, 32)
+ lo = (qs & 0xF).astype(np.float32)
+ hi = ((qs >> 4) & 0xF).astype(np.float32)
+ y = np.empty((nb, 256), dtype=np.float32)
+ for c in range(4):
+ y[:, c * 64:c * 64 + 32] = dl[:, 2 * c, None] * lo[:, c, :] - ml[:, 2 * c, None]
+ y[:, c * 64 + 32:c * 64 + 64] = dl[:, 2 * c + 1, None] * hi[:, c, :] - ml[:, 2 * c + 1, None]
+ return y.astype(np.float16)
+
+
+def quantize_q8_1_row(x: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+ """ggml quantize_q8_1: per-32 amax/127, round-half-away, returns (q, d, s)."""
+ x = np.asarray(x, dtype=np.float32)
+ assert x.size % 32 == 0
+ xr = x.reshape(-1, 32)
+ amax = np.abs(xr).max(axis=1)
+ d = amax / 127.0
+ q = np.zeros_like(xr, dtype=np.int32)
+ nz = amax != 0
+ q[nz] = np.floor(xr[nz] / d[nz, None] + 0.5).astype(np.int32)
+ q = np.clip(q, -127, 127)
+ s = xr.sum(axis=1)
+ return q.astype(np.int8), d.astype(np.float32), s.astype(np.float32)
+
+
+def _dp4a(a: int, b: int) -> int:
+ s = 0
+ for m in range(4):
+ av = ((a >> (8 * m)) & 0xFF) - 256 * (((a >> (8 * m)) & 0x80) >> 7)
+ bv = ((b >> (8 * m)) & 0xFF) - 256 * (((b >> (8 * m)) & 0x80) >> 7)
+ s += av * bv
+ return s
+
+
+def _u32(le_bytes) -> int:
+ v = 0
+ for m, by in enumerate(bytes(le_bytes)):
+ v |= int(by) << (8 * m)
+ return v
+
+
+def q8_dot_numpy(packed_row: bytes, x: np.ndarray, fmt: str) -> float:
+ """Exact integer replica of the CUDA q8_1-activation dots in fq_gemv.cuh.
+
+ Same op order as ggml vec_dot_*_q8_1 (int32 dp4a accumulation, one float
+ scale per chunk, float sum over chunks). Used for the bitwise gate.
+ """
+ b = np.frombuffer(packed_row, dtype=np.uint8)
+ q8, da32, _ = quantize_q8_1_row(x)
+ # CUDA stores the q8 scales as fp16 (round-to-nearest on quantize);
+ # replicate the stored values for the bitwise gate.
+ da = np.float16(da32).astype(np.float32)
+ nq8 = q8.reshape(-1, 32)
+ acc = np.float32(0.0)
+ if fmt == "q4_k":
+ assert len(b) % 144 == 0
+ nb = len(b) // 144
+ for bb in range(nb):
+ blk = b[bb * 144:(bb + 1) * 144]
+ dm = np.frombuffer(bytes(blk[0:4]), dtype=np.float16).astype(np.float32)
+ dm0 = np.float32(dm[0])
+ dm1 = np.float32(dm[1])
+ qs = blk[16:144]
+ for t in range(16):
+ bo = 2 * (t // 4)
+ qo = (t % 4)
+ v0 = _u32(qs[16 * bo + 4 * qo:16 * bo + 4 * qo + 4])
+ v1 = _u32(qs[16 * bo + 4 * qo + 16:16 * bo + 4 * qo + 20])
+ j = bo // 2
+ jm = j & 1
+ # u16 pairs, matching the CUDA reinterpret path
+ s0 = int(blk[4 + jm * 2]) | (int(blk[4 + jm * 2 + 1]) << 8)
+ s2 = int(blk[4 + (jm + 2) * 2]) | (int(blk[4 + (jm + 2) * 2 + 1]) << 8)
+ s4 = int(blk[4 + (jm + 4) * 2]) | (int(blk[4 + (jm + 4) * 2 + 1]) << 8)
+ hi = 0xFFFFFFFF if j >= 2 else 0
+ aux0 = (((s0 & 0x3F3F) & (~hi & 0xFFFF)) |
+ ((((s4 >> 0) & 0x0F0F) | ((s0 & 0xC0C0) >> 2)) & (hi & 0xFFFF))) & 0xFFFF
+ aux1 = (((s2 & 0x3F3F) & (~hi & 0xFFFF)) |
+ ((((s4 >> 4) & 0x0F0F) | ((s2 & 0xC0C0) >> 2)) & (hi & 0xFFFF))) & 0xFFFF
+ sc = [aux0 & 0xFF, (aux0 >> 8) & 0xFF]
+ mm = [aux1 & 0xFF, (aux1 >> 8) & 0xFF]
+ sumf_d = np.float32(0.0)
+ sumf_m = np.float32(0.0)
+ for i in range(2):
+ v0i = (v0 >> (4 * i)) & 0x0F0F0F0F
+ v1i = (v1 >> (4 * i)) & 0x0F0F0F0F
+ qb = bb * 8 + bo + i
+ aqb = nq8[qb].tobytes()
+ u0 = _u32(aqb[4 * qo:4 * qo + 4])
+ u1 = _u32(aqb[16 + 4 * qo:16 + 4 * qo + 4])
+ d8 = np.float32(da[qb])
+ dot1 = _dp4a(v0i, u0) + _dp4a(v1i, u1)
+ dot2 = _dp4a(0x01010101, u0) + _dp4a(0x01010101, u1)
+ sumf_d = np.float32(sumf_d + np.float32(d8 * np.float32(dot1 * sc[i])))
+ sumf_m = np.float32(sumf_m + np.float32(d8 * np.float32(dot2 * mm[i])))
+ m0 = np.float32(dm0 * sumf_d)
+ m1 = np.float32(dm1 * sumf_m)
+ acc = np.float32(acc + np.float32(m0 + np.float32(-m1)))
+ return float(acc)
+ if fmt == "q5_k":
+ assert len(b) % 176 == 0
+ nb = len(b) // 176
+ for bb in range(nb):
+ blk = b[bb * 176:(bb + 1) * 176]
+ dm = np.frombuffer(bytes(blk[0:4]), dtype=np.float16).astype(np.float32)
+ dm0 = np.float32(dm[0])
+ dm1 = np.float32(dm[1])
+ qh = blk[16:48]
+ qs = blk[48:176]
+ for t in range(16):
+ bo = 2 * (t // 4)
+ qo = (t % 4)
+ vl0 = _u32(qs[16 * bo + 4 * qo:16 * bo + 4 * qo + 4])
+ vl1 = _u32(qs[16 * bo + 4 * qo + 16:16 * bo + 4 * qo + 20])
+ vh0 = _u32(qh[4 * qo:4 * qo + 4]) >> bo
+ vh1 = _u32(qh[4 * qo + 16:4 * qo + 20]) >> bo
+ j = bo // 2
+ jm = j & 1
+ s0 = int(blk[4 + jm * 2]) | (int(blk[4 + jm * 2 + 1]) << 8)
+ s2 = int(blk[4 + (jm + 2) * 2]) | (int(blk[4 + (jm + 2) * 2 + 1]) << 8)
+ s4 = int(blk[4 + (jm + 4) * 2]) | (int(blk[4 + (jm + 4) * 2 + 1]) << 8)
+ hi = 0xFFFFFFFF if j >= 2 else 0
+ aux0 = (((s0 & 0x3F3F) & (~hi & 0xFFFF)) |
+ ((((s4 >> 0) & 0x0F0F) | ((s0 & 0xC0C0) >> 2)) & (hi & 0xFFFF))) & 0xFFFF
+ aux1 = (((s2 & 0x3F3F) & (~hi & 0xFFFF)) |
+ ((((s4 >> 4) & 0x0F0F) | ((s2 & 0xC0C0) >> 2)) & (hi & 0xFFFF))) & 0xFFFF
+ sc = [aux0 & 0xFF, (aux0 >> 8) & 0xFF]
+ mm = [aux1 & 0xFF, (aux1 >> 8) & 0xFF]
+ sumf_d = np.float32(0.0)
+ sumf_m = np.float32(0.0)
+ for i in range(2):
+ v0i = ((vl0 >> (4 * i)) & 0x0F0F0F0F) | ((((vh0 >> i) << 4) & 0x10101010))
+ v1i = ((vl1 >> (4 * i)) & 0x0F0F0F0F) | ((((vh1 >> i) << 4) & 0x10101010))
+ qb = bb * 8 + bo + i
+ aqb = nq8[qb].tobytes()
+ u0 = _u32(aqb[4 * qo:4 * qo + 4])
+ u1 = _u32(aqb[16 + 4 * qo:16 + 4 * qo + 4])
+ d8 = np.float32(da[qb])
+ dot1 = _dp4a(v0i, u0) + _dp4a(v1i, u1)
+ dot2 = _dp4a(0x01010101, u0) + _dp4a(0x01010101, u1)
+ sumf_d = np.float32(sumf_d + np.float32(d8 * np.float32(dot1 * sc[i])))
+ sumf_m = np.float32(sumf_m + np.float32(d8 * np.float32(dot2 * mm[i])))
+ m0 = np.float32(dm0 * sumf_d)
+ m1 = np.float32(dm1 * sumf_m)
+ acc = np.float32(acc + np.float32(m0 + np.float32(-m1)))
+ return float(acc)
+ if fmt == "q6_k":
+ assert len(b) % 210 == 0
+ nb = len(b) // 210
+ for bb in range(nb):
+ blk = b[bb * 210:(bb + 1) * 210]
+ ql = blk[0:128]
+ qhb = blk[128:192]
+ sc = np.frombuffer(bytes(blk[192:208]), dtype=np.int8).astype(np.int32)
+ d = float(np.frombuffer(bytes(blk[208:210]), dtype=np.float16)[0])
+ df = np.float32(d)
+ for s8 in range(32):
+ iqs = s8
+ bo = 4 * (iqs // 16) + (iqs % 16) // 8
+ sco = 8 * (iqs // 16) + (iqs % 16) // 4
+ vsh = 2 * ((iqs % 16) // 8)
+ vl = _u32(ql[4 * iqs:4 * iqs + 4])
+ vh = _u32(qhb[4 * (8 * (iqs // 16) + iqs % 8):4 * (8 * (iqs // 16) + iqs % 8) + 4]) >> vsh
+ sumf = np.float32(0.0)
+ for i in range(2):
+ scc = int(sc[sco + 4 * i])
+ vil = (vl >> (4 * i)) & 0x0F0F0F0F
+ vih = ((vh >> (4 * i)) << 4) & 0x30303030
+ vi = 0
+ for mm_ in range(4):
+ vb = ((((vil >> (8 * mm_)) & 0xFF) + (((vih >> (8 * mm_)) & 0xFF))) - 0x20) & 0xFF
+ vi |= vb << (8 * mm_)
+ qb = bb * 8 + bo + 2 * i
+ aqb = nq8[qb].tobytes()
+ u = _u32(aqb[4 * (iqs % 8):4 * (iqs % 8) + 4])
+ d8 = np.float32(da[qb])
+ sumf = np.float32(sumf + np.float32(d8 * np.float32(_dp4a(vi, u) * scc)))
+ acc = np.float32(acc + np.float32(df * sumf))
+ return float(acc)
+ if fmt == "iq4_xs":
+ assert len(b) % 136 == 0
+ nb = len(b) // 136
+ for bb in range(nb):
+ blk = b[bb * 136:(bb + 1) * 136]
+ dw = float(np.frombuffer(bytes(blk[0:2]), dtype=np.float16)[0])
+ dwf = np.float32(dw)
+ sh = int(blk[2]) | (int(blk[3]) << 8)
+ sl = blk[4:8]
+ qs = blk[8:136]
+ for sub in range(8):
+ iqs = 4 * sub
+ ls = ((int(sl[sub // 2]) >> (4 * (sub % 2))) & 0xF) | \
+ (((sh >> (2 * sub)) & 3) << 4)
+ qb = bb * 8 + sub
+ dah = np.float32(da[qb])
+ aq = nq8[qb].tobytes()
+ sumi = 0
+ for j in range(4):
+ aux = _u32(qs[4 * (iqs + j):4 * (iqs + j) + 4])
+ vx, vy = 0, 0
+ for k in range(4):
+ vx |= (int(KVALUES_IQ4NL[(aux >> (8 * k)) & 0xF]) & 0xFF) << (8 * k)
+ vy |= (int(KVALUES_IQ4NL[(aux >> (8 * k + 4)) & 0xF]) & 0xFF) << (8 * k)
+ u0 = _u32(aq[4 * j:4 * j + 4])
+ u1 = _u32(aq[4 * (j + 4):4 * (j + 4) + 4])
+ sumi += _dp4a(vx & 0xFFFFFFFF, u0) + _dp4a(vy & 0xFFFFFFFF, u1)
+ sumi *= ls - 32
+ acc = np.float32(acc + np.float32(np.float32(dwf * dah) * np.float32(sumi)))
+ return float(acc)
+ raise ValueError(fmt)
diff --git a/exllamav3/foreign_quant/nvfp4.py b/exllamav3/foreign_quant/nvfp4.py
new file mode 100644
index 0000000..78a79c3
--- /dev/null
+++ b/exllamav3/foreign_quant/nvfp4.py
@@ -0,0 +1,93 @@
+"""NVFP4 (ModelOpt W4A16) dequant reference, numpy-only.
+
+Per 16-element group, NVIDIA ModelOpt's NVFP4 stores (see the Bolt
+``hf_quant_config.json``: ``W4A16_NVFP4``, ``group_size 16``):
+
+* 4-bit E2M1 payloads (OCP Microscaling E2M1, finite: ``0x7 -> +6``,
+ ``0xF -> -6``, no NaN/Inf), two per byte, **low nibble = even index**
+ (ModelOpt packing convention);
+* one fp8 E4M3 per-group scale (OCP: ``0x38 -> 1.0``, ``0x7E -> 448``,
+ NaN only at ``0x7F``/``0xFF``);
+* one fp32 global scale per tensor (``weight_scale_2``).
+
+Decoded as ``w = e2m1(q) * scale_fp8 * scale_global``.
+
+In the Bolt safetensors, e.g. ``layers.0.mixer.in_proj``::
+
+ weight U8 [18560, 2048] # [out, in/2] packed E2M1
+ weight_scale F8_E4M3 [18560, 256] # [out, in/16] per-group scales
+ weight_scale_2 F32 [] # global scale
+
+E2M1/E4M3 codebooks follow the OCP Microscaling Formats specification and are
+cross-checked against ``ml_dtypes`` (``float4_e2m1fn`` / ``float8_e4m3fn``) in
+tests/test_foreign_quant_cpu.py.
+"""
+from __future__ import annotations
+
+import numpy as np
+
+NVFP4_GROUP_SIZE = 16
+
+# OCP MX E2M1 (finite variant): index = nibble value.
+E2M1_LUT = (
+ 0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0,
+ -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0,
+)
+
+_E2M1 = np.array(E2M1_LUT, dtype=np.float32)
+
+
+def _as_bytes(data: object) -> np.ndarray:
+ if isinstance(data, (bytes, bytearray, memoryview)):
+ return np.frombuffer(data, dtype=np.uint8)
+ return np.asarray(data, dtype=np.uint8)
+
+
+def e4m3_to_float32(data: object) -> np.ndarray:
+ """Decode fp8 E4M3 bytes to float32 (OCP: bias behaves as 7 for e<=14,
+ e==15 is normal with exponent 8; NaN only at 0x7F/0xFF)."""
+ b = np.ascontiguousarray(_as_bytes(data))
+ e = ((b >> 3) & 0xF).astype(np.int32)
+ m = (b & 0x7).astype(np.float32)
+ is_nan = (e == 15) & (m == 7)
+ is_zero = (e == 0) & (m == 0)
+ is_sub = (e == 0) & (m != 0)
+ # Normal (incl. e==15, m!=7): 2**(e-7) * (1 + m/8); subnormal: m * 2**-9.
+ vals = np.ldexp(1.0 + m / np.float32(8.0), e - 7).astype(np.float32)
+ vals = np.where(is_sub, m * np.float32(2.0 ** -9), vals)
+ vals = np.where(is_zero, np.float32(0.0), vals)
+ vals = np.where(is_nan, np.float32(np.nan), vals)
+ sign = np.where((b >> 7) != 0, np.float32(-1.0), np.float32(1.0))
+ return (vals * sign).astype(np.float32)
+
+
+def unpack_e2m1(packed: object) -> np.ndarray:
+ """Unpack E2M1 nibbles to float32, low nibble = even index.
+
+ :param packed: uint8 array (..., K/2).
+ :return: float32 array (..., K).
+ """
+ p = np.ascontiguousarray(_as_bytes(packed))
+ lo = _E2M1[p & 0xF]
+ hi = _E2M1[(p >> 4) & 0xF]
+ out = np.empty(p.shape + (2,), dtype=np.float32)
+ out[..., 0] = lo
+ out[..., 1] = hi
+ return out.reshape(p.shape[:-1] + (p.shape[-1] * 2,))
+
+
+def dequant_nvfp4(packed: object, scales_fp8: object, global_scale: float) -> np.ndarray:
+ """Dequantize a ModelOpt NVFP4 tensor to float32.
+
+ :param packed: uint8 array (..., K/2), two E2M1 values per byte.
+ :param scales_fp8: uint8 array (..., K/16), one E4M3 scale per 16 values.
+ :param global_scale: fp32 ``weight_scale_2`` scalar.
+ :return: float32 array (..., K).
+ """
+ p = np.ascontiguousarray(_as_bytes(packed))
+ s = np.ascontiguousarray(_as_bytes(scales_fp8))
+ if p.shape[-1] * 2 != s.shape[-1] * NVFP4_GROUP_SIZE or p.shape[:-1] != s.shape[:-1]:
+ raise ValueError(f"NVFP4 shape mismatch: packed {p.shape} vs scales {s.shape}")
+ vals = unpack_e2m1(p)
+ gscales = np.repeat(e4m3_to_float32(s), NVFP4_GROUP_SIZE, axis=-1)
+ return vals * gscales * np.float32(global_scale)
diff --git a/exllamav3/foreign_quant/q8_0.py b/exllamav3/foreign_quant/q8_0.py
new file mode 100644
index 0000000..c15bf1a
--- /dev/null
+++ b/exllamav3/foreign_quant/q8_0.py
@@ -0,0 +1,57 @@
+"""Q8_0 dequant reference (ggml, numpy-only).
+
+Block layout (34 bytes, groups of 32 values), after llama.cpp
+``ggml/src/ggml-common.h`` (MIT License, Copyright (c) llama.cpp contributors,
+https://github.com/ggml-org/llama.cpp)::
+
+ typedef struct { ggml_half d; int8_t qs[32]; } block_q8_0;
+
+i.e. a little-endian fp16 scale followed by 32 int8 residuals, decoded by
+``dequantize_row_q8_0`` (``ggml/src/ggml-quants.c``) as ``y[j] = qs[j] * d``.
+
+In the Bolt safetensors, Q8_0 tensors are stored as raw bytes with shape
+``[..., num_blocks, 34]`` (e.g. ``lm_head`` is U8 ``[131072, 128, 34]``).
+"""
+from __future__ import annotations
+
+import numpy as np
+
+Q8_0_GROUP_SIZE = 32
+Q8_0_BLOCK_BYTES = 34
+
+
+def _as_bytes(data: object) -> np.ndarray:
+ if isinstance(data, (bytes, bytearray, memoryview)):
+ return np.frombuffer(data, dtype=np.uint8)
+ return np.asarray(data, dtype=np.uint8)
+
+
+def _as_block_array(data: object) -> np.ndarray:
+ """Raw payload as a contiguous uint8 array with trailing dim 34."""
+ a = np.ascontiguousarray(_as_bytes(data))
+ if a.shape[-1] != Q8_0_BLOCK_BYTES:
+ raise ValueError(f"Q8_0 trailing dim must be 34, got shape {a.shape}")
+ return a.reshape(-1, Q8_0_BLOCK_BYTES)
+
+
+def dequant_q8_0_block(block: object) -> np.ndarray:
+ """Dequantize one 34-byte Q8_0 block to float32 shape (32,)."""
+ flat = _as_block_array(block)
+ if flat.shape[0] != 1:
+ raise ValueError(f"Expected a single block, got shape {flat.shape}")
+ return dequant_q8_0(flat).reshape(Q8_0_GROUP_SIZE)
+
+
+def dequant_q8_0(data: object) -> np.ndarray:
+ """Dequantize Q8_0 payload(s) to float32.
+
+ :param data: uint8 array of shape (..., 34); one 32-value group per block.
+ :return: float32 array of shape (..., 32).
+ """
+ flat = _as_block_array(data)
+ # First two bytes: little-endian fp16 scale (GGML_FP16_TO_FP32).
+ scales = flat[:, :2].copy().view("<f2").reshape(-1).astype(np.float32)
+ # Remaining 32 bytes: signed residuals.
+ quants = flat[:, 2:].copy().view(np.int8).astype(np.float32)
+ out = quants * scales[:, None]
+ return out.reshape(np.shape(data)[:-1] + (Q8_0_GROUP_SIZE,))
diff --git a/exllamav3/generator/chunk_il.py b/exllamav3/generator/chunk_il.py
new file mode 100644
index 0000000..f954a24
--- /dev/null
+++ b/exllamav3/generator/chunk_il.py
@@ -0,0 +1,183 @@
+"""EXL3_SCHED_CHUNK_IL=1 (default off): chunked-prefill interleave planner. Pure python (no torch), importable without a GPU.
+
+The engine already prefills in chunks (EXL3_PREFILL_CHUNK, 4096 rows; Job.prefill runs ONE chunk per Generator.iterate()
+step and keeps kv_position / pages / recurrent slot between steps). This planner only decides, per step, WHICH jobs may run
+their next chunk, so a big prefill (the "leader": first-arrived unfinished prefill with more than EXL3_CIL_SHORT_TOK rows left)
+alternates with the queued short work of other jobs:
+
+ shorts slice : leader parked, the other jobs run (short prefills, ONE batch-1 decode per step) for up to EXL3_CIL_SLICE_S s
+ leader chunk : exactly one leader chunk; every other job is parked / held, so the chunk does not share its step with them
+ ... repeat until the leader's deferral budget is used, then leader chunks only (= FIFO order) until its prefill is done.
+
+Hard bound: the leader's deferral (wall time of steps in which it did not run) is capped per leader by
+min(EXL3_CIL_MAX_DEFER_S, EXL3_CIL_DEFER_FRAC x its estimated prefill time), so a smaller big prefill pays a proportionally
+smaller price (default 8 s and 18 %: a 45K prefill of 36 s defers at most 6.5 s, an 8K one of 6.5 s at most 1.2 s). A slice step
+runs the oldest short prefills whose rows still fit: used + estimated_cost(step) <= budget (cost = rows to prefill x measured
+s/row of the leader's own chunks + EXL3_CIL_DECODE_S per decode step), so the overshoot is the estimate error of one step, not one
+whole short request. A second big prefill is parked while the leader prefills (FIFO order between bigs, no round-robin between
+equals). With fewer than two active jobs nothing is parked or held (single-user path untouched).
+
+Only WHEN a chunk runs changes: chunk boundaries come from the job's own kv_position, never from other jobs, so the sequence of
+chunk calls of every job is the one of the non-interleaved path (tests: test_chunk_il.py).
+"""
+from __future__ import annotations
+
+import logging
+import os
+import time
+from typing import Any, NamedTuple
+
+
+def chunk_il_enabled() -> bool:
+ return os.environ.get("EXL3_SCHED_CHUNK_IL", "0") == "1"
+
+
+class View(NamedTuple):
+ key: Any # stable job identity (arrival order = sort order of `order`)
+ order: int # arrival rank (Job.serial_number)
+ remaining: int # prompt rows still to prefill (0 once prefill is done)
+ done: bool # prefill done = decode-ready
+ next_rows: int # rows its next prefill chunk will take (0 when done)
+ kv: int # kv_position now (progress measure for the s/row estimate)
+
+
+class Plan(NamedTuple):
+ parked: set # keys that skip prefill this step
+ mode: str | None # None (no interleave), 'shorts', 'chunk'
+ leader: Any
+
+
+class _Leader:
+ def __init__(self, key: Any, kv: int, now: float):
+ self.key = key
+ self.mode = None
+ self.used = 0.0 # deferral so far (s)
+ self.slice_used = 0.0
+ self.t_last = now
+ self.kv_last = kv
+ self.slices = 0
+ self.chunks = 0
+ self.rows_chunked = 0
+ self.t_start = now
+ self.rows = 0 # prompt rows left when it took the lead (budget base)
+
+
+class ChunkPlanner:
+ def __init__(self, short_tok: int | None = None, max_defer_s: float | None = None, slice_s: float | None = None,
+ row_s: float | None = None, decode_s: float | None = None, single_decode: bool | None = None,
+ defer_frac: float | None = None, clock=time.monotonic) -> None:
+ e = os.environ.get
+ self.short_tok = int(e("EXL3_CIL_SHORT_TOK", "4096")) if short_tok is None else short_tok
+ self.max_defer_s = float(e("EXL3_CIL_MAX_DEFER_S", "8")) if max_defer_s is None else max_defer_s
+ self.defer_frac = float(e("EXL3_CIL_DEFER_FRAC", "0.18")) if defer_frac is None else defer_frac
+ self.slice_s = float(e("EXL3_CIL_SLICE_S", "0.6")) if slice_s is None else slice_s
+ self.row_s = float(e("EXL3_CIL_ROW_S", "0.0007")) if row_s is None else row_s # 2.9 s per 4096-row chunk until measured
+ self.decode_s = float(e("EXL3_CIL_DECODE_S", "0.05")) if decode_s is None else decode_s
+ self.single_decode = (e("EXL3_CIL_SINGLE_DECODE", "1") != "0") if single_decode is None else single_decode
+ self._clock = clock
+ self._lead: _Leader | None = None
+ self._resync = False
+ self._tick = 0
+ self._last_decoded: dict[Any, int] = {}
+ self.finished: list[dict] = [] # stats of the last leaders that completed (bounded)
+
+ # ---- helpers
+ def _stats(self, ld: _Leader, now: float) -> dict:
+ return {"deferred_s": round(ld.used, 4), "budget_s": round(self._budget(ld), 3), "slices": ld.slices, "chunks": ld.chunks,
+ "span_s": round(now - ld.t_start, 3), "row_s": round(self.row_s, 6)}
+
+ def _budget(self, ld: _Leader) -> float:
+ """Deferral allowed for this leader: a fraction of its estimated prefill time (rows left when it took the lead x measured
+ s/row), never more than the absolute cap. Fraction 0 = the cap alone."""
+ if self.defer_frac <= 0:
+ return self.max_defer_s
+ return min(self.max_defer_s, self.defer_frac * ld.rows * self.row_s)
+
+ def _pick(self, shorts: list[View], room: float) -> set:
+ """Keys of the shorts a slice step runs: the oldest prefills whose rows still fit in `room` (s of deferral left), plus the
+ decode of the ready ones. Empty when not even one of them fits."""
+ ready = {v.key for v in shorts if v.done}
+ cost = self.decode_s if ready else 0.0
+ run = set()
+ for v in sorted((v for v in shorts if not v.done), key=lambda v: v.order):
+ c = v.next_rows * self.row_s
+ if cost + c <= room:
+ run.add(v.key)
+ cost += c
+ return (run | ready) if run or cost <= room else set()
+
+ def solo(self) -> None:
+ """The generator ran a step with fewer than two active jobs and did not call the planner. The time and progress of those steps
+ are not interleave time: the next plan re-bases the leader's clock instead of charging them to its deferral or to the
+ s/row estimate."""
+ self._resync = self._lead is not None
+
+ # ---- prefill round
+ def plan_prefill(self, views: list[View]) -> Plan:
+ now = self._clock()
+ self._tick += 1
+ live = [v for v in views if not v.done]
+ ld = self._lead
+ if ld is not None and not any(v.key == ld.key and not v.done for v in views):
+ self.finished = self.finished[-15:] + [self._stats(ld, now)] # leader finished its prefill (or left): the interleave is over
+ logging.info("chunk_il leader done %s", self.finished[-1])
+ self._lead = ld = None
+ if ld is None:
+ bigs = sorted((v for v in live if v.remaining > self.short_tok), key=lambda v: v.order)
+ if not bigs:
+ return Plan(set(), None, None)
+ lv = bigs[0]
+ ld = self._lead = _Leader(lv.key, lv.kv, now)
+ ld.rows = lv.remaining
+ lv = next(v for v in views if v.key == ld.key)
+ others = [v for v in views if v.key != ld.key]
+ if not others:
+ ld.t_last, ld.kv_last = now, lv.kv
+ return Plan(set(), None, ld.key)
+ if self._resync:
+ self._resync = False
+ ld.t_last, ld.kv_last, ld.mode = now, lv.kv, None
+ dt = max(now - ld.t_last, 0.0)
+ if ld.mode == "shorts":
+ ld.used += dt
+ ld.slice_used += dt
+ elif ld.mode == "chunk" and lv.kv > ld.kv_last and dt > 0:
+ rows = lv.kv - ld.kv_last # the leader's own chunk(s) since the last step: measured s/row
+ ld.chunks += 1
+ ld.rows_chunked += rows
+ self.row_s = 0.5 * self.row_s + 0.5 * (dt / rows)
+ ld.t_last, ld.kv_last = now, lv.kv
+ bigs_other = [v for v in others if not v.done and v.remaining > self.short_tok]
+ shorts = [v for v in others if v not in bigs_other]
+ budget = self._budget(ld)
+ # next mode
+ run = self._pick(shorts, budget - ld.used)
+ fits = bool(run)
+ if ld.mode in (None, "chunk"):
+ if fits:
+ ld.mode, ld.slice_used = "shorts", 0.0
+ ld.slices += 1
+ else:
+ ld.mode = "chunk"
+ elif not fits or ld.slice_used >= self.slice_s: # 'shorts' continues until its slice / the budget is spent
+ ld.mode = "chunk"
+ if ld.mode == "shorts":
+ return Plan({ld.key} | {v.key for v in others if not v.done and v.key not in run}, "shorts", ld.key)
+ return Plan({v.key for v in others if not v.done}, ld.mode, ld.key)
+
+ # ---- generation round (after the prefill round: jobs that just finished their prefill are decode-ready)
+ def plan_decode(self, views: list[View], plan: Plan) -> set:
+ """Keys of decode-ready jobs held this step."""
+ if plan.mode is None:
+ return set()
+ ready = [v for v in views if v.done and v.key != plan.leader] # the leader (just finished) decodes at once
+ if plan.mode == "chunk":
+ return {v.key for v in ready} # the leader chunk does not share its step with a decode
+ if not self.single_decode or len(ready) <= 1:
+ return set()
+ run = min(ready, key=lambda v: (self._last_decoded.get(v.key, -1), v.order)) # one batch-1 decode, least recently served
+ self._last_decoded[run.key] = self._tick
+ if len(self._last_decoded) > 64:
+ alive = {v.key for v in views}
+ self._last_decoded = {k: t for k, t in self._last_decoded.items() if k in alive}
+ return {v.key for v in ready if v.key != run.key}
diff --git a/exllamav3/generator/generator.py b/exllamav3/generator/generator.py
index 5d0a1eb..162d7d1 100644
--- a/exllamav3/generator/generator.py
+++ b/exllamav3/generator/generator.py
@@ -19,6 +19,7 @@ from ..util.memory import malloc_trim
from .pagetable import PageTable, is_content_hash
from .cpu_cache import CPUPageCache
from .draft_confidence import DraftConfidenceCalibrator
+from . import chunk_il
from .job import Job, _ttrace_begin, _ttrace_end, _TAIL_REPLY as _TAIL_REPLY_GEN
# EXL3_REPLY_FIRST=1 (default off): a job that finishes inside iterate() is released (deallocate_pages: reply-end tail
# stash, draft flush, page / slot release) by flush_deferred() AFTER its last results are returned, not before. The server calls it
@@ -27,6 +28,8 @@ from .job import Job, _ttrace_begin, _ttrace_end, _TAIL_REPLY as _TAIL_REPLY_GEN
_REPLY_FIRST = os.environ.get("EXL3_REPLY_FIRST", "0") == "1"
from . import spec_sample
from .filter import Filter
+from .row_groups import plan_groups, group_rows_cap, GROUPS as ROW_GROUPS
+from ..util.row_inv import ROW_INV
from concurrent.futures import ThreadPoolExecutor
from .sampler import Sampler
from .visualizer import CacheVisualizer
@@ -260,6 +263,9 @@ class Generator:
if max_chunk_size > 65535:
raise ValueError(f"prefill chunk of {max_chunk_size} rows is not supported: a forward is limited to 65535 rows (mixer kernel grid.y); lower EXL3_PREFILL_CHUNK / max_chunk_size")
self.max_chunk_size = max_chunk_size
+ # Constructed chunk size: a caller that lowers max_chunk_size at runtime (decode-priority prefill while other
+ # jobs decode, e.g. a serving loop) gets exactly that chunk; adaptive big chunks apply only at this size
+ self.base_chunk_size = max_chunk_size
# Job queues
self.job_serial = 0
@@ -309,6 +315,11 @@ class Generator:
# Exact prompt-end checkpoints (see Job._tail_stash); EXL3_TAIL_CKPT=0 turns them off
self.tail_ckpts = []
self.tail_ckpt_max = int(os.environ.get("EXL3_TAIL_CKPT", "8")) if tail_ckpt is None else int(tail_ckpt)
+ # Sub-page prompt-tail checkpoints (EXL3_TAIL_SUB, see Job.sub_ckpt_rows): same entry format as tail_ckpts, kept in
+ # their own list so a long prompt's several entries never push the exact prompt-end checkpoints out. Host memory
+ # bound = sub_ckpt_max x one checkpoint (142 MiB on the KDA model, 75 MiB on the GDN one), oldest dropped first
+ self.sub_ckpts = []
+ self.sub_ckpt_max = max(0, int(os.environ.get("EXL3_TAIL_SUB_MAX", "8"))) # 0 = keep no sub-page entry
# prompts shorter than this never stash (the stash is 20-40 ms of host copy and 142 MiB per entry)
self.tail_ckpt_min = int(os.environ.get("EXL3_TAIL_MIN", "512"))
@@ -357,6 +368,23 @@ class Generator:
self.draft_calibrator = DraftConfidenceCalibrator(draft_confidence)
+ def wide_prefill_chunks(self) -> tuple[bool, bool]:
+ """(attention-only state, fused MoE). attention-only: the recurrent layers are all sliding-window attention rings
+ (no GDN / KDA state, whose checkpoint cadence the chunk plan protects). fused MoE: CUDA block-sparse MoE layers
+ with the fused prefill kernel, which gets more rows per expert from wider chunks."""
+ v = getattr(self, "_wide_prefill_chunks", None)
+ if v is None:
+ from ..modules.block_sparse_mlp import BlockSparseMLP
+ from ..modules.sliding_attn import SlidingAttention
+ swa_only = all(isinstance(m, SlidingAttention) for m in self.model.get_recurrent_layers())
+ moe = not torch.version.hip and any(
+ isinstance(m, BlockSparseMLP) and getattr(m, "fused_mode_buffers", None) is not None
+ for m in self.model
+ )
+ v = self._wide_prefill_chunks = (swa_only, moe)
+ return v
+
+
def num_remaining_jobs(self):
return len(self.pending_jobs) + len(self.active_jobs)
@@ -557,6 +585,79 @@ class Generator:
_moe_fused_check(self.model)
return results
+ def _cil_views(self) -> list:
+ views = []
+ for job in self.active_jobs:
+ seq = job.sequences[0]
+ done = job.is_prefill_done()
+ cur = max(seq.kv_position, job.cached_pages * PAGE_SIZE)
+ if not done and job.time_first_prefill is None:
+ # no step has run yet: the first one may jump to a tail checkpoint (Job._tail_restore), so a follow-up turn on a
+ # long cached conversation is SHORT, not "big". Peeked once per job (read-only), else it would be parked for good.
+ peek = getattr(job, "_cil_peek", None)
+ if peek is None:
+ try:
+ peek = job._tail_peek(seq)
+ except Exception: # noqa: BLE001
+ peek = 0
+ job._cil_peek = peek
+ cur = max(cur, peek)
+ left = 0 if done else max(len(seq.sequence_ids) - 1 - cur, 0)
+ views.append(chunk_il.View(id(job), job.serial_number, left, done,
+ 0 if done else min(left, self.max_chunk_size), seq.kv_position))
+ return views
+
+ def _cil_parked(self) -> list:
+ """
+ EXL3_SCHED_CHUNK_IL=1: chunked-prefill interleave (chunk_il.ChunkPlanner). Returns the jobs that skip their prefill chunk
+ this step (sets job._cil_skip for the speculation policy, which counts only unparked jobs). Any planner
+ error switches the interleave off for the process (one warning) and serves as without the flag.
+ """
+ for job in self.active_jobs:
+ job._cil_skip = False
+ job._cil_hold = False
+ if getattr(self, "_cil_broken", False) or len(self.active_jobs) < 2:
+ self._cil_plan = None
+ if getattr(self, "_cil", None) is not None:
+ self._cil.solo() # these steps are not interleave time
+ return []
+ try:
+ if getattr(self, "_cil", None) is None:
+ self._cil = chunk_il.ChunkPlanner()
+ views = self._cil_views()
+ self._cil_plan = self._cil.plan_prefill(views)
+ parked = [j for j in self.active_jobs if id(j) in self._cil_plan.parked and not j.is_prefill_done()]
+ except Exception as e: # noqa: BLE001
+ logging.warning("EXL3_SCHED_CHUNK_IL disabled (%r); serving without it", e)
+ self._cil_broken, self._cil_plan = True, None
+ return []
+ for job in parked:
+ job._cil_skip = True
+ return parked
+
+ def _cil_hold(self) -> None:
+ """Generation round: decode-ready jobs the plan holds this step read as not prefill-done (Job._cil_hold), which every
+ draft/verify/sample loop already skips. Undone by _cil_release() at the end of iterate()."""
+ plan = getattr(self, "_cil_plan", None)
+ if plan is None or plan.mode is None or not chunk_il.chunk_il_enabled():
+ return
+ try:
+ held = self._cil.plan_decode(self._cil_views(), plan)
+ except Exception as e: # noqa: BLE001
+ logging.warning("EXL3_SCHED_CHUNK_IL disabled (%r); serving without it", e)
+ self._cil_broken, self._cil_plan = True, None
+ return
+ for job in self.active_jobs:
+ if id(job) in held:
+ job._cil_hold = True
+ job._cil_skip = True
+
+ def _cil_release(self) -> None:
+ if getattr(self, "_cil_plan", None) is None:
+ return
+ for job in self.active_jobs:
+ job._cil_hold = False
+
def _iterate_inner(self) -> list[dict]:
"""
Performs inference on available jobs.
@@ -644,7 +745,10 @@ class Generator:
# Perform one round of prefill
_t0 = _ttrace_begin()
+ parked = self._cil_parked() if chunk_il.chunk_il_enabled() else ()
for job in list(self.active_jobs):
+ if job in parked:
+ continue
try:
job.prefill(results)
except Exception as e:
@@ -658,6 +762,7 @@ class Generator:
if self.recurrent_cache is not None:
self.recurrent_checkpoint()
_ttrace_end("recurrent_checkpoint", _t0)
+ self._cil_hold()
_t0 = _ttrace_begin()
# Generation with draft model
@@ -691,6 +796,7 @@ class Generator:
self.update_visualizer()
# Finished iteration
+ self._cil_release()
return results
@@ -830,6 +936,7 @@ class Generator:
def clear_prompt_ckpts(self):
"""Drop every prompt-end recurrent checkpoint (host memory, ~142 MiB each)."""
self.tail_ckpts.clear()
+ self.sub_ckpts.clear()
def _flush_mtp_defer(self, job, with_tail: bool):
@@ -1267,6 +1374,47 @@ class Generator:
return buf[:rows]
+ def _row_groups(self, batch_jobs: list, width: int) -> list[tuple[int, int]]:
+ """Job ranges of the forwards that carry one multi-job decode step (see row_groups.py). Every range holds at
+ most the exact-path row count, so each row gets the bits it would get decoded alone."""
+ return plan_groups([len(job.sequences) for job in batch_jobs], width, group_rows_cap())
+
+ def _forward_groups(self, batch_ids: torch.Tensor, params: dict, batch_jobs: list,
+ groups: list[tuple[int, int]], own_pages: list | None) -> torch.Tensor:
+ """One model forward per job group, concatenated in batch order. A group of several rows runs the verify
+ kernels (params["dflash_verify"]) also when nothing is drafted: the R-row exact paths give each row the bits
+ of the one-row launch. params["export_states"] of the whole step is rebuilt from the groups' lists."""
+ logits = []
+ exports = []
+ r0 = 0
+ for j0, j1 in groups:
+ r1 = r0 + sum(len(job.sequences) for job in batch_jobs[j0:j1])
+ p = dict(params)
+ p["block_table"] = params["block_table"][r0:r1]
+ p["cache_seqlens"] = params["cache_seqlens"][r0:r1]
+ if params.get("positions") is not None:
+ p["positions"] = params["positions"][r0:r1]
+ if params.get("recurrent_states") is not None:
+ p["recurrent_states"] = params["recurrent_states"][j0:j1]
+ if own_pages is not None:
+ p["dflash_table_pages"] = own_pages[r0:r1]
+ if (r1 - r0) * batch_ids.shape[-1] > 1:
+ p["dflash_verify"] = True
+ if r1 - r0 > 1:
+ p["row_inv_per_seq"] = True # the attention layers run each sequence on its own (Attention.forward)
+ if len(groups) > 1:
+ # The reused pinned staging of the embedding upload (modules/embedding.py) is only safe with a sync point
+ # between two forwards; the forwards of one step follow each other with none, and the next group would
+ # overwrite the rows the previous one has not copied yet
+ p["pinned_staging"] = False
+ logits.append(self.model.forward(input_ids = batch_ids[r0:r1], params = p))
+ if "export_states" in p:
+ exports.append(p["export_states"])
+ r0 = r1
+ if exports:
+ params["export_states"] = [torch.cat(parts, dim = 0) for parts in zip(*exports)]
+ return torch.cat(logits, dim = 0)
+
def iterate_gen(self, results: list, draft_tokens: torch.Tensor | None = None):
# Get shape of active batch
@@ -1385,10 +1533,16 @@ class Generator:
if self.draft_model:
params.update(self.draft_model.draft_verifier_params)
_tv0 = _pt()
- batch_logits = self.model.forward(
- input_ids = batch_ids,
- params = params,
- )
+ groups = None
+ if len(batch_jobs) > 1 and ROW_GROUPS["on"] and ROW_INV["on"] and self.model.caps.get("row_inv_groups") and not active_embeddings:
+ groups = self._row_groups(batch_jobs, batch_ids.shape[-1])
+ if groups is None:
+ batch_logits = self.model.forward(
+ input_ids = batch_ids,
+ params = params,
+ )
+ else:
+ batch_logits = self._forward_groups(batch_ids, params, batch_jobs, groups, own_pages)
_tv1 = _pt()
if SPEC_PROF:
_PROF_CUR["t_verify"] = _tv1 - _tv0
diff --git a/exllamav3/generator/job.py b/exllamav3/generator/job.py
index 25ac005..86347b9 100644
--- a/exllamav3/generator/job.py
+++ b/exllamav3/generator/job.py
@@ -5,6 +5,21 @@ from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .generator import Generator
from ..constants import PAGE_SIZE
+
+
+def _draft_pages_shared(g) -> bool:
+ """True when the draft cache can take a target page index (as many physical pages as the target cache). A smaller
+ draft cache (a ring of pages remapped by the caller, e.g. a DFlash2 drafter ring: 16 pages vs ~770) cannot:
+ page copies by target index would overflow it or land in the wrong ring slot, so those paths replay instead."""
+ if not g.draft_model or g.draft_cache is None:
+ return True
+ r = getattr(g, "_draft_pages_shared", None)
+ if r is None:
+ def pages(c):
+ l = next(iter(c.layers.values()), None)
+ return getattr(l, "max_num_tokens", 0) // PAGE_SIZE
+ r = g._draft_pages_shared = pages(g.draft_cache) >= pages(g.cache)
+ return r
import numpy as np
from .pagetable import Sequence, tensor_hash_checksum, random_hash
from .filter import Filter
@@ -44,10 +59,27 @@ def _strings_to_utf32(strings: tuple[str]) -> tuple[np.ndarray, np.ndarray] | No
return concat_strings, offsets
+import itertools
+# Write generation of a cache page (EXL3_PF_SPLIT exactness tags): every prefill write of a page takes a fresh number, so a
+# checkpoint that recorded the numbers of the pages below it can tell whether any of them was rewritten since.
+_PAGE_GEN = itertools.count(1)
+
+
+def _split_offsets() -> list:
+ """EXL3_PF_SPLIT (read per call): comma-separated tail sizes in rows, e.g. "256" or "1536,256"; empty = off."""
+ s = os.environ.get("EXL3_PF_SPLIT", "").replace(" ", "")
+ return sorted({int(x) for x in s.split(",") if x}, reverse = True)
+
+
_TT = bool(os.environ.get("KYO_TURN_TRACE"))
# EXL3_TAIL_REPLY=1 (default off): a finished job also stashes a tail checkpoint at the END of its reply, so the
# next turn (prompt = old prompt + reply + new message) resumes after the reply instead of replaying its last page
_TAIL_REPLY = os.environ.get("EXL3_TAIL_REPLY", "0") == "1"
+# CUDA: prompt-end tail checkpoints go to pinned host buffers asynchronously (GDNLayerState.stash); EXL3_TAIL_PIN=0 = synchronous .cpu()
+_TAIL_PIN = torch.version.hip is None and torch.cuda.is_available() and os.environ.get("EXL3_TAIL_PIN", "1") != "0"
+# EXL3_TAIL_RING=1 (default off): allow a tail restore into a partial page when the draft cache is a ring smaller than the target cache
+# (e.g. a DFlash2 drafter ring). Only the target K/V is copied; the drafter keeps what its ring slot holds. Drafts only, the target verifies
+_TAIL_RING = os.environ.get("EXL3_TAIL_RING", "0") == "1"
def _ttrace_begin():
if not _TT: return 0.0
torch.cuda.synchronize()
@@ -394,7 +426,11 @@ class Job:
return f"Generator job #{self.serial_number}"
+ _cil_hold = False # EXL3_SCHED_CHUNK_IL: decode-ready but held this step (Generator._cil_hold): reads as "not decodable"
+
def is_prefill_done(self):
+ if self._cil_hold:
+ return False
return all(seq.kv_position == len(seq.sequence_ids) - 1 for seq in self.sequences)
@@ -1272,7 +1308,23 @@ class Job:
# (last 2 * max_chunk_size tokens, see is_checkpoint_boundary), so the tail keeps every
# recurrent checkpoint of plain max_chunk_size chunking
chunk = self.generator.max_chunk_size
- big = int(os.environ.get("EXL3_PREFILL_BIG_CHUNK", "4096"))
+ # Models whose only recurrent state is the SWA ring (no GDN / KDA checkpoint cadence to protect) take the big chunk as soon as the
+ # prompt needs more than one plain chunk: a 4K prompt is one pass instead of 2048 + 1792 (+ tail), every
+ # expert's weights decoded once, ~2x the rows per expert (Flint 4K prefill +16 %). Block-sparse MoE
+ # models also default to 8192-row chunks below 64K of kv (more rows per expert: Flint 16K +1.5 %, 32K
+ # +4.7 %, 64K +3.6 %; +0.36 GiB workspace); EXL3_PREFILL_BIG_CHUNK sets it explicitly,
+ # EXL3_PREFILL_WIDE=0 restores the previous plan
+ swa_only, fused_moe = self.generator.wide_prefill_chunks()
+ no_rec = swa_only and not self.embeddings and os.environ.get("EXL3_PREFILL_WIDE", "1") != "0"
+ big_default = "4096"
+ if no_rec and fused_moe and seq.kv_position + 8192 <= 65536:
+ big_default = "8192"
+ self._wide_chunk_used = True
+ elif getattr(self, "_wide_chunk_used", False):
+ # past 64K: back to 4096-row chunks, release the wider workspace once (256K contexts are tight)
+ self._wide_chunk_used = False
+ torch.cuda.empty_cache()
+ big = int(os.environ.get("EXL3_PREFILL_BIG_CHUNK", big_default))
if big > 65535:
raise ValueError(f"EXL3_PREFILL_BIG_CHUNK={big}: a forward is limited to 65535 rows (mixer kernel grid.y)")
# EXL3_PREFILL_BIG_CHUNK_MAXPOS (default 0 = off): from this kv position on, plain chunks again (smaller
@@ -1285,6 +1337,13 @@ class Job:
self._big_chunk_released = True
torch.cuda.empty_cache()
remaining = len(seq.sequence_ids) - 1 - seq.kv_position
+ # a runtime-lowered max_chunk_size (decode priority, see Generator.base_chunk_size) disables big chunks, and so
+ # (CUDA) does any other job active or waiting: a big chunk would hold a short request behind 4096 rows of this
+ # prompt. ROCm lanes keep their measured chunking
+ g = self.generator
+ if chunk < getattr(g, "base_chunk_size", chunk) or \
+ (not torch.version.hip and (len(g.active_jobs) > 1 or g.pending_jobs)):
+ big = chunk
big_tail = big > chunk and big % chunk == 0 and self.big_tail_enabled()
if big_tail:
# EXL3_PREFILL_BIG_TAIL=1 (with EXL3_MIDCHUNK_CKPT=2): big chunks also inside the tail window, the
@@ -1301,7 +1360,8 @@ class Job:
keep = 3 if os.environ.get("EXL3_NC2_CKPT4", "0") == "1" else 1
if len(interior) > keep:
chunk = interior[keep] - seq.kv_position
- elif big > chunk and big % chunk == 0 and remaining > big + chunk:
+ elif big > chunk and big % chunk == 0 and (
+ remaining > big + chunk or (no_rec and remaining > chunk)):
chunk = big
prefill_end = seq.kv_position + chunk
if not (big_tail and prefill_end >= len(seq.sequence_ids) - 1):
@@ -1347,6 +1407,22 @@ class Job:
if prefill_end <= prefill_start:
continue
+ # EXL3_PF_SPLIT (GDN no-tail path): the last chunk is cut at page boundaries a fixed number of rows before the prompt
+ # end, and the state at each cut is kept as an exact checkpoint (see split_plan, _stash_exact). A later prompt whose
+ # cold plan has the same cut resumes there and replays the same chunk shapes as its cold prefill, so the result
+ # is bitwise a cold prefill (a resume with another row count differs numerically, see split_plan)
+ split_sig = None
+ if (gdn_nt or big_tail) and prefill_end == len(seq.sequence_ids) - 1 and prefill_start % PAGE_SIZE == 0 and \
+ len(self.sequences) == 1 and not self._unaligned_start:
+ plan = self.split_plan(prefill_end, "gdn" if gdn_nt else "kda")
+ if plan is not None and prefill_start in plan:
+ i = plan.index(prefill_start)
+ if i + 1 < len(plan):
+ prefill_end = plan[i + 1]
+ split_sig = plan[:i + 2]
+ m = self.generator.recurrent_cache.metrics
+ m["split_passes"] = m.get("split_passes", 0) + 1
+
assert prefill_start % PAGE_SIZE == 0 or mm_exact_chunks or self._unaligned_start
prefill_ids = seq.sequence_ids.torch_slice(prefill_start, prefill_end)
@@ -1355,7 +1431,8 @@ class Job:
# since the recurrent checkpoint will always be on a page boundary
p0 = prefill_start // PAGE_SIZE
p1 = prefill_end // PAGE_SIZE
- if prefill_start == p0 * PAGE_SIZE and self.generator.recurrent_cache is None:
+ if prefill_start == p0 * PAGE_SIZE and self.generator.recurrent_cache is None and \
+ _draft_pages_shared(self.generator):
prev_hash = None if p0 == 0 else seq.allocated_pages[p0 - 1].phash
best_match = 0
best_match_page = None
@@ -1410,6 +1487,13 @@ class Job:
resume_pos = self.cached_pages * PAGE_SIZE
off_grid = os.environ.get("EXL3_TAIL_OFFGRID", "0") == "1" and resume_pos % self.generator.max_chunk_size != 0
gap_base = resume_pos if self._unaligned_start or off_grid else 0
+ # a resume at a cut of the EXL3_PF_SPLIT plan measures the gap from the prompt start like the cold prefill does,
+ # so its last passes have the shapes of the cold ones (the checkpoint there is an exact one, see exact_gate)
+ if gap_base and not self._unaligned_start and len(self.sequences) == 1:
+ smode = self.split_mode()
+ splan = self.split_plan(seqlen, smode) if smode else None
+ if splan is not None and resume_pos in splan[1:]:
+ gap_base = 0
# EXL3_PF_NO_TAIL=1 (default 0, big-tail mode only): no separate pass for the prompt's last page
# (a 4K prompt ran 3840 + 255, the 255-row tail cost ~1 s); the chunk runs whole and the KDA
# kernel side-writes the last-page state as a second mid-chunk checkpoint (stash_midchunk)
@@ -1422,7 +1506,7 @@ class Job:
no_tail_row = last_page_b - prefill_start
elif prefill_start < last_page_b <= prefill_end and not (
prefill_end > last_page_b and self._tail_ok(seq) and seqlen % PAGE_SIZE != 0 and
- last_page_b - gap_base < int(os.environ.get("EXL3_TAIL_MAXGAP", "1024"))):
+ last_page_b - gap_base < self._tail_maxgap()):
# (a prompt-end tail checkpoint, see _tail_stash, replaces this separate pass; it is still taken
# when the last full-page checkpoint is EXL3_TAIL_MAXGAP tokens behind, which bounds the replay
# after a restart from the disk slot)
@@ -1441,6 +1525,14 @@ class Job:
if prefill_start < L < prefill_end and L - prefill_start != no_tail_row:
branch_row = L - prefill_start
+ # Dense prompt-tail checkpoints (GDN no-tail path): the kernel also side-writes the state at the page boundaries
+ # just below the last full page, so a request that shares the prompt up to some point inside its final
+ # EXL3_TAIL_DENSE pages (same document, another question) resumes at most one page before the divergence
+ dense_rows = []
+ if gdn_nt and prefill_start % PAGE_SIZE == 0:
+ sub_rows = self.sub_ckpt_rows(seq, prefill_start, prefill_end, [no_tail_row, branch_row])
+ dense_rows = sub_rows + self.tail_ckpt_rows(seq, prefill_start, prefill_end, [no_tail_row, branch_row] + sub_rows)
+
# Exact multimodal chunking (DeepSeek-V4 vision): an image span is prefilled as
# exactly one chunk (non-causal within itself) and never re-fed, since the
# ring / compressor / pool states are streams. Text chunks end at a span start and
@@ -1517,16 +1609,18 @@ class Job:
"inv_freq": self.alt_rope_freqs,
"mm_span_prefix": mm_span_prefix,
}
+ # the prompt and where this chunk ends: lets a model warm host-side lookup tables for the chunks to come
+ params["pf_ahead"] = (seq, prefill_start + prefill_ids.shape[-1])
if self.generator.draft_model:
params.update(self.generator.draft_model.draft_verifier_params)
# EXL3_MIDCHUNK_CKPT=1 (default off): a chunk that crosses a recurrent checkpoint boundary also
# saves the recurrent state at that boundary (KDA layers split conv + core there), stashed below
if self.recurrent_state is not None and not self.embeddings and \
(os.environ.get("EXL3_MIDCHUNK_CKPT", "0") in ("1", "2") or
- (gdn_nt and (no_tail_row is not None or branch_row is not None))) and \
+ (gdn_nt and (no_tail_row is not None or branch_row is not None or dense_rows))) and \
not self.generator.model.loaded_tp and prefill_start % PAGE_SIZE == 0:
if gdn_nt:
- rows = sorted(r for r in (branch_row, no_tail_row) if r is not None) # the kernel side-writes 2
+ rows = sorted([r for r in (branch_row, no_tail_row) if r is not None] + dense_rows) # the kernel side-writes up to 8
else:
rows = [
p - prefill_start
@@ -1540,6 +1634,14 @@ class Job:
2 if os.environ.get("EXL3_PF_NO_TAIL", "0") == "1" else 1)
if branch_row is not None and branch_row not in rows and len(rows) < cap:
rows = sorted(rows + [branch_row])
+ if os.environ.get("EXL3_MIDCHUNK_CKPT") == "2":
+ # the CK8 kernel build side-writes 8 rows: sub-page prompt-tail checkpoints first, then the dense
+ # page-boundary ones fill the free slots. Only in mode 2: mode 1 splits the layer at every row and
+ # declines when a segment is 256 rows or less (GatedDeltaNet._midchunk_segments), which rows one page
+ # (or 64 rows) apart always are, so such a row would drop every mid-chunk checkpoint of the chunk
+ rows = sorted(rows + self.sub_ckpt_rows(seq, prefill_start, prefill_end, rows))
+ if int(os.environ.get("EXL3_TAIL_DENSE", "0")) > 0:
+ rows = sorted(rows + self.tail_ckpt_rows(seq, prefill_start, prefill_end, rows))
if rows:
params["checkpoint_rows"] = rows
# 1: split conv + KDA core (reference), 2: in-kernel S side-write + async D2H (the only GDN mode)
@@ -1638,8 +1740,12 @@ class Job:
# (exact multimodal chunking) that page starts after prefill_end
if pfp_b > pfp_a:
page.sequence[:, pfp_a:pfp_b].copy_(seq.sequence_ids.torch_slice(pf_a, pf_b))
+ page.wgen = next(_PAGE_GEN)
page.can_revert = False
+ if split_sig is not None:
+ self._stash_exact(seq, split_sig)
+
if params.get("checkpoint_rows"):
# a requested row the forward did not save (split declined) is a lost checkpoint: count it
n = self.stash_midchunk(params.get("midchunk_states") or {}, prefill_start)
@@ -1687,7 +1793,14 @@ class Job:
for seq in self.sequences:
allocated_pages, cached_pages, non_sequential_pages, stashed_recurrent_state = \
- seq.allocate_pages(self.pagetable, self.generator.recurrent_cache, protected_hashes)
+ seq.allocate_pages(self.pagetable, self.generator.recurrent_cache, protected_hashes,
+ self.exact_gate(seq) if self.generator.recurrent_cache is not None and
+ (self.generator.recurrent_cache.exact_meta or _split_offsets()) else None)
+ rc = self.generator.recurrent_cache
+ if rc is not None and cached_pages > 0 and rc.exact_meta:
+ meta = rc.exact_meta.get(seq.page_hashes[cached_pages - 1])
+ if meta is not None and meta["eid"] == id(stashed_recurrent_state):
+ rc.metrics["exact_hits"] = rc.metrics.get("exact_hits", 0) + 1
# Free the previous state before acquiring a new one. A bare assignment drops
# the handle without returning the slot index to the cache free list, so every
@@ -1769,7 +1882,7 @@ class Job:
f.is_active = f.trigger_token is None and not self.filters_suspended
- def gdn_no_tail_enabled(self):
+ def gdn_no_tail_enabled(self, alloc = False):
"""
EXL3_PF_NO_TAIL=1 for GDN (non-KDA) recurrent models: text-only job, no TP, every recurrent layer a GatedDeltaNet (or the
Qwen PLE layer) with the fused HIP chain (EXL3_GDN_FUSE=1, EXL3_GDN_PF on), the only path that side-writes the mid-chunk state.
@@ -1777,7 +1890,7 @@ class Job:
if os.environ.get("EXL3_PF_NO_TAIL", "0") != "1" or os.environ.get("EXL3_GDN_FUSE", "0") != "1" or \
os.environ.get("EXL3_GDN_PF", "1") != "1":
return False
- if self.recurrent_state is None or self.embeddings:
+ if (self.recurrent_state is None and not alloc) or self.embeddings: # alloc: asked before the job has its state
return False
g = self.generator
ok = getattr(g, "_gdn_no_tail_ok", None)
@@ -1792,14 +1905,14 @@ class Job:
return ok
- def big_tail_enabled(self):
+ def big_tail_enabled(self, alloc = False):
"""
EXL3_PREFILL_BIG_TAIL=1, honored only with EXL3_MIDCHUNK_CKPT=2 and where the mid-chunk path can stash every
boundary: text-only recurrent job, no TP, every recurrent layer a KDA GatedDeltaNet (the mode-2 kernel).
"""
if os.environ.get("EXL3_PREFILL_BIG_TAIL", "0") != "1" or os.environ.get("EXL3_MIDCHUNK_CKPT", "0") != "2":
return False
- if self.recurrent_state is None or self.embeddings:
+ if (self.recurrent_state is None and not alloc) or self.embeddings: # alloc: asked before the job has its state
return False
g = self.generator
ok = getattr(g, "_big_tail_ok", None)
@@ -1854,6 +1967,136 @@ class Job:
self._mm_exact_spans = spans
return spans
+ def split_mode(self, alloc = False):
+ """Which prefill planner a split follows: "gdn" (GDN no-tail path), "kda" (KDA big-tail path) or None."""
+ if self.gdn_no_tail_enabled(alloc = alloc):
+ return "gdn"
+ if self.big_tail_enabled(alloc = alloc):
+ return "kda"
+ return None
+
+ def split_plan(self, total: int, mode = "gdn"):
+ """
+ Cold chunk plan of a prompt of `total` prefill rows under EXL3_PF_SPLIT: (ks, b1, ..., bn), the starts of the chunks of
+ the last region (ks = start of the merged last chunk, 4096-row chunks before it) and the page-aligned cuts that
+ end all but the last pass, each at least off_j rows before the prompt end. None = no split (switch off, prompt shorter
+ than EXL3_PF_SPLIT_MIN, adaptive chunking with the GDN planner, or no room for a first pass of EXL3_PF_SPLIT_HEAD rows).
+ mode "kda" follows the big-tail planner instead: chunks of EXL3_PREFILL_BIG_CHUNK rows, the last one is what remains
+ (<= that size, no merge window). The cuts are multiples of
+ EXL3_PF_SPLIT_Q rows (default one page): a coarser grid keeps a cut when the prompt length changes a little, at the price
+ of a longer last pass.
+ Why: LinearEXL3, hipBLASLt and the routed-MoE kernel pick algorithms by the row count of a forward, so a resume that
+ replays a chunk of another size than the cold prefill computed there is not bitwise the cold result, while the same
+ chunk at the same position is (state, conv state and K/V restore exactly). The cuts make the replay after a resume a
+ chunk the cold prefill of the same prompt ran too. The plan only depends on the prompt length, so a prompt of another
+ length has other cuts and cannot use these checkpoints (it falls back to the chunk start, like without the switch).
+ """
+ offs = _split_offsets()
+ if not offs:
+ return None
+ g = self.generator
+ chunk = g.max_chunk_size
+ big = int(os.environ.get("EXL3_PREFILL_BIG_CHUNK", "4096"))
+ if int(os.environ.get("EXL3_PREFILL_BIG_CHUNK_MAXPOS", "0")):
+ return None
+ if mode == "kda":
+ # KDA big-tail path: chunks of `big` rows, the last one is whatever remains (<= big, no merge window)
+ if big <= chunk or big % chunk or big % PAGE_SIZE:
+ return None
+ chunk, merge = big, 0
+ else:
+ if big > chunk:
+ return None
+ merge = int(os.environ.get("EXL3_PF_TAIL_MERGE", "0"))
+ if total < int(os.environ.get("EXL3_PF_SPLIT_MIN", "4096")) or chunk % PAGE_SIZE:
+ return None
+ ks = 0
+ while total - ks > chunk + merge:
+ ks += chunk
+ plan = [ks]
+ lo = ks + int(os.environ.get("EXL3_PF_SPLIT_HEAD", "1024"))
+ step = int(os.environ.get("EXL3_PF_SPLIT_STEP", "512"))
+ q = max(PAGE_SIZE, int(os.environ.get("EXL3_PF_SPLIT_Q", str(PAGE_SIZE))) // PAGE_SIZE * PAGE_SIZE)
+ for off in offs:
+ b = (total - off) // q * q
+ if b >= lo:
+ plan.append(b)
+ lo = b + step
+ return tuple(plan) if len(plan) > 1 else None
+
+
+ def exact_gate(self, seq):
+ """
+ Filter for the recurrent checkpoints an allocation may resume from (Sequence.allocate_pages): gate(state, page hash, page
+ index) -> bool. A checkpoint stashed by _stash_exact is usable only if this prompt's cold plan has the same cuts up to it
+ and none of the pages under it was rewritten since; a state without that tag at a cut of this plan is refused (it cannot
+ be shown to come from the cold chunk shapes). Every other checkpoint passes as before, except that allocate_pages drops those
+ deeper than the deepest accepted exact checkpoint (gate.tagged).
+ """
+ rc = self.generator.recurrent_cache
+ total = len(seq.sequence_ids) - 1
+ cache = []
+
+ def gate(state, ph, pi):
+ if not cache:
+ mode = self.split_mode(alloc = True) if len(self.sequences) == 1 else None
+ cache.append(self.split_plan(total, mode) if mode else None)
+ plan = cache[0]
+ meta = rc.exact_meta.get(ph)
+ m = rc.metrics
+ if meta is not None and meta["eid"] == id(state):
+ sig = meta["sig"]
+ ok = plan is not None and plan[:len(sig)] == sig
+ if ok:
+ pt = self.pagetable
+ hs = seq.page_hashes[sig[0] // PAGE_SIZE: sig[-1] // PAGE_SIZE]
+ for h, w in zip(hs, meta["pw"]):
+ p = pt.referenced_pages.get(h) or pt.unreferenced_pages.get(h)
+ if p is None or getattr(p, "wgen", 0) != w:
+ ok = False
+ break
+ if ok:
+ gate.tagged.append(pi)
+ else:
+ m["exact_rejected"] = m.get("exact_rejected", 0) + 1
+ return ok
+ if plan is not None and (pi + 1) * PAGE_SIZE in plan[1:]:
+ m["exact_rejected"] = m.get("exact_rejected", 0) + 1
+ return False
+ return True
+
+ gate.tagged = [] # page indices of the exact checkpoints accepted (allocate_pages prefers the deepest)
+ return gate
+
+
+ def _stash_exact(self, seq, sig: tuple):
+ """
+ Keep the recurrent state at the end of a split pass (position sig[-1], a page boundary) as an exact checkpoint, with the
+ plan prefix it belongs to and the write generations of the pages under it (see exact_gate). Replaces any state stashed
+ under the same page hash, which could come from a prefill with other chunk shapes.
+ """
+ rc = self.generator.recurrent_cache
+ b = sig[-1]
+ if rc is None or self.recurrent_state is None or self.recurrent_state.position != b:
+ return
+ page = seq.allocated_pages[b // PAGE_SIZE - 1]
+ if page.kv_position != PAGE_SIZE:
+ return
+ key = page.phash
+ if key in rc:
+ rc.drop(key)
+ rc.put(key, self.recurrent_state)
+ entry = dict.get(rc, key) # not rc.get: that would wait for the asynchronous stash
+ if entry is None:
+ return
+ pw = tuple(getattr(p, "wgen", 0) for p in seq.allocated_pages[sig[0] // PAGE_SIZE: b // PAGE_SIZE])
+ rc.exact_meta[key] = {"eid": id(entry), "sig": sig, "pw": pw}
+ while len(rc.exact_meta) > 256:
+ rc.exact_meta.pop(next(iter(rc.exact_meta)))
+ self.last_recurrent_checkpoint_pos = b
+ rc.metrics["split_stashes"] = rc.metrics.get("split_stashes", 0) + 1
+
+
def maybe_stash_recurrent(self, cache, interval = None):
"""
Store the current recurrent state if the sequence is at a checkpoint boundary.
@@ -1887,6 +2130,54 @@ class Job:
self.last_recurrent_checkpoint_pos = seq.kv_position
+ def tail_ckpt_rows(self, seq, prefill_start: int, prefill_end: int, taken):
+ """
+ Chunk rows of the dense prompt-tail checkpoints: the page boundaries last_page - k * PAGE_SIZE, k = 1 ..
+ EXL3_TAIL_DENSE, that fall strictly inside [prefill_start, prefill_end) and are not already requested (taken).
+ The GDN kernel has 8 side-write slots; the last page and a branch row come first, the dense rows fill the rest
+ (the deepest first). Reuse contract: a later prompt resumes at min(end of the hash-matched K/V pages, latest
+ recurrent checkpoint at or before it), so with a checkpoint on every page of the last EXL3_TAIL_DENSE pages a
+ prompt that diverges there replays at most one page plus its own new tokens.
+ """
+ n = int(os.environ.get("EXL3_TAIL_DENSE", "0"))
+ if n <= 0:
+ return []
+ last_page_b = (len(seq.sequence_ids) - 1) // PAGE_SIZE * PAGE_SIZE
+ have = [r for r in taken if r is not None]
+ rows = []
+ for k in range(1, n + 1):
+ r = last_page_b - k * PAGE_SIZE - prefill_start
+ if r <= 0:
+ break
+ if r not in have and 0 < r < prefill_end - prefill_start:
+ rows.append(r)
+ return rows[:max(0, 8 - len(have))]
+
+
+ def sub_ckpt_rows(self, seq, prefill_start: int, prefill_end: int, taken):
+ """
+ Chunk rows of the sub-page prompt-tail checkpoints (EXL3_TAIL_SUB = how many): the last multiples of 64 rows of
+ the chunk that holds the prompt end (the recurrent kernels write state at 64-row granularity), so a prompt that
+ diverges in its final tokens resumes at most 64 rows plus its own new tokens before the divergence, not up to a
+ page before it. Rows on a page boundary become ordinary page checkpoints; the others are kept by stash_midchunk
+ as sub-page entries (generator.sub_ckpts) that _tail_restore picks when they are the deepest match.
+ Only for a page-aligned chunk start (the kernel rows are then also multiples of 64 in absolute position).
+ """
+ n = int(os.environ.get("EXL3_TAIL_SUB", "0"))
+ if n <= 0 or getattr(self.generator, "sub_ckpt_max", 1) <= 0 or prefill_start % PAGE_SIZE != 0 or not self._tail_ok(seq):
+ return [] # EXL3_TAIL_SUB_MAX=0 keeps no entry, so no kernel slot is spent on one
+ if prefill_end != len(seq.sequence_ids) - 1:
+ return []
+ have = [r for r in taken if r is not None]
+ rows = []
+ r = (prefill_end - prefill_start - 1) // 64 * 64
+ while r >= 64 and len(rows) < n:
+ if r not in have and prefill_start + r >= self.generator.tail_ckpt_min:
+ rows.append(r)
+ r -= 64
+ return rows[:max(0, 8 - len(have))]
+
+
def stash_midchunk(self, saved: dict, prefill_start: int):
"""
Stash the mid-chunk recurrent states saved by the forward pass (EXL3_MIDCHUNK_CKPT), keyed like
@@ -1901,20 +2192,52 @@ class Job:
if set(per_layer) != set(layers):
continue
pos = prefill_start + r
- page = seq.allocated_pages[pos // PAGE_SIZE - 1]
- assert pos % PAGE_SIZE == 0 and page.kv_position == PAGE_SIZE
stashed = {"position": pos, "checkpoint_size": self.recurrent_state.checkpoint_size}
for k in layers:
s, c = per_layer[k][:2]
if len(per_layer[k]) == 3:
per_layer[k][2].synchronize() # mode 2: pinned host copies, D2H event on the side stream
stashed[k] = (s.cpu(), c.cpu())
+ if pos % PAGE_SIZE:
+ n += self._stash_sub(seq, pos, stashed)
+ continue
+ page = seq.allocated_pages[pos // PAGE_SIZE - 1]
+ assert page.kv_position == PAGE_SIZE
rc.put(page.phash, None, stashed = stashed)
rc.metrics["midchunk_stashes"] = rc.metrics.get("midchunk_stashes", 0) + 1
n += 1
return n
+ def _stash_sub(self, seq, pos: int, stashed: dict) -> int:
+ """
+ Keep a mid-page recurrent checkpoint (position pos, not a page boundary) as a sub-page entry: the same content-keyed
+ format as a prompt-end tail checkpoint (hash of the preceding full page + the token ids of the partial page), with
+ the page that holds the K/V rows. Reuse contract: _tail_restore resumes a later prompt at the deepest entry whose
+ ids are a prefix of it, copying the first (pos % PAGE_SIZE) K/V rows of the partial page. No MTP carry is kept
+ (the replay recomputes it), like a page checkpoint.
+ """
+ g = self.generator
+ p0 = pos // PAGE_SIZE
+ if g.sub_ckpt_max <= 0 or len(seq.allocated_pages) <= p0 or (p0 > 0 and seq.allocated_pages[p0 - 1].kv_position != PAGE_SIZE):
+ return 0
+ prev_hash = None if p0 == 0 else seq.allocated_pages[p0 - 1].phash
+ ids = seq.sequence_ids.torch_slice(p0 * PAGE_SIZE, pos).clone()
+ for e in g.sub_ckpts:
+ if e["prev_hash"] == prev_hash and e["ids"].shape == ids.shape and torch.equal(e["ids"], ids):
+ # same content: replace it (fresh page reference), most recent. By identity: list.remove() compares the
+ # entries with ==, which is a tensor comparison inside the dicts and raises
+ g.sub_ckpts[:] = [x for x in g.sub_ckpts if x is not e]
+ break
+ while g.sub_ckpts and len(g.sub_ckpts) >= g.sub_ckpt_max:
+ g.sub_ckpts.pop(0)
+ g.sub_ckpts.append({
+ "prev_hash": prev_hash, "ids": ids, "stashed": stashed, "carry": None,
+ "page": seq.allocated_pages[p0], "draft_ok": not self.mtp_defer,
+ })
+ return 1
+
+
def find_recurrent_stash(self, target_pos: int):
"""
Return the most recent page-aligned recurrent state stash at or before target_pos, refreshing its LRU
@@ -1929,6 +2252,14 @@ class Job:
return None
+ def _tail_maxgap(self) -> int:
+ # EXL3_TAIL_MAXGAP_RESUME (default = EXL3_TAIL_MAXGAP): the bound for a prefill resumed from a tail checkpoint (a conversation
+ # turn). A large value drops the separate last-page forward there (+0.15-0.3 s per turn on an RTX 3090 with Qwen3.8-27B) while cold
+ # prompts keep their chunking and last-page checkpoint
+ g = int(os.environ.get("EXL3_TAIL_MAXGAP", "1024"))
+ return int(os.environ.get("EXL3_TAIL_MAXGAP_RESUME", g)) if self._unaligned_start else g
+
+
def _tail_ok(self, seq) -> bool:
g = self.generator
return (
@@ -1982,7 +2313,7 @@ class Job:
if rc is not None and rc.async_stash_ok(self.recurrent_state):
stashed = rc.stash_async(self.recurrent_state) # EXL3_NC2_ASYNC_STASH: settled before _tail_restore reads it
else:
- stashed = self.recurrent_state.stash()
+ stashed = self.recurrent_state.stash(pinned = True) if _TAIL_PIN else self.recurrent_state.stash()
g.tail_ckpts.append({
"prev_hash": prev_hash, "ids": ids, "stashed": stashed,
"carry": None if carry is None else carry.clone(), "page": seq.allocated_pages[p0],
@@ -1992,6 +2323,36 @@ class Job:
_ttrace_end("tail checkpoint stash", t)
+ def _tail_peek(self, seq) -> int:
+ """
+ Read-only twin of the match scan in _tail_restore: the kv position the first prefill step would resume at (0 = no tail
+ checkpoint applies). Optimistic (it does not test the source page), so it can only over-estimate the skipped rows.
+ The chunk planner (EXL3_SCHED_CHUNK_IL) classifies big / short from it before the job has run any step.
+ """
+ if not self._tail_ok(seq):
+ return 0
+ g = self.generator
+ start = seq.kv_position
+ if not g.tail_ckpts or start % PAGE_SIZE != 0:
+ return 0
+ total = len(seq.sequence_ids) - 1
+ pages = seq.allocated_pages
+ valid = 0
+ while valid < len(pages) and pages[valid].kv_position == PAGE_SIZE:
+ valid += 1
+ first = start // PAGE_SIZE
+ for e in reversed(g.tail_ckpts):
+ L = e["ids"].shape[-1]
+ ph = e["prev_hash"]
+ i = 0 if ph is None else next((k + 1 for k in range(max(first - 1, 0), min(valid, len(pages))) if pages[k].phash == ph), -1)
+ if i < first or i > valid or i >= len(pages):
+ continue
+ pos = i * PAGE_SIZE
+ if pos + L > total or not torch.equal(e["ids"], seq.sequence_ids.torch_slice(pos, pos + L)):
+ continue
+ return pos + L
+ return 0
+
def _tail_restore(self, seq) -> int:
"""
Resume a prompt exactly at the end of an earlier prompt's prefill when the new prompt starts with the same
@@ -2005,7 +2366,7 @@ class Job:
return 0
g = self.generator
start = seq.kv_position
- if not g.tail_ckpts or start % PAGE_SIZE != 0:
+ if not (g.tail_ckpts or g.sub_ckpts) or start % PAGE_SIZE != 0:
return 0
total = len(seq.sequence_ids) - 1
pages = seq.allocated_pages
@@ -2013,22 +2374,33 @@ class Job:
while valid < len(pages) and pages[valid].kv_position == PAGE_SIZE:
valid += 1
first = start // PAGE_SIZE
- for e in reversed(g.tail_ckpts):
+ # candidates: every entry (exact prompt-end ones and sub-page ones) whose chain and token ids match this prompt,
+ # deepest resume position first; on a tie the exact prompt-end entry (it carries the MTP carry), then the most recent
+ cands = []
+ for lst in (g.tail_ckpts, g.sub_ckpts):
+ for e in reversed(lst):
+ L = e["ids"].shape[-1]
+ ph = e["prev_hash"]
+ if ph is None:
+ i = 0
+ else:
+ i = next((k + 1 for k in range(max(first - 1, 0), min(valid, len(pages))) if pages[k].phash == ph), -1)
+ if i < first or i > valid or i >= len(pages):
+ continue
+ pos = i * PAGE_SIZE
+ if pos + L > total or not torch.equal(e["ids"], seq.sequence_ids.torch_slice(pos, pos + L)):
+ continue
+ cands.append((pos + L, e, lst, i))
+ cands.sort(key = lambda c: -c[0])
+ for _, e, lst, i in cands:
L = e["ids"].shape[-1]
ph = e["prev_hash"]
- if ph is None:
- i = 0
- else:
- i = next((k + 1 for k in range(max(first - 1, 0), min(valid, len(pages))) if pages[k].phash == ph), -1)
- if i < first or i > valid or i >= len(pages):
- continue
pos = i * PAGE_SIZE
- if pos + L > total or not torch.equal(e["ids"], seq.sequence_ids.torch_slice(pos, pos + L)):
- continue
dst = pages[i]
if dst.kv_position == PAGE_SIZE and dst.prev_hash != ph: # a complete revived page must follow the entry's chain
continue
- if dst.kv_position != PAGE_SIZE and g.draft_model and not e.get("draft_ok", True):
+ ring = g.draft_model is not None and _TAIL_RING and not _draft_pages_shared(g)
+ if dst.kv_position != PAGE_SIZE and g.draft_model and (not e.get("draft_ok", True) or not (_draft_pages_shared(g) or ring)):
continue
if dst.kv_position != PAGE_SIZE: # a complete revived page already holds this K/V
src = e["page"]
@@ -2037,10 +2409,11 @@ class Job:
if _TT: print(f"trace: tail ckpt found but source page unusable (same={src is dst} kvp={src.kv_position})", flush=True)
continue
t = _ttrace_begin()
- for c in [g.cache] if not g.draft_model else [g.cache, g.draft_cache]:
+ for c in [g.cache] if not g.draft_model or ring else [g.cache, g.draft_cache]:
c.copy_page(c, src.page_index, dst.page_index, L)
dst.prev_hash = ph
dst.sequence[:, :L].copy_(e["ids"])
+ dst.wgen = next(_PAGE_GEN)
dst.kv_position = L
dst.can_revert = False
_ttrace_end(f"tail restore page copy rows={L}", t)
@@ -2057,8 +2430,8 @@ class Job:
self._unaligned_start = True
skipped = pos + L - start
self.cached_tokens += skipped
- g.tail_ckpts[:] = [x for x in g.tail_ckpts if x is not e]
- g.tail_ckpts.append(e)
+ lst[:] = [x for x in lst if x is not e]
+ lst.append(e)
return skipped
return 0
diff --git a/exllamav3/generator/pagetable.py b/exllamav3/generator/pagetable.py
index ad4707f..e0814c7 100644
--- a/exllamav3/generator/pagetable.py
+++ b/exllamav3/generator/pagetable.py
@@ -273,6 +273,7 @@ class Sequence:
pagetable: PageTable,
recurrent_cache: None | RecurrentCache,
protected_hashes: set | None = None,
+ exact_gate = None,
):
if self.max_cached_pages is None:
page_hashes = self.page_hashes
@@ -287,10 +288,14 @@ class Sequence:
recurrent_pages = []
for pi, ph in enumerate(page_hashes):
rs = recurrent_cache.get(ph)
- if rs:
+ if rs and (exact_gate is None or exact_gate(rs, ph, pi)):
recurrent_pages.append(pi)
# CPU-tier restores past the last checkpoint can't advance the resume point; replay prefill
# rewrites those pages anyway
+ if exact_gate is not None and getattr(exact_gate, "tagged", None):
+ # an exact checkpoint (EXL3_PF_SPLIT) is usable: resume there, not at a deeper checkpoint that would make the
+ # replay a chunk the cold prefill never computed (every page below it must be cached to reach a deeper one anyway)
+ recurrent_pages = [p for p in recurrent_pages if p <= max(exact_gate.tagged)]
restore_limit = (max(recurrent_pages) + 1) if recurrent_pages else 0
# Allocate pages in KV cache, limit prefix caching to available recurrent states
diff --git a/exllamav3/generator/row_groups.py b/exllamav3/generator/row_groups.py
new file mode 100644
index 0000000..bcfc117
--- /dev/null
+++ b/exllamav3/generator/row_groups.py
@@ -0,0 +1,44 @@
+"""Job groups for a row-invariant multi-job decode step.
+
+With several jobs decoding together, one forward carries (jobs x rows) token rows. Most weight kernels pick their
+arithmetic by the total row count, so a job's row gets other bits than the same row decoded alone. The kernels that
+serve up to ROW_INV_MAX_ROWS rows (one-row GEMV, R-row GEMV, fused MoE, ...) give every row the bits of the one-row
+launch whatever the row count. A step with more rows than that is therefore run as several forwards, each one with at
+most ROW_INV_MAX_ROWS rows: jobs are packed in order, and a job always stays whole in one group. The attention layers
+of a group still run one sequence at a time (Attention.forward, params["row_inv_per_seq"]): the split plan of the paged
+decode, the sparse selection and the graph path all follow the batch size and the longest sequence of the batch.
+
+The grouped step is opt-in: models declare caps["row_inv_groups"], and EXL3_ROW_INV_GROUPS=1 (GROUPS["on"], mutable at
+run time for one-load A/B) turns it on. It also needs ROW_INV["on"]. Off, all jobs run in one forward as before.
+EXL3_ROW_INV_GROUP_ROWS overrides the row cap (1 = one forward per job, the slowest and most obviously exact plan).
+"""
+import os
+
+from ..util.row_inv import ROW_INV_MAX_ROWS
+
+GROUPS = {"on": os.environ.get("EXL3_ROW_INV_GROUPS", "0") not in ("", "0")}
+
+
+def group_rows_cap() -> int:
+ v = os.environ.get("EXL3_ROW_INV_GROUP_ROWS", "")
+ return max(1, int(v)) if v.strip() else ROW_INV_MAX_ROWS
+
+
+def plan_groups(seq_counts: list[int], width: int, cap: int) -> list[tuple[int, int]]:
+ """Consecutive job ranges (j0, j1) of one forward each.
+
+ seq_counts: sequences (batch rows) per job; width: token rows per sequence in this step (1 + drafted tokens);
+ cap: most token rows a group may carry. A job whose own rows exceed the cap still forms a group of its own."""
+ spans = []
+ j0 = 0
+ rows = 0
+ n = len(seq_counts)
+ for j in range(n):
+ r = seq_counts[j] * width
+ if j > j0 and rows + r > cap:
+ spans.append((j0, j))
+ j0, rows = j, 0
+ rows += r
+ if n:
+ spans.append((j0, n))
+ return spans
diff --git a/exllamav3/kernel_seed/triton-3.7.0-gfx1151.tar.xz b/exllamav3/kernel_seed/triton-3.7.0-gfx1151.tar.xz
new file mode 100644
index 0000000..e9e2ad4
Binary files /dev/null and b/exllamav3/kernel_seed/triton-3.7.0-gfx1151.tar.xz differ
diff --git a/exllamav3/loader/gguf_collection.py b/exllamav3/loader/gguf_collection.py
new file mode 100644
index 0000000..ffca8e6
--- /dev/null
+++ b/exllamav3/loader/gguf_collection.py
@@ -0,0 +1,250 @@
+"""GGUF tensor collection: serve raw GGUF payloads to the
+engine's module loaders with the same call shape as SafetensorsCollection.
+
+Quantized tensors come back as raw uint8 bytes shaped [N, nb*block_bytes]
+(row-major GGUF order: dims[0] = K tiled in 256-groups, dims[1] = N rows,
+dims[2] = experts), ready for the ForeignLinear q8_1-activation dots.
+F16/F32 tensors come back as half/float with engine [N, K] (transposed vs
+the stored dims) or flat for vectors. Reads go through pread into numpy
+and a single H2D copy per tensor (no conversion, no requant).
+
+Only the methods the modules call are implemented: has_tensor,
+get_tensor (optional/allow_bf16/float2half/no_defer/transpose kwargs),
+get_tensor_sizes. Anything else raises.
+"""
+from __future__ import annotations
+
+import os
+import struct
+
+import numpy as np
+import torch
+
+GGML_BBS = {
+ 12: 144, # Q4_K
+ 13: 176, # Q5_K
+ 14: 210, # Q6_K
+ 23: 136, # IQ4_XS
+}
+GGML_QUANT = set(GGML_BBS.keys())
+
+_META_SZ = {0: 1, 1: 1, 2: 2, 3: 2, 4: 4, 5: 4, 6: 4, 7: 1, 10: 8, 11: 8, 12: 8}
+
+
+def _pad_to(t: torch.Tensor, pad_to) -> torch.Tensor:
+ """Zero-pad like Linear.pad_out (STC pads on load when pad_to is passed):
+ 2-D [in, out] -> pad_to (in, out); 1-D bias -> pad_to[0]."""
+ if pad_to is None:
+ return t
+ if t.dim() == 2:
+ ti, to = pad_to[0], pad_to[1]
+ if t.shape[0] >= ti and t.shape[1] >= to:
+ return t
+ p = torch.zeros((max(t.shape[0], ti), max(t.shape[1], to)),
+ dtype=t.dtype, device=t.device)
+ p[:t.shape[0], :t.shape[1]] = t
+ return p.contiguous()
+ to = pad_to[0] if isinstance(pad_to, tuple) else pad_to
+ if t.shape[0] >= to:
+ return t
+ p = torch.zeros((to,), dtype=t.dtype, device=t.device)
+ p[:t.shape[0]] = t
+ return p.contiguous()
+
+
+class GGUFCollection:
+
+ def __init__(self, path: str):
+ self.path = path
+ self.fd = os.open(path, os.O_RDONLY)
+ with open(path, "rb") as f:
+ assert f.read(4) == b"GGUF"
+ f.read(4)
+ nt = struct.unpack("<Q", f.read(8))[0]
+ nm = struct.unpack("<Q", f.read(8))[0]
+
+ def rs():
+ n = struct.unpack("<Q", f.read(8))[0]
+ return f.read(n).decode()
+
+ def sv():
+ t = struct.unpack("<I", f.read(4))[0]
+ if t in _META_SZ:
+ f.read(_META_SZ[t])
+ elif t == 8:
+ f.read(struct.unpack("<Q", f.read(8))[0])
+ elif t == 9:
+ at = struct.unpack("<I", f.read(4))[0]
+ n = struct.unpack("<Q", f.read(8))[0]
+ if at == 8:
+ for _ in range(n):
+ f.read(struct.unpack("<Q", f.read(8))[0])
+ else:
+ f.read(n * _META_SZ[at])
+
+ for _ in range(nm):
+ rs()
+ sv()
+ self.infos = {}
+ for _ in range(nt):
+ name = rs()
+ nd = struct.unpack("<I", f.read(4))[0]
+ dims = [struct.unpack("<Q", f.read(8))[0] for _ in range(nd)]
+ ty = struct.unpack("<I", f.read(4))[0]
+ off = struct.unpack("<Q", f.read(8))[0]
+ self.infos[name] = (ty, tuple(dims), off)
+ self.base = (f.tell() + 31) // 32 * 32
+ # SafetensorsCollection attrs poked by Config/model_init paths
+ self.directory = os.path.dirname(path)
+ self.tensor_file_map = {k: path for k in self.infos}
+ self.file_headers = {}
+ # Engine-key -> gguf-name translation (set by the arch config).
+ # Values are gguf names, or (gguf name, "T") when the engine wants
+ # the transpose of the stored orientation (e.g. the GDN conv).
+ self.name_map: dict[str, str | tuple] = {}
+ # In-memory overrides (e.g. dequantized embedding), served first.
+ self.new_tensors: dict[str, torch.Tensor] | None = None
+
+ def _resolve(self, key: str) -> str:
+ mapped = self.name_map.get(key, key)
+ return mapped[0] if isinstance(mapped, tuple) else mapped
+
+ def has_tensor(self, key: str) -> bool:
+ if self.new_tensors and key in self.new_tensors:
+ return True
+ return self._resolve(key) in self.infos
+
+ # Deferred-load arena API (SafetensorsCollection): ForeignLinear and the
+ # fp16 paths load eagerly, so these are no-ops. Present because
+ # model_ls brackets every load with them.
+ def begin_deferred_load(self, arena=True):
+ return None
+
+ def end_deferred_load(self):
+ return None
+
+ def abort_deferred_load(self):
+ return None
+
+ def drop_page_cache(self):
+ return None
+
+ def close(self):
+ try:
+ os.close(self.fd)
+ except OSError:
+ pass
+
+ def has_tensor_group(self, key, subkeys) -> bool:
+ if isinstance(key, list):
+ return all(self.has_tensor_group(k, subkeys) for k in key)
+ for sk in subkeys:
+ if isinstance(sk, str):
+ if not self.has_tensor(f"{key}.{sk}"):
+ return False
+ elif not any(self.has_tensor(f"{key}.{s}") for s in sk):
+ return False
+ return True
+
+ def get_tensor_sizes(self, key: str):
+ info = self.infos.get(self._resolve(key))
+ if info is None:
+ raise KeyError(key)
+ return info[1]
+
+ def _pread(self, off: int, n: int) -> np.ndarray:
+ buf = bytearray(n)
+ mv = memoryview(buf)
+ got = 0
+ while got < n:
+ r = os.pread(self.fd, n - got, self.base + off + got)
+ if not r:
+ raise IOError(f"short read at {off + got}")
+ mv[got:got + len(r)] = r
+ got += len(r)
+ return np.frombuffer(buf, dtype=np.uint8)
+
+ def get_tensor(
+ self,
+ key: str,
+ device: torch.device | None = None,
+ optional: bool = False,
+ allow_bf16: bool = False,
+ float2half: bool = False,
+ no_defer: bool = False,
+ transpose: bool = False,
+ pad_to: tuple | None = None,
+ fidx=None,
+ ) -> torch.Tensor | None:
+ if self.new_tensors and key in self.new_tensors:
+ t = self.new_tensors[key]
+ t = t.to(device) if device is not None else t
+ # Overrides are stored in engine orientation; ignore transpose.
+ if float2half and t.dtype == torch.float32:
+ t = t.half()
+ return _pad_to(t, pad_to)
+ # Expert-slice protocol: "<gguf3d>.e<idx>[.weight]" serves expert
+ # idx's [N, nb*bb] rows out of a [K, N, E] tensor (contiguous expert).
+ exp_idx = None
+ body = key[:-7] if key.endswith(".weight") else key
+ if key not in self.infos and ".e" in body:
+ base_body, esuf = body.rsplit(".e", 1)
+ if esuf.isdigit() and (base_body + ".weight") in self.infos:
+ key, exp_idx = base_body + ".weight", int(esuf)
+ mapped = self.name_map.get(key, key)
+ want_T = False
+ if isinstance(mapped, tuple):
+ mapped, want_T = mapped[0], (mapped[1] == "T")
+ info = self.infos.get(mapped)
+ if info is None:
+ if not optional:
+ raise ValueError(f"Required tensor {key} not found in {self.path}")
+ return None
+ ty, dims, off = info
+ dev = device if device is not None else torch.device("cpu")
+ if ty in GGML_QUANT:
+ bb = GGML_BBS[ty]
+ K, N = dims[0], dims[1]
+ assert K % 256 == 0
+ nb = K // 256
+ if exp_idx is not None:
+ assert len(dims) == 3
+ E = dims[2]
+ assert 0 <= exp_idx < E
+ raw = self._pread(off + exp_idx * N * nb * bb, N * nb * bb)
+ raw = raw.reshape(N, nb * bb)
+ else:
+ extra = int(np.prod(dims[2:])) if len(dims) > 2 else 1
+ raw = self._pread(off, extra * N * nb * bb).reshape(extra * N, nb * bb)
+ t = torch.from_numpy(np.ascontiguousarray(raw))
+ if transpose:
+ raise ValueError("transpose not supported for quant payloads")
+ return t.to(dev)
+ if ty in (0, 1): # F32 / F16
+ dt = np.float32 if ty == 0 else np.float16
+ es = 4 if ty == 0 else 2
+ n = int(np.prod(dims))
+ raw = self._pread(off, n * es)
+ a = np.frombuffer(raw, dtype=dt)
+ # GGUF dims are ggml order (ne[0] = row length, fastest): the TRUE
+ # matrix orientation is [dims[1], dims[0}] (dims[1] rows of dims[0]).
+ # (A scrambled (dims[0], dims[1]) view silently corrupts every 2-D
+ # F32 consumer, e.g. the MoE router: flat-identical, corr ~0.)
+ # The transpose flag converts to engine [in, out] (like the STC);
+ # tensors mapped with the "T" mark are transposed (e.g. GDN conv
+ # is served [C, K] as stored; the engine flats it directly).
+ if len(dims) == 2:
+ a = a.reshape(dims[1], dims[0])
+ if transpose or want_T:
+ a = a.T
+ else:
+ a = a.reshape(*dims) if len(dims) > 1 else a
+ if key.endswith("shared_expert_gate.weight") and a.ndim == 1:
+ a = a.reshape(-1, 1) # Linear(in=H, out=1) weight [H, 1]
+ t = torch.from_numpy(np.ascontiguousarray(a))
+ if float2half and t.dtype == torch.float32:
+ t = t.half()
+ elif allow_bf16 and t.dtype == torch.float32:
+ t = t.bfloat16()
+ return _pad_to(t.to(dev), pad_to)
+ raise ValueError(f"unsupported gguf type {ty} for {key}")
diff --git a/exllamav3/model/config.py b/exllamav3/model/config.py
index 4cf0b5b..3d06bb9 100644
--- a/exllamav3/model/config.py
+++ b/exllamav3/model/config.py
@@ -56,7 +56,7 @@ class InferParams:
# Stream an n-gram embedding table (PLE models, e.g. Qwen3.8-Flash-Next) from disk with
# per-forward row gathers instead of loading the whole table into system RAM (tens of
# GB). Set before loading the model
- # None (env unset): NGramEmbedding picks RAM when the host has room for the table, else disk
+ # None (env unset) = default, which is disk streaming (see decide_ngram_stream); RAM only with EXL3_NGRAM_STREAM=0 or --ngram_ram
_ns = os.environ.get("EXL3_NGRAM_STREAM")
self.ngram_stream_from_disk = None if _ns is None else _ns != "0"
diff --git a/exllamav3/model/cuda_graph.py b/exllamav3/model/cuda_graph.py
new file mode 100644
index 0000000..6160ea2
--- /dev/null
+++ b/exllamav3/model/cuda_graph.py
@@ -0,0 +1,571 @@
+"""Whole-forward CUDA graph for decode on CUDA (opt-in: EXL3_CUDA_GRAPH=1, default off).
+
+Scope: Qwen3-MoE style models and (stage C) GatedDeltaNet hybrids
+such as Qwen3_5, and LFM2 ShortConv hybrids (Embedding -> [TransformerBlock(Attention|GatedDeltaNet|ShortConv +
+BlockSparseMLP|GatedMLP)]* ->
+RMSNorm -> lm_head Linear), B=1, Q in 1..8, single CUDA device, no TP. Everything else declines to the
+eager path with no behaviour change (this module returns None and Model.forward carries on as before).
+
+Stage C (recurrent hybrids), per step values made static or keyed:
+- recurrent slot ids: static int32 device tensor e.slots, refreshed by a stream-ordered D2D copy only when the
+ live slot tensor object changes (block_graph.py logic); params["recurrent_slots"] in the graph params is e.slots.
+- conv/recurrent state tensors: cache-owned, allocated once (GDNLayerState.alloc), rewind/stash copy in place, so
+ their pointers are stable; the key holds id(cache) and a fingerprint of the first KV and recurrent state tensor.
+- history flag (recurrent_history) and dflash_verify are in the key (they select the BC slot / state stride).
+- positions (mrope): separate static buffer e.pos, refreshed per step (already handled for non-aliased positions).
+- export_state_layers / export_state_norm_keys (DFlash2 and MTP verify: target hidden taps) are in the key; the
+ tap tensors produced inside the capture are kept (e.exports) and cloned into params["export_states"] per replay.
+- prepare_for_recurrence (slot tensor) runs in Model.prepare_inputs before this runner; advance_recurrent_states
+ runs after it in Model.forward, exactly as in eager. Rewind (generator reject_remainder) is host side, after.
+
+What is graphed: all modules after the Embedding (blocks + final norm + lm_head), from the embedding
+OUTPUT to logits. The CPU embedding lookup stays eager (as today) and its result is copied into a
+static device buffer. The C++ BC objects run their eager launch path while the stream is capturing
+(stage A), so the outer torch.cuda.graph records plain kernel launches on static buffers.
+
+Per capture key (see _key): static device buffers x_in, block_table, cache_seqlens (+ positions when it
+is a separate tensor, e.g. mrope). The params dict used for warmup and capture holds those STATIC CUDA
+tensors, so util.tensor.get_for_device returns them as they are (to_device is a no-op for same-device
+tensors) and no host-to-device copy is captured. Before every replay the step's values are copy_'d into
+the static buffers (stream-ordered, non_blocking when the source is pinned: the generator's staging
+buffers are; it synchronizes once per step before refilling them).
+
+Lifecycle per key: EXL3_CUDA_GRAPH_WARMUPS (2) real eager calls through the same static buffers (BC slot
+configure, autotune, Triton compile happen there; their logits are returned normally), then the next
+call captures (capture records, it does not execute) and replays once to commit the step. Every later
+call = copy-in + replay. Host-only bookkeeping (advance_recurrent_states) stays in Model.forward.
+
+Output lifetime: the graph's logits tensor lives in the private pool shared by all graphs of a device and
+is overwritten by the next replay of ANY graph on that device. By default (EXL3_CUDA_GRAPH_CLONE=1) a
+clone is returned (one small copy: Q*vocab*2 bytes); set it to 0 only when every caller consumes the
+logits before the next forward on the device.
+
+Failure policy: a capture error disables the key and raises (a capture error can mean captured work ran
+for real); EXL3_CUDA_GRAPH_FALLBACK=eager declines to the eager path instead (diagnostic). A replay error
+disables the key and raises. A capture is recreated when the block table width changes (every 4096
+tokens at B=1, exactly the width the generator passes, so split numerics match eager); LRU cap
+EXL3_CUDA_GRAPH_MAX (6). purge() releases everything (call between harness arms / model reloads).
+"""
+
+from __future__ import annotations
+
+import os
+import weakref
+from collections import Counter, OrderedDict
+
+import torch
+
+_env_int = lambda name, default: int(os.environ.get(name, default) or default)
+
+# Module global: a harness may flip it between arms (then call purge()).
+CUDA_GRAPH_ENABLED = os.environ.get("EXL3_CUDA_GRAPH", "0") == "1"
+CUDA_GRAPH_WARMUPS = max(1, _env_int("EXL3_CUDA_GRAPH_WARMUPS", 2))
+# EXL3_CUDA_GRAPH_MULTI=1 (default off): several jobs per graph (B in 1..4, Q <= 16, B*Q <= 32), bigger LRU. Off =
+# the B=1, Q <= 8 behaviour above, unchanged. set_multi() flips the globals for harness arms (then call purge()).
+CUDA_GRAPH_MULTI = False
+CUDA_GRAPH_MAX = 6
+CUDA_GRAPH_MAX_ROWS = 8 # B*Q, MAX_BSZN of the BC objects
+CUDA_GRAPH_MAX_B = 1
+CUDA_GRAPH_MAX_Q = 8
+
+
+def set_multi(on: bool):
+ global CUDA_GRAPH_MULTI, CUDA_GRAPH_MAX, CUDA_GRAPH_MAX_ROWS, CUDA_GRAPH_MAX_B, CUDA_GRAPH_MAX_Q
+ CUDA_GRAPH_MULTI = bool(on)
+ CUDA_GRAPH_MAX = max(1, _env_int("EXL3_CUDA_GRAPH_MAX", 16 if on else 6))
+ CUDA_GRAPH_MAX_ROWS = 32 if on else 8
+ CUDA_GRAPH_MAX_B = 4 if on else 1
+ CUDA_GRAPH_MAX_Q = 16 if on else 8
+
+
+set_multi(os.environ.get("EXL3_CUDA_GRAPH_MULTI", "0") == "1")
+CUDA_GRAPH_CLONE = os.environ.get("EXL3_CUDA_GRAPH_CLONE", "1") != "0"
+CUDA_GRAPH_FALLBACK = os.environ.get("EXL3_CUDA_GRAPH_FALLBACK", "closed")
+CUDA_GRAPH_DEBUG = os.environ.get("EXL3_CUDA_GRAPH_DEBUG", "0") == "1"
+
+# Only these params keys may be present; anything else (export_state_layers, activate_all_experts,
+# autosplit_measure, reconstruct, capture, ovr, sim_kvq, non_causal_spans, last_tokens_only, skip_logits,
+# draft verifier extras, ...) means a path the graph was not designed for -> eager.
+_ALLOWED = frozenset({
+ "attn_mode", "block_table", "cache", "cache_seqlens", "recurrent_states", "indexed_embeddings",
+ "positions", "position_ids", "position", "recurrent_history", "pinned_staging", "dflash_verify",
+ "dflash_table_pages", "layer_instance", "input_ids", "dev_cache", "recurrent_slots",
+ "export_state_layers", "export_state_norm_keys",
+})
+# NB: "swa_cs" is set by the runner on its own params copy only, never by callers
+
+_pools: dict[int, object] = {}
+_streams: dict[int, object] = {}
+_registry: list = []
+
+
+def _live_graphs(dev_index: int) -> int:
+ n = 0
+ for ref in _registry:
+ r = ref()
+ if r is not None and r.dev is not None and r.dev.index == dev_index:
+ n += sum(1 for e in r.entries.values() if e.graph is not None)
+ return n
+
+
+def _pool_for(dev_index: int):
+ p = _pools.get(dev_index)
+ # Once every graph of a pool is released (LRU evictions while new keys are still warming up, e.g. varying
+ # draft widths) torch keeps the pool registered with use_count 0 as long as a returned output still holds one
+ # of its blocks, and capture_begin on that handle hits "it->second->use_count > 0" (CUDACachingAllocator).
+ # A fresh handle then: same graphs, only the pool identity changes
+ if p is None or _live_graphs(dev_index) == 0:
+ p = _pools[dev_index] = torch.cuda.graph_pool_handle()
+ return p
+
+
+def _stream_for(dev_index: int):
+ s = _streams.get(dev_index)
+ if s is None:
+ s = _streams[dev_index] = torch.cuda.Stream(device = dev_index)
+ return s
+
+
+class _Entry:
+ __slots__ = ("graph", "out", "x_in", "bt", "cs", "pos", "params", "warm", "last_used", "cache_ref", "fp",
+ "slots", "slots_src", "exports", "swa_cs", "swa_host")
+
+
+def _cache_fp(cache):
+ """Address fingerprint of the cache's first layer: a reloaded/reallocated cache invalidates graphs."""
+ try:
+ layer = next(iter(cache.layers.values()), None)
+ k = getattr(layer, "k", None)
+ fp = [k.data_ptr() if torch.is_tensor(k) else 0]
+ rl = getattr(cache, "recurrent_layers", None)
+ if rl:
+ r = next(iter(rl.values()))
+ # 0 while freed (meta); ShortConv layers have conv_state only
+ fp += [t.data_ptr() for t in (getattr(r, "conv_state", None), getattr(r, "recurrent_state", None))
+ if torch.is_tensor(t)]
+ return tuple(fp)
+ except Exception:
+ return ()
+
+
+def _foreign_gdn_ok(a) -> bool:
+ """MiniCPM-style GDN: split foreign/fp16 projections, no KDA/TP/heads-less.
+ Capture compatibility of the torch path is verified empirically (a capture
+ error declines the key); this only admits the attempt."""
+ from ..modules.foreign_linear import ForeignLinear
+ from ..modules import Linear
+ if a.kda or a.tp_reduce or a.num_k_heads == 0:
+ return False
+ if a.qkvz_proj is not None or a.ba_proj is not None:
+ return False
+ for p in (a.qkv_proj, a.z_proj, a.b_proj, a.a_proj, a.o_proj):
+ if p is None:
+ return False
+ if type(p) is ForeignLinear:
+ if p.quant_type != "foreign":
+ return False
+ elif type(p) is Linear:
+ if p.quant_type != "fp16":
+ return False
+ else:
+ return False
+ return True
+
+
+class CudaGraphRunner:
+
+ def __init__(self, model):
+ self.model = model
+ self.entries: OrderedDict = OrderedDict()
+ self.disabled: set = set()
+ self.stats = {"captures": 0, "replays": 0, "warmups": 0, "declines": Counter()}
+ self.tick = 0
+ self._model_ok = None
+ self.dev = None
+ self.has_gdn = False
+ self.has_conv = False
+ self.has_mamba = False
+ self.has_swa = False
+ self.swa_mods = []
+ _registry.append(weakref.ref(self))
+
+ # -- eligibility ---------------------------------------------------------------------------
+
+ def _check_model(self) -> bool:
+ from ..modules import (Embedding, TransformerBlock, Attention, BlockSparseMLP, GatedMLP, RMSNorm, Linear)
+ from ..modules.gated_delta_net import GatedDeltaNet
+ from ..modules.short_conv import ShortConv
+ from ..modules.mamba2 import Mamba2
+ from ..modules.sliding_attn import SlidingAttention
+ from ..modules.foreign_linear import ForeignLinear
+ m = self.model
+ fm = m.fwd_modules
+ if m.loaded_tp or len(fm) < 3 or type(fm[0][0]) is not Embedding:
+ return False
+ if m._get_prefetch_layers or getattr(m.config, "moe_cpu_hosts", None):
+ return False
+ devs = set()
+ self.has_gdn = False
+ self.has_conv = False
+ self.has_mamba = False
+ self.has_swa = False
+ self.swa_mods = []
+ for mod, inst, _ in fm[1:]:
+ t = type(mod)
+ if t is TransformerBlock:
+ if mod.attn is None:
+ pass # MoE/norm-only block (Bolt "E"): the mlp check below applies
+ elif type(mod.attn) is Mamba2:
+ # Bolt: torch-path Mamba2 over as-shipped foreign projs (the exl3
+ # BC path sets .bc and stays on its own lane). No TP, no heads-less.
+ a = mod.attn
+ if a.bc is not None or a.tp_reduce or a.num_k_heads == 0 or \
+ type(a.in_proj) is not ForeignLinear or \
+ type(a.o_proj) is not ForeignLinear:
+ return False
+ self.has_mamba = True
+ if mod.mlp is not None:
+ return False
+ elif type(mod.attn) is GatedDeltaNet:
+ # only the fused BC_GatedDeltaNetSplit path (static buffers, no shape-keyed Python caches
+ # such as _qd3_ba/_qd3_bg); KDA, TP-reduced and head-less variants stay eager
+ a = mod.attn
+ if not a.bc_split or a.bc is None or a.kda or a.tp_reduce or a.num_k_heads == 0:
+ # MCPM_FQ_GRAPH=1 (MiniCPM foreign-GDN experiment): allow the
+ # torch-path GDN when every projection is as-shipped
+ # (ForeignLinear) or plain fp16, so capture can be
+ # attempted; anything else in the layer stays eager.
+ if not (os.environ.get("MCPM_FQ_GRAPH", "1") == "1" and
+ _foreign_gdn_ok(a)):
+ return False
+ self.has_gdn = True
+ elif type(mod.attn) is ShortConv:
+ # LFM2: the conv slot is resolved on the host (CPU slot tensor) and baked into the capture,
+ # so the slot id is part of the key; TP-reduced variants stay eager
+ if mod.attn.tp_reduce:
+ return False
+ self.has_conv = True
+ elif type(mod.attn) is SlidingAttention:
+ # sliding-window ring (Flint): host-side window shift + in-state seqlens are prepared per step
+ # by the runner (sliding_attn.swa_graph_prep) into a static buffer, block table is per slot
+ if mod.attn.tp_reduce or mod.attn.num_kv_heads == 0:
+ return False
+ self.has_swa = True
+ self.swa_mods.append((mod.attn, inst))
+ elif type(mod.attn) is not Attention or getattr(mod.attn, "qsa_indexer", None) is not None:
+ return False
+ if mod.mlp is None:
+ # Attn/mamba-only blocks: Bolt foreign Attention (all projs
+ # as-shipped) or Bolt Mamba2 above; anything else stays eager.
+ if mod.attn is not None and type(mod.attn) is Mamba2:
+ pass
+ elif type(mod.attn) is Attention and all(
+ type(getattr(mod.attn, k, None)) in (ForeignLinear, type(None))
+ for k in ("q_proj", "k_proj", "v_proj", "o_proj")) and \
+ any(getattr(mod.attn, k, None) is not None
+ for k in ("q_proj", "k_proj", "v_proj", "o_proj")):
+ pass
+ else:
+ return False
+ elif type(mod.mlp) not in (BlockSparseMLP, GatedMLP):
+ return False
+ if mod.attn_hc is not None or mod.mlp_hc is not None or mod.ablit:
+ return False
+ elif t is Linear:
+ if mod.lora_a_tensors:
+ return False
+ elif t is ForeignLinear:
+ pass # Bolt lm_head over as-shipped weights (no LoRA/adapters)
+ elif t is not RMSNorm:
+ return False
+ if mod.device is None:
+ return False
+ devs.add(torch.device(mod.device))
+ if len(devs) != 1 or (self.has_gdn and self.has_conv):
+ return False # GDN graphs pass device slot ids, ShortConv reads them on the host: no mixed model
+ dev = devs.pop()
+ if dev.type != "cuda" or dev.index is None:
+ return False
+ if not fm[-1][0].caps.get("logits_output"):
+ return False
+ self.dev = dev
+ return True
+
+ def _decline(self, ids, params):
+ """None when this call may be graphed, else a short reason."""
+ if (ids.dim() != 2 or not 1 <= ids.shape[0] <= CUDA_GRAPH_MAX_B or ids.shape[1] > CUDA_GRAPH_MAX_Q
+ or ids.shape[0] * ids.shape[1] > CUDA_GRAPH_MAX_ROWS):
+ return "shape"
+ for k in params:
+ if k not in _ALLOWED:
+ return "param:" + k
+ if self.has_swa and ids.shape[1] > 1:
+ return "swa_multi" # m>1 (ngram / MTP verify) sliding steps use paths that are not capture-safe (per-call tensors): eager
+ bt = params.get("block_table")
+ cs = params.get("cache_seqlens")
+ if not torch.is_tensor(bt) or not torch.is_tensor(cs) or params.get("cache") is None or bt.dim() != 2:
+ return "no_block_table"
+ if params.get("indexed_embeddings"):
+ return "state"
+ rs = params.get("recurrent_states")
+ if self.has_gdn or self.has_conv or self.has_mamba or self.has_swa:
+ slots = params.get("recurrent_slots")
+ nb = ids.shape[0] if CUDA_GRAPH_MULTI else 1 # one recurrent state / slot per job
+ if (not rs or len(rs) != nb or any(getattr(r, "exported", False) for r in rs[:nb])
+ or not torch.is_tensor(slots) or slots.numel() != nb):
+ return "state"
+ if self.has_conv and slots.device.type != "cpu":
+ return "state"
+ elif rs:
+ return "state"
+ if params.get("position") or params.get("position_ids") is not None:
+ return "position"
+ if params.get("attn_mode", "flash_attn") != "flash_attn":
+ return "attn_mode"
+ if torch.cuda.is_current_stream_capturing():
+ return "capturing"
+ return None
+
+ # -- entry points --------------------------------------------------------------------------
+
+ def forward(self, ids: torch.Tensor, params: dict):
+ if self._model_ok is None:
+ self._model_ok = self._check_model()
+ if not self._model_ok:
+ self.stats["declines"]["model"] += 1
+ return None
+ why = self._decline(ids, params)
+ if why is not None:
+ self.stats["declines"][why] += 1
+ return None
+
+ fm = self.model.fwd_modules
+ # Embedding stays eager, exactly as forward_ls would run it
+ emb, inst0, _ = fm[0]
+ params["layer_instance"] = inst0
+ x = emb.prepare_for_device(ids, params)
+ x = emb.forward(x, params)
+ tail = fm[1:]
+
+ key = self._key(x, params)
+ if key in self.disabled:
+ self.stats["declines"]["disabled_key"] += 1
+ return self._run_tail(tail, x, params)
+
+ cache = params["cache"]
+ e = self.entries.get(key)
+ if e is not None and (e.cache_ref() is not cache or e.fp != _cache_fp(cache)):
+ self._drop(key) # cache object recycled / reallocated: static pointers are stale
+ e = None
+ if e is None:
+ e = self._new_entry(key, x, params)
+ self.tick += 1
+ e.last_used = self.tick
+ self.entries.move_to_end(key)
+ dev = self.dev
+
+ self._load(e, x, params)
+ if e.graph is None:
+ if e.warm < CUDA_GRAPH_WARMUPS:
+ e.warm += 1
+ self.stats["warmups"] += 1
+ # real eager call through the same static buffers; output is the step's result
+ p = dict(e.params)
+ y = self._run_tail(tail, e.x_in, p)
+ if "export_states" in p:
+ params["export_states"] = p["export_states"]
+ return y
+ if not self._capture(key, e, tail, x, params):
+ return self._run_tail(tail, x, params) # FALLBACK=eager decline
+ try:
+ with torch.cuda.device(dev):
+ e.graph.replay()
+ except Exception:
+ self._drop(key)
+ self.disabled.add(key)
+ self.stats["declines"]["replay_error"] += 1
+ raise
+ self.stats["replays"] += 1
+ if CUDA_GRAPH_DEBUG:
+ print(f"[cudagraph] replay key={key[1:5]}", flush = True)
+ if e.exports is not None:
+ # target hidden taps (DFlash2 / MTP verify): the generator keeps them past the next forward
+ params["export_states"] = [t.clone() for t in e.exports] if CUDA_GRAPH_CLONE else list(e.exports)
+ return e.out.clone() if CUDA_GRAPH_CLONE else e.out
+
+ # -- internals -----------------------------------------------------------------------------
+
+ @staticmethod
+ def _run_tail(tail, x, p):
+ # Same loop as Model.forward_ls minus the embedding (declines guarantee no last_tokens_only /
+ # skip_logits / moe_cpu_hosts)
+ for module, instance, idx in tail:
+ p["layer_instance"] = instance
+ x = module.prepare_for_device(x, p)
+ x = module.forward(x, p)
+ return x
+
+ def _key(self, x, params):
+ bt = params["block_table"]
+ cs = params["cache_seqlens"]
+ pos = params.get("positions")
+ pages = params.get("dflash_table_pages")
+ exl = params.get("export_state_layers")
+ exn = params.get("export_state_norm_keys")
+ return (
+ self.dev.index, x.shape[0], x.shape[1], bt.shape[1], id(params["cache"]),
+ tuple(x.shape), x.dtype, bt.dtype, cs.dtype, tuple(cs.shape),
+ None if (pos is None or pos is cs) else (tuple(pos.shape), pos.dtype),
+ bool(params.get("dflash_verify")), bool(params.get("recurrent_history")),
+ # per-job page counts feed only the MLA decode kernel's KV split (mla_attn.py); MLAttention models
+ # never get here (_check_model), and with B jobs they would recapture whenever one job crosses 16 pages
+ None if CUDA_GRAPH_MULTI else (tuple(pages) if pages is not None else None),
+ (self.has_gdn, self.has_mamba), tuple(sorted(exl)) if exl else None, tuple(sorted(exn)) if exn else None,
+ tuple(int(s) for s in params["recurrent_slots"].tolist()) if self.has_conv else None, # every job's conv slot is baked in
+ tuple(r.slot for r in params["recurrent_states"]) if self.has_swa else None, # per-slot ring block table is baked in
+ )
+
+ def _new_entry(self, key, x, params):
+ while len(self.entries) >= CUDA_GRAPH_MAX:
+ old = next(iter(self.entries))
+ self._drop(old, sync = True)
+ self.stats["evictions"] = self.stats.get("evictions", 0) + 1
+ dev = self.dev
+ bt, cs, pos = params["block_table"], params["cache_seqlens"], params.get("positions")
+ e = _Entry()
+ e.graph = None
+ e.out = None
+ e.warm = 0
+ e.last_used = 0
+ e.cache_ref = weakref.ref(params["cache"])
+ e.fp = _cache_fp(params["cache"])
+ e.slots = e.slots_src = e.exports = e.swa_cs = e.swa_host = None
+ with torch.cuda.device(dev):
+ e.x_in = torch.empty(x.shape, dtype = x.dtype, device = dev)
+ e.bt = torch.zeros(bt.shape, dtype = bt.dtype, device = dev)
+ e.cs = torch.zeros(cs.shape, dtype = cs.dtype, device = dev)
+ e.pos = None if (pos is None or pos is cs) else torch.zeros(pos.shape, dtype = pos.dtype, device = dev)
+ if self.has_swa:
+ e.swa_cs = torch.zeros(x.shape[0], dtype = torch.int32, device = dev)
+ e.swa_host = torch.zeros(x.shape[0], dtype = torch.int32).pin_memory()
+ if self.has_gdn or self.has_mamba:
+ # Fixed-address slot buffer refreshed only when the live slot
+ # tensor object changes (stable across steps for one job, so
+ # the capture never bakes a per-step upload address).
+ e.slots = torch.zeros(params["recurrent_slots"].shape, dtype = torch.int32, device = dev)
+ # Params dict for warmup and capture: static CUDA tensors, nothing host-resident. dev_cache,
+ # input_ids and layer_instance are per-call and are rebuilt by the modules
+ p = {k: v for k, v in params.items() if k not in ("dev_cache", "input_ids", "layer_instance")}
+ p["block_table"] = e.bt
+ p["cache_seqlens"] = e.cs
+ p["positions"] = e.cs if e.pos is None else e.pos
+ if e.slots is not None:
+ p["recurrent_slots"] = e.slots
+ if e.swa_cs is not None:
+ p["swa_cs"] = e.swa_cs
+ e.params = p
+ self.entries[key] = e
+ return e
+
+ def _load(self, e, x, params):
+ """Per-step values into the static buffers (stream-ordered on the current stream)."""
+ # Multi-job (EXL3_CUDA_GRAPH_MULTI) per-job state, all either keyed or copied here, nothing else is read
+ # inside the capture: job order / join / leave -> row order of x, block table, cache_seqlens, positions
+ # and the slot tuple change, all copied below (B, Q, table width are in the key, so a count or width
+ # change selects/creates another entry); per-job page counts (dflash_table_pages) only feed MLA (see
+ # _key); recurrent_states (per-job host position / rewind) are touched only by Model.forward after the
+ # replay and by the generator; state tensors are cache-owned with fixed pointers (_cache_fp), the slot
+ # ids select the row inside them; BC split config derives from the (keyed) table width, not from the
+ # cache lengths; per-job sampling state never enters the forward.
+ e.x_in.copy_(x, non_blocking = True)
+ e.bt.copy_(params["block_table"], non_blocking = True)
+ e.cs.copy_(params["cache_seqlens"], non_blocking = True)
+ if e.pos is not None:
+ e.pos.copy_(params["positions"], non_blocking = True)
+ if e.swa_cs is not None:
+ # window shift (rare, eager copies) + in-state seqlens of this step, then into the static buffer
+ from ..modules.sliding_attn import swa_graph_prep
+ cs = swa_graph_prep(params["cache"], self.swa_mods, params["recurrent_states"], x.shape[1])
+ e.swa_host.copy_(torch.tensor(cs, dtype = torch.int32))
+ e.swa_cs.copy_(e.swa_host, non_blocking = True)
+ if e.slots is not None:
+ # Slot ids as data: the live slot tensor is immutable per slot tuple (cached, with a persistent
+ # device copy); refresh the graph's fixed-address buffer only when the source object changes.
+ # Holding the reference makes the identity test exact (a recycled address cannot alias it)
+ live = params["recurrent_slots"]
+ if live is not e.slots_src:
+ from ..util.tensor import get_for_device
+ e.slots.copy_(get_for_device(params, "recurrent_slots", self.dev))
+ e.slots_src = live
+
+ def _capture(self, key, e, tail, x, params) -> bool:
+ dev = self.dev
+ for d in range(torch.cuda.device_count()):
+ if torch.cuda.memory_allocated(d) > 0:
+ torch.cuda.synchronize(d)
+ g = torch.cuda.CUDAGraph()
+ try:
+ with torch.cuda.device(dev):
+ stream = _stream_for(dev.index)
+ with torch.cuda.graph(g, pool = _pool_for(dev.index), stream = stream,
+ capture_error_mode = "thread_local"):
+ assert torch.cuda.is_current_stream_capturing()
+ pc = dict(e.params)
+ out = self._run_tail(tail, e.x_in, pc)
+ except Exception as ex:
+ self._drop(key)
+ self.disabled.add(key)
+ self.stats["declines"][f"capture_error:{type(ex).__name__}"] += 1
+ self.stats["capture_error_msg"] = repr(ex)[:500]
+ if CUDA_GRAPH_FALLBACK == "eager":
+ return False # diagnostic only: captured-region work may have run for real
+ raise
+ e.graph = g
+ e.out = out
+ e.exports = list(pc["export_states"]) if pc.get("export_states") else None
+ self.stats["captures"] += 1
+ if CUDA_GRAPH_DEBUG:
+ print(f"[cudagraph] captured key={key[1:5]}", flush = True)
+ return True
+
+ def _drop(self, key, sync: bool = False):
+ e = self.entries.pop(key, None)
+ if e is not None and (sync or e.graph is not None):
+ try:
+ torch.cuda.synchronize(self.dev)
+ except Exception:
+ pass
+ del e
+
+ def clear(self):
+ if self.entries:
+ try:
+ torch.cuda.synchronize(self.dev)
+ except Exception:
+ pass
+ self.entries.clear()
+ self.disabled.clear()
+ self._model_ok = None
+
+
+def maybe_forward(model, ids: torch.Tensor, params: dict):
+ """Hook for Model.forward (non-TP branch). Returns the logits, or None to run the eager path."""
+ if not CUDA_GRAPH_ENABLED or torch.version.hip or not torch.cuda.is_available():
+ return None
+ r = model.__dict__.get("_cuda_graph_runner")
+ if r is None:
+ r = model.__dict__["_cuda_graph_runner"] = CudaGraphRunner(model)
+ return r.forward(ids, params)
+
+
+def purge(model = None):
+ """Release graphs (every runner, or one model's). Harness arms / model unload."""
+ for ref in list(_registry):
+ r = ref()
+ if r is None:
+ _registry.remove(ref)
+ elif model is None or r.model is model:
+ r.clear()
+ if model is None:
+ _pools.clear()
+ _streams.clear()
diff --git a/exllamav3/model/dense_gemm_tune_seed.txt b/exllamav3/model/dense_gemm_tune_seed.txt
index a17dafd..4255558 100644
--- a/exllamav3/model/dense_gemm_tune_seed.txt
+++ b/exllamav3/model/dense_gemm_tune_seed.txt
@@ -136,3 +136,331 @@
5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 2560 30208 1 0 -1162086307
5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 2560 30976 1 0 0
5.0.2.20250912-42-1199-g2584e35062|gfx1151|exact1 2560 2560 32000 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 256 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 512 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 768 1 0 -1162084884
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 1024 1 0 -1162084890
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 1024 3 0 -1162084891
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 1280 1 0 -1162084883
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 1280 3 0 -1162084883
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 1536 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 1536 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 1792 1 0 -1162084846
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 1792 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 2048 1 0 -1162084871
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 2048 3 0 -1162084849
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 2304 1 0 -1162084883
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 2304 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 2560 1 0 -1162084875
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 2560 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 2816 1 0 -1162084900
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 2816 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 3072 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 3072 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 3328 1 0 -1162084872
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 3328 3 0 -1162084875
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 3584 1 0 -1162084872
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 3584 3 0 -1162084876
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 3840 1 0 -1162084872
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 3840 3 0 -1162084874
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 4096 1 0 -1162084872
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 4096 3 0 -1162084872
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 4352 1 0 -1162084875
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 4352 3 0 -1162084883
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 4608 1 0 -1162084872
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 4608 3 0 -1162084872
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 4864 1 0 -1162084875
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 4864 3 0 -1162084872
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 5120 1 0 -1162084890
+5.4.0.f000f7786e|gfx1151|exact1 512 2560 5120 3 0 -1162084890
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 256 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 512 1 0 -1162084875
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 768 1 0 -1162084876
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 1024 1 0 -1162084874
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 1024 3 0 -1162084889
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 1280 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 1280 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 1536 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 1536 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 1792 1 0 -1162084840
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 1792 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 2048 1 0 -1162084902
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 2048 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 2304 1 0 -1162084897
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 2304 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 2560 1 0 -1162084902
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 2560 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 2816 1 0 -1162084877
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 2816 3 0 -1162084889
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 3072 1 0 -1162084875
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 3072 3 0 -1162084885
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 3328 1 0 -1162084883
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 3328 3 0 -1162084874
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 3584 1 0 -1162084875
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 3584 3 0 -1162084891
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 3840 1 0 -1162084883
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 3840 3 0 -1162084876
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 4096 1 0 -1162084872
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 4096 3 0 -1162084875
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 4352 1 0 -1162084900
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 4352 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 4608 1 0 -1162084900
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 4608 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 4864 1 0 -1162084897
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 4864 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 5120 1 0 -1162084897
+5.4.0.f000f7786e|gfx1151|exact1 640 2560 5120 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 1152 1152 11008 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 1152 1536 11008 1 1 0
+5.4.0.f000f7786e|gfx1151|exact1 1152 4352 11008 1 0 -1162084842
+5.4.0.f000f7786e|gfx1151|exact1 2560 640 256 1 0 -1162084883
+5.4.0.f000f7786e|gfx1151|exact1 2560 640 512 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 640 768 1 0 -1162084885
+5.4.0.f000f7786e|gfx1151|exact1 2560 640 1024 1 0 -1162084891
+5.4.0.f000f7786e|gfx1151|exact1 2560 640 1280 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 640 1536 1 0 -1162084819
+5.4.0.f000f7786e|gfx1151|exact1 2560 640 1792 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 640 2048 1 0 -1162084825
+5.4.0.f000f7786e|gfx1151|exact1 2560 640 2304 1 0 -1162084878
+5.4.0.f000f7786e|gfx1151|exact1 2560 640 2560 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 640 2816 1 0 -1162084882
+5.4.0.f000f7786e|gfx1151|exact1 2560 640 3072 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 640 3328 1 0 -1162084825
+5.4.0.f000f7786e|gfx1151|exact1 2560 640 3584 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 640 3840 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 640 4096 1 0 -1162084837
+5.4.0.f000f7786e|gfx1151|exact1 2560 640 4352 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 640 4608 1 0 -1162084901
+5.4.0.f000f7786e|gfx1151|exact1 2560 640 4864 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 640 5120 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 256 1 0 -1162084883
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 512 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 768 1 0 -1162084873
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 1024 1 0 -1162084872
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 1024 3 0 -1162084875
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 1280 1 0 -1162084850
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 1280 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 1536 1 0 -1162084872
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 1536 3 0 -1162084875
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 1792 1 0 -1162084883
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 1792 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 2048 1 0 -1162084897
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 2048 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 2304 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 2304 3 0 -1162084891
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 2560 1 0 -1162084897
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 2560 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 2816 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 2816 3 0 -1162084808
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 3072 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 3072 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 3328 1 0 -1162084897
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 3328 3 0 -1162084807
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 3584 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 3584 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 3840 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 3840 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 4096 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 4096 3 0 -1162084807
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 4352 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 4352 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 4608 1 0 -1162084897
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 4608 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 4864 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 4864 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 5120 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 5120 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 5376 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 5632 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 5888 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 6144 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 6400 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 6656 1 0 -1162084897
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 6912 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 7168 1 0 -1162084897
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 7424 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 7680 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 7936 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 8192 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 8448 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 8704 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 8960 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 9216 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 9472 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 9728 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 9984 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 10240 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 10496 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 10752 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 11008 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 11264 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 11520 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 11776 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 12032 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 12288 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 12544 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 12800 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 13056 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 13312 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 13568 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 13824 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 14080 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 14336 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 14592 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 14848 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 15104 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 15360 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 15616 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 15872 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 16128 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 16384 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 16640 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 16896 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 17152 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 17408 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 17664 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 17920 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 18176 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 18432 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 18688 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 18944 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 19200 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 19456 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 19712 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 19968 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 20224 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 2560 20480 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 4608 2816 1 0 -1162084806
+5.4.0.f000f7786e|gfx1151|exact1 2560 6144 256 1 0 -1162084883
+5.4.0.f000f7786e|gfx1151|exact1 2560 6144 512 1 0 -1162084903
+5.4.0.f000f7786e|gfx1151|exact1 2560 6144 768 1 0 -1162084902
+5.4.0.f000f7786e|gfx1151|exact1 2560 6144 1024 3 0 -1162084889
+5.4.0.f000f7786e|gfx1151|exact1 2560 6144 1280 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 6144 1536 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 6144 1792 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 6144 2048 3 0 -1162084897
+5.4.0.f000f7786e|gfx1151|exact1 2560 6144 2304 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 6144 2560 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 6144 2816 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 6144 3072 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 6144 3328 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 6144 3584 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 6144 3840 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 6144 4096 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 6144 4352 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 6144 4608 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 6144 4864 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 2560 6144 5120 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 4352 1152 11008 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 4608 4608 2816 1 0 -1162084905
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 256 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 512 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 768 1 0 -1162084814
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 1024 1 0 -1162084814
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 1024 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 1280 1 0 -1162084897
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 1280 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 1536 1 0 -1162084897
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 1536 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 1792 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 1792 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 2048 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 2048 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 2304 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 2304 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 2560 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 2560 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 2816 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 2816 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 3072 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 3072 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 3328 1 0 -1162084840
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 3328 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 3584 1 0 -1162084897
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 3584 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 3840 1 0 -1162084897
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 3840 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 4096 1 0 -1162084897
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 4096 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 4352 1 0 -1162084900
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 4352 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 4608 1 0 -1162084897
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 4608 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 4864 1 0 -1162084897
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 4864 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 5120 1 0 -1162084900
+5.4.0.f000f7786e|gfx1151|exact1 6144 2560 5120 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 256 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 512 1 0 -1162084900
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 768 1 0 -1162084863
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 1024 1 0 -1162084900
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 1024 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 1280 1 0 -1162084848
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 1280 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 1536 1 0 -1162084900
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 1536 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 1792 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 1792 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 2048 1 0 -1162084900
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 2048 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 2304 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 2304 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 2560 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 2560 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 2816 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 2816 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 3072 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 3072 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 3328 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 3328 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 3584 1 0 -1162084900
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 3584 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 3840 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 3840 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 4096 1 0 -1162084900
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 4096 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 4352 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 4352 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 4608 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 4608 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 4864 1 0 -1162084900
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 4864 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 5120 1 0 -1162084900
+5.4.0.f000f7786e|gfx1151|exact1 10240 2560 5120 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 256 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 512 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 768 1 0 -1162084902
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 1024 1 0 -1162084900
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 1024 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 1280 1 0 -1162084900
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 1280 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 1536 1 0 -1162084900
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 1536 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 1792 1 0 -1162084902
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 1792 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 2048 1 0 -1162084903
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 2048 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 2304 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 2304 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 2560 1 0 -1162084900
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 2560 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 2816 1 0 -1162084903
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 2816 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 3072 1 0 -1162084900
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 3072 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 3328 1 0 0
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 3328 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 3584 1 0 -1162084900
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 3584 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 3840 1 0 -1162084903
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 3840 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 4096 1 0 -1162084900
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 4096 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 4352 1 0 -1162084900
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 4352 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 4608 1 0 -1162084900
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 4608 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 4864 1 0 -1162084900
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 4864 3 0 0
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 5120 1 0 -1162084900
+5.4.0.f000f7786e|gfx1151|exact1 12288 2560 5120 3 0 0
diff --git a/exllamav3/model/dense_warmup.py b/exllamav3/model/dense_warmup.py
index a87cf72..0f23f79 100644
--- a/exllamav3/model/dense_warmup.py
+++ b/exllamav3/model/dense_warmup.py
@@ -57,33 +57,50 @@ def warm_dense_gemm(models, max_rows: int = 4096, log=print) -> dict:
mem0 = torch.cuda.memory_allocated()
torch.cuda.reset_peak_memory_stats()
calls = 0
+ # A cold tune cache (no shipped seed for this library version) pays a rocBLAS screening per key, minutes in total.
+ # Past the budget the rest of the warm-up runs untuned (bit-exact, same output); the first request at a class that
+ # is still missing tunes it then. EXL3_WARM_TUNE_BUDGET_S=0 never defers.
+ budget = float(os.environ.get("EXL3_WARM_TUNE_BUDGET_S", "90"))
+ tune_env = os.environ.get("EXL3_DENSE_GEMM_TUNE")
+ deferred = False
nclass = (max_rows + 255) // 256
- for model in models:
- if model is None:
- continue
- for lin in _dense_linears(model):
- k = lin.in_features
- # The MTP input projection runs per stream: tokens x hc_count rows (4 x 4096 = class 64).
- mult = 4 if lin.key.endswith("mtp.fc_hidden") else 1
- rows_list = list(SMALL_ROWS) + [256 * c for c in range(1, nclass * mult + 1)]
- for rows in rows_list:
- # unpadded input (contiguous), and the row-padded input a producer gives (only above PAD_MIN_ROWS, and only
- # for activations of at most one prefill chunk: the per-stream MTP rows are never producer-padded)
- pitches = [0]
- if rows <= max_rows:
- p = row_pad_pitch(lin, k, rows, {})
- if p:
- pitches.append(p)
- for pitch in pitches:
- buf = torch.randn((rows, pitch or k), device=lin.device, dtype=torch.half).mul_(0.1)
- x = buf[:, :k] if pitch else buf
- lin.forward(x, {})
- calls += 1
- del buf, x
- torch.cuda.synchronize()
- torch.cuda.synchronize()
+ try:
+ for model in models:
+ if model is None:
+ continue
+ for lin in _dense_linears(model):
+ k = lin.in_features
+ # The MTP input projection runs per stream: tokens x hc_count rows (4 x 4096 = class 64).
+ mult = 4 if lin.key.endswith("mtp.fc_hidden") else 1
+ rows_list = list(SMALL_ROWS) + [256 * c for c in range(1, nclass * mult + 1)]
+ for rows in rows_list:
+ # unpadded input (contiguous), and the row-padded input a producer gives (only above PAD_MIN_ROWS, and only
+ # for activations of at most one prefill chunk: the per-stream MTP rows are never producer-padded)
+ pitches = [0]
+ if rows <= max_rows:
+ p = row_pad_pitch(lin, k, rows, {})
+ if p:
+ pitches.append(p)
+ for pitch in pitches:
+ buf = torch.randn((rows, pitch or k), device=lin.device, dtype=torch.half).mul_(0.1)
+ x = buf[:, :k] if pitch else buf
+ lin.forward(x, {})
+ calls += 1
+ if budget > 0 and not deferred and rows > 255 and time.perf_counter() - t0 > budget:
+ deferred = True
+ os.environ["EXL3_DENSE_GEMM_TUNE"] = "0"
+ log(f"warm_dense_gemm: tune budget {budget:.0f} s used, remaining classes tune at first use")
+ del buf, x
+ torch.cuda.synchronize()
+ torch.cuda.synchronize()
+ finally: # an error in a forward must not leave the tune switched off for the rest of the process
+ if deferred:
+ if tune_env is None:
+ os.environ.pop("EXL3_DENSE_GEMM_TUNE", None)
+ else:
+ os.environ["EXL3_DENSE_GEMM_TUNE"] = tune_env
peak = torch.cuda.max_memory_allocated() - mem0
torch.cuda.empty_cache()
- st = {"seconds": time.perf_counter() - t0, "calls": calls, "peak_extra_mib": peak / 2**20}
+ st = {"seconds": time.perf_counter() - t0, "calls": calls, "deferred": deferred, "peak_extra_mib": peak / 2**20}
log(f"warm_dense_gemm: {calls} calls in {st['seconds']:.1f} s, transient peak {st['peak_extra_mib']:.0f} MiB")
return st
diff --git a/exllamav3/model/model.py b/exllamav3/model/model.py
index a0811fd..1fa01b8 100644
--- a/exllamav3/model/model.py
+++ b/exllamav3/model/model.py
@@ -9,6 +9,7 @@ from .model_tp import Model_TPMixin
from .model_ls import Model_LSMixin
from ..util.tensor import g_tensor_cache
from ..cache.recurrent_util import advance_recurrent_states
+from . import cuda_graph as _cuda_graph
import os
class Model(Model_TPMixin, Model_LSMixin):
@@ -230,6 +231,12 @@ class Model(Model_TPMixin, Model_LSMixin):
advance_recurrent_states(input_ids, params, self)
return y
else:
+ if _cuda_graph.CUDA_GRAPH_ENABLED:
+ # opt-in whole-forward CUDA graph (decode only); None = declined, run eager below
+ y = _cuda_graph.maybe_forward(self, x, params)
+ if y is not None:
+ advance_recurrent_states(input_ids, params, self)
+ return y
for m in self._get_prefetch_layers:
m.prefetch(x, params)
y = self.forward_ls(x, params)
@@ -238,6 +245,7 @@ class Model(Model_TPMixin, Model_LSMixin):
def unload(self):
+ _cuda_graph.purge(self)
for module in self.modules:
module.unload()
# The loader's open slab blocks must not outlive the tensors sliced from them
diff --git a/exllamav3/modules/arch_specific/dflash2.py b/exllamav3/modules/arch_specific/dflash2.py
new file mode 100644
index 0000000..29b3371
--- /dev/null
+++ b/exllamav3/modules/arch_specific/dflash2.py
@@ -0,0 +1,397 @@
+# ported from exllamav3 1.6.0, MIT, (c) turboderp
+"""
+DFlash2-specific modules: grouped dynamic convolutions, the conv-wrapped
+transformer block, and the top-k candidate selector.
+
+Reference: the ``DFlash2DraftModel`` implementation in the ``dflash`` package.
+
+The residual stream stays in fp32, matching the standard transformer path.
+RMSNorm and convolution prepare outputs are fp16; convolution finish returns
+fp32 before the residual add.
+"""
+
+from __future__ import annotations
+from typing_extensions import override
+import torch
+import torch.nn.functional as F
+
+from ...model.config import Config
+from .. import Module, Linear, RMSNorm, Attention, GatedMLP
+from ...util.tensor import to2
+
+from ...ext import exllamav3_ext as ext
+
+# Absent on ROCm builds and on extensions built before the DFlash2 kernels
+HAS_DFLASH2 = getattr(ext, "HAS_DFLASH2", False)
+
+
+def _grouped_dynamic_convolve_torch(
+ hidden: torch.Tensor,
+ dynamic: torch.Tensor,
+ base: torch.Tensor,
+ group_size: int,
+ residual: torch.Tensor | None = None,
+) -> torch.Tensor:
+ batch, length, hidden_size = hidden.shape
+ groups = hidden_size // group_size
+ blocks = hidden.float().view(batch, length, groups, group_size)
+ dynamic = dynamic.float().view(batch, length, base.shape[0], groups, 1)
+ output = torch.zeros_like(blocks)
+ for offset in range(min(base.shape[0], length)):
+ values = blocks[:, : length - offset]
+ kernel = base[offset].float().view(1, 1, groups, group_size)
+ weights = kernel + dynamic[:, offset:, offset]
+ output[:, offset:] += weights * values
+ output = output.view(batch, length, hidden_size)
+ if residual is not None:
+ residual += output
+ return residual
+ return output.to(hidden.dtype)
+
+
+def _grouped_dynamic_convolve(
+ hidden: torch.Tensor,
+ dynamic: torch.Tensor,
+ base: torch.Tensor,
+ group_size: int,
+ residual: torch.Tensor | None = None,
+) -> torch.Tensor:
+ """Transcribed from dflash.model._grouped_dynamic_convolve.
+
+ hidden [b, l, H]; dynamic [b, l, taps, H//group_size] (any strides); base [taps, H].
+ output[t] = sum_taps base[tap] * x[t - tap] + dyn[tap][t] * x[t - tap]
+ (causal; tap 0 = current position). Result has hidden's dtype, or, with residual (fp32
+ [b, l, H]), is added into residual in place and residual is returned (the finish()
+ variant's residual add, fused into the kernel).
+ """
+ # TODO: HIP version
+ if not hidden.is_cuda or not HAS_DFLASH2:
+ return _grouped_dynamic_convolve_torch(hidden, dynamic, base, group_size, residual)
+ hidden = hidden.contiguous()
+ if residual is not None:
+ ext.dflash2_dynconv(hidden, dynamic, base, residual, group_size, True)
+ return residual
+ output = torch.empty_like(hidden)
+ ext.dflash2_dynconv(hidden, dynamic, base, output, group_size, False)
+ return output
+
+
+class DFlash2DynConv(Module):
+ """Two-tap grouped dynamic conv (dflash ``GroupedDynamicCausalConv``).
+
+ Checkpoint tensors (raw, unquantized, bf16):
+ {key}.base_kernel [2, kernel_size, hidden] (prepare base, finish base)
+ {key}.kernel_projection Linear(hidden -> 2 * kernel_size * groups)
+
+ prepare() uses fp16 input/output. finish() adds the fp32 result into the block's
+ fp32 residual stream in place (one kernel, no separate add).
+ """
+
+ def __init__(
+ self,
+ config: Config,
+ key: str,
+ hidden_size: int,
+ kernel_size: int,
+ group_size: int,
+ qmap: str | None = None,
+ ):
+ super().__init__(config, key, None)
+ self.module_name = "DFlash2DynConv"
+ self.hidden_size = hidden_size
+ self.kernel_size = kernel_size
+ self.group_size = group_size
+ self.groups = hidden_size // group_size
+
+ self.proj = Linear(
+ config = config,
+ key = f"{key}.kernel_projection",
+ in_features = hidden_size,
+ out_features = 2 * kernel_size * self.groups,
+ qmap = qmap,
+ trim_padded_out = True,
+ )
+ self.register_submodule(self.proj)
+
+ self.base_kernel = None
+ self.key_base_kernel = f"{key}.base_kernel"
+ self.base_kernel_numel = 2 * kernel_size * hidden_size
+ self.caps.update({"x_cpu": True})
+
+ def optimizer_targets(self):
+ return []
+
+ @override
+ def weights_numel(self):
+ return self.base_kernel_numel + super().weights_numel()
+
+ @override
+ def load(self, device: torch.device, **kwargs):
+ super().load(device, **kwargs)
+ self.base_kernel = self.config.stc.get_tensor(
+ self.key_base_kernel, self.device, optional = False, allow_bf16 = True
+ )
+ expected_shape = (2, self.kernel_size, self.hidden_size)
+ if self.base_kernel.shape != expected_shape:
+ raise ValueError(
+ f"Expected {self.key_base_kernel} shape {expected_shape}, "
+ f"got {tuple(self.base_kernel.shape)}"
+ )
+
+ @override
+ def unload(self):
+ self.base_kernel = None
+ super().unload()
+
+ @override
+ def get_tensors(self):
+ t = super().get_tensors()
+ if self.base_kernel is not None:
+ t[self.key_base_kernel] = self.base_kernel.contiguous()
+ return t
+
+ def prepare(self, x: torch.Tensor, params: dict):
+ """x [b, l, H] (post-norm) -> (convolved half, finish-time dynamic half)"""
+ x = x.half()
+ dyn = self.proj.forward(x, params)
+ dyn = dyn.view(*x.shape[:-1], 2, self.kernel_size, self.groups)
+ y = _grouped_dynamic_convolve(
+ x, dyn[..., 0, :, :], self.base_kernel[0], self.group_size)
+ return y, dyn[..., 1, :, :]
+
+ def finish(self, x: torch.Tensor, dynamic: torch.Tensor, residual: torch.Tensor | None = None) -> torch.Tensor:
+ """Sublayer output x [b, l, H] (fp16 or fp32) -> conv result in fp32, or, with residual
+ (fp32 [b, l, H]), residual += conv result in place (returned)"""
+ if residual is not None:
+ return _grouped_dynamic_convolve(
+ x, dynamic, self.base_kernel[1], self.group_size, residual = residual)
+ return _grouped_dynamic_convolve(
+ x.float(), dynamic, self.base_kernel[1], self.group_size)
+
+ @override
+ def forward(self, x: torch.Tensor, params: dict, out_dtype = None):
+ y, dyn = self.prepare(x, params)
+ return to2(self.finish(y, dyn), out_dtype, torch.float)
+
+
+class DFlash2Block(Module):
+ """Reference DFlash2 decoder layer (Qwen3DFlashDecoderLayer):
+
+ r = x; x = attn_norm(x); x, k = attn_conv.prepare(x); x = attn(x);
+ x = attn_conv.finish(x, k); x = r + x
+ r = x; x = mlp_norm(x); x, k = mlp_conv.prepare(x); x = mlp(x);
+ x = mlp_conv.finish(x, k); x = r + x
+
+ Residual stream fp32; normed sub-ops fp16. The residual adds are fused into the
+ finish() convolutions.
+ """
+
+ def __init__(
+ self,
+ config: Config,
+ key: str,
+ layer_idx: int,
+ attn: Attention,
+ mlp: GatedMLP,
+ attn_norm: RMSNorm,
+ mlp_norm: RMSNorm,
+ attn_conv: DFlash2DynConv,
+ mlp_conv: DFlash2DynConv,
+ ):
+ super().__init__(config, key, None)
+ self.module_name = "DFlash2Block"
+ self.layer_idx = layer_idx
+ self.attn = attn
+ self.mlp = mlp
+ self.attn_norm = attn_norm
+ self.mlp_norm = mlp_norm
+ self.attn_conv = attn_conv
+ self.mlp_conv = mlp_conv
+ for m in (attn, mlp, attn_norm, mlp_norm, attn_conv, mlp_conv):
+ self.register_submodule(m)
+
+ def optimizer_targets(self):
+ return [self.attn.optimizer_targets(), self.mlp.optimizer_targets()]
+
+ @override
+ def forward(self, x: torch.Tensor, params: dict, out_dtype = None):
+ x = x.float() if x.dtype != torch.float else x
+ y = self.attn_norm.forward(x, params, out_dtype = torch.half)
+ y, kernel = self.attn_conv.prepare(y, params)
+ y = self.attn.forward(y, params)
+ x = self.attn_conv.finish(y, kernel, residual = x)
+
+ y = self.mlp_norm.forward(x, params, out_dtype = torch.half)
+ y, kernel = self.mlp_conv.prepare(y, params)
+ y = self.mlp.forward(y, params)
+ x = self.mlp_conv.finish(y, kernel, residual = x)
+
+ return to2(x, out_dtype, torch.float)
+
+
+class DFlash2Selector(Module):
+ """Top-k candidate selector (dflash ``CandidateSelector``).
+
+ Checkpoint tensors (raw, unquantized, BARE keys — no .weight suffix):
+ candidate_selector.predecessor_codebook [vocab, rank]
+ candidate_selector.successor_codebook [vocab, rank]
+ candidate_selector.hidden_projection Linear(hidden -> rank, no bias)
+
+ walk(): top-k(16) per row from draft logits, then greedy chained walk
+ S_t(a, b) = U_t(b) + <A(a) ⊙ H(h_t), B(b)>, a = previous path token
+ """
+
+ def __init__(
+ self,
+ config: Config,
+ key: str,
+ vocab_size: int,
+ hidden_size: int,
+ rank: int,
+ top_k: int,
+ ):
+ super().__init__(config, key, None)
+ self.module_name = "DFlash2Selector"
+ self.vocab_size = vocab_size
+ self.rank = rank
+ self.top_k = top_k
+
+ self.hidden_proj = Linear(
+ config = config,
+ key = f"{key}.hidden_projection",
+ in_features = hidden_size,
+ out_features = rank,
+ trim_padded_out = True,
+ )
+ self.register_submodule(self.hidden_proj)
+
+ self.key_pred = f"{key}.predecessor_codebook"
+ self.key_succ = f"{key}.successor_codebook"
+ self.pred_codebook = None
+ self.succ_codebook = None
+ self.caps.update({"x_cpu": True})
+
+ def optimizer_targets(self):
+ return []
+
+ @override
+ def weights_numel(self):
+ return 2 * self.vocab_size * self.rank + super().weights_numel()
+
+ def forward(self, x: torch.Tensor, params: dict, out_dtype = None):
+ # The selector is part of the module list so loading, autosplit and compilation account
+ # for its tensors. Proposal generation invokes walk() after the shared target LM head.
+ return to2(x, out_dtype, None)
+
+ @override
+ def load(self, device: torch.device, **kwargs):
+ super().load(device, **kwargs)
+ # Older trainers append .weight to the bare codebook keys;
+ # try bare first, fall back to suffixed (same bytes either way).
+ self.pred_codebook = self.config.stc.get_tensor(
+ self.key_pred, self.device, optional = True, allow_bf16 = True)
+ if self.pred_codebook is None:
+ self.pred_codebook = self.config.stc.get_tensor(
+ self.key_pred + ".weight", self.device, optional = False, allow_bf16 = True)
+ self.succ_codebook = self.config.stc.get_tensor(
+ self.key_succ, self.device, optional = True, allow_bf16 = True)
+ if self.succ_codebook is None:
+ self.succ_codebook = self.config.stc.get_tensor(
+ self.key_succ + ".weight", self.device, optional = False, allow_bf16 = True)
+ expected_shape = (self.vocab_size, self.rank)
+ if self.pred_codebook.shape != expected_shape:
+ raise ValueError(
+ f"Expected {self.key_pred} shape {expected_shape}, "
+ f"got {tuple(self.pred_codebook.shape)}"
+ )
+ if self.succ_codebook.shape != expected_shape:
+ raise ValueError(
+ f"Expected {self.key_succ} shape {expected_shape}, "
+ f"got {tuple(self.succ_codebook.shape)}"
+ )
+
+ @override
+ def unload(self):
+ self.pred_codebook = None
+ self.succ_codebook = None
+ super().unload()
+
+ @override
+ def get_tensors(self):
+ t = super().get_tensors()
+ if self.pred_codebook is not None:
+ t[self.key_pred] = self.pred_codebook.contiguous()
+ t[self.key_succ] = self.succ_codebook.contiguous()
+ return t
+
+ def walk(
+ self,
+ hidden: torch.Tensor, # [b, rows, H] post-norm draft state
+ logits: torch.Tensor, # [b, rows, V] float draft logits
+ anchor_ids: torch.Tensor, # [b]
+ return_confidence: bool = False,
+ ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
+ """Greedily rerank each row's top-k tokens, conditioned on the preceding token.
+ Returns the path [b, rows] (and per-row winning scores [b, rows])."""
+ out, conf = self.walk_block(hidden, logits, anchor_ids, return_confidence)
+ if return_confidence:
+ return out[:, 1:], conf[:, 1:]
+ return out[:, 1:]
+
+
+ def walk_block(
+ self,
+ hidden: torch.Tensor,
+ logits: torch.Tensor,
+ anchor_ids: torch.Tensor,
+ return_confidence: bool = False,
+ vocab_size: int | None = None,
+ scale: float = 1.0,
+ softcap: float = 0.0,
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
+ """walk() in the generator's block layout: ids [b, rows + 1] = [anchor, path...] and,
+ when requested, confidence [b, rows + 1] = [0, winning score...]. logits may be wider
+ than vocab_size (padded head) and are scaled / softcapped on the fly. On CUDA the top-k
+ and the whole chain run as two kernels (no per-row host round trip, no torch
+ intermediates)."""
+ vocab_size = vocab_size or logits.shape[-1]
+ # The generator passes state[:, 1:], a strided view for more than one row, and .half() on
+ # an fp16 state returns that view as is
+ gate = self.hidden_proj.forward(hidden.half().contiguous(), params = {})
+ anchor_ids = anchor_ids.long()
+ bsz, rows = logits.shape[:2]
+ cuda = HAS_DFLASH2 and hidden.is_cuda and self.pred_codebook.dtype in (torch.half, torch.bfloat16)
+ if cuda and self.top_k in (8, 16, 32) and logits.stride(-1) == 1:
+ unary = torch.empty((bsz, rows, self.top_k), dtype = torch.float, device = hidden.device)
+ cands = torch.empty((bsz, rows, self.top_k), dtype = torch.long, device = hidden.device)
+ ext.dflash2_topk(logits, vocab_size, scale, softcap, unary, cands)
+ else:
+ logits = logits[..., :vocab_size].float() * scale
+ if softcap > 0.0:
+ logits = torch.tanh(logits / softcap) * softcap
+ unary, cands = torch.topk(logits, self.top_k, dim = -1, sorted = False)
+ if cuda:
+ out = torch.empty((bsz, rows + 1), dtype = torch.long, device = hidden.device)
+ conf = torch.empty((bsz, rows + 1), dtype = torch.float, device = hidden.device) if return_confidence else None
+ ext.dflash2_selector_walk(
+ unary.float().contiguous(), cands.long().contiguous(), gate.contiguous(),
+ self.pred_codebook, self.succ_codebook, anchor_ids.to(hidden.device, non_blocking = anchor_ids.is_pinned()).contiguous(), out, conf,
+ )
+ return out, conf
+ return self._walk_torch(unary.float(), cands.long(), gate.float(), anchor_ids, return_confidence)
+
+
+ def _walk_torch(self, unary, cands, gate, anchor_ids, return_confidence):
+ pred = anchor_ids
+ path = [pred]
+ confidence = [torch.zeros_like(pred, dtype = torch.float)]
+ for i in range(unary.shape[1]):
+ a_emb = F.embedding(pred, self.pred_codebook).float()
+ b_emb = F.embedding(cands[:, i], self.succ_codebook).float()
+ scores = unary[:, i] + torch.einsum("br,bkr->bk", a_emb * gate[:, i], b_emb)
+ score, idx = torch.max(scores, dim = -1)
+ pred = cands[:, i].gather(-1, idx[:, None])[:, 0]
+ path.append(pred)
+ confidence.append(score)
+ out = torch.stack(path, dim = 1)
+ return out, (torch.stack(confidence, dim = 1) if return_confidence else None)
diff --git a/exllamav3/modules/attention_fn/bc_attn.py b/exllamav3/modules/attention_fn/bc_attn.py
index a9a1f76..f9014c6 100644
--- a/exllamav3/modules/attention_fn/bc_attn.py
+++ b/exllamav3/modules/attention_fn/bc_attn.py
@@ -263,11 +263,29 @@ class BCAttn:
def _configure(self, bsz: int, q_len: int, causal: bool, regime: int):
import triton
from .triton_paged import (
+ ATTN16,
_paged_attn_decode_split_kernel,
_paged_attn_decode_combine_kernel,
_paged_kv_update_kernel,
_normalize_window,
)
+ # The 1.6 kernels for a quantized cache, a sliding window (the DFlash2 drafter: trace0, 300 vs 17 us per call at
+ # 20K) or single-token decode (equal kernel time in attn1, and the 1.6 path carries the :16 hints: ab5 MoE -2.5 %
+ # at 2.5K context on the hint-less pre-1.6 kernels); with fp16 K/V, no window, at q_len 8 the pre-1.6 kernels are
+ # faster (attn1)
+ ATTN16 = ATTN16 and (self.quant or _normalize_window(self.window_size)[0] >= 0 or q_len == 1)
+ if os.environ.get("EXL3_ATTN16_DEBUG") == "1":
+ print(" -- attn16 BC configure", (bsz, q_len, self.num_q_heads, self.num_kv_heads, self.head_dim, self.window_size, self.quant), "new" if ATTN16 else "old", flush = True)
+ if ATTN16:
+ # Upstream exllamav3 1.6.0 (MIT) decode kernels: dense (query, head) rows, sliding-window split
+ # range, sub-tiled combine (triton_paged_cu.py). EXL3_ATTN16=0 keeps the kernels above
+ from .triton_paged_cu import (
+ _paged_attn_decode_split_kernel,
+ _paged_attn_decode_combine_kernel,
+ attn_decode_config,
+ combine_subtiles,
+ decode_row_layout,
+ )
dev = self.device
hd = self.head_dim
@@ -275,11 +293,15 @@ class BCAttn:
qh, kvh = self.num_q_heads, self.num_kv_heads
group_size = qh // kvh
- block_n = max(16, 8192 // hd_pad)
- block_m = triton.next_power_of_2(q_len)
- block_h = max(16 // block_m, 1)
- block_rows = block_m * block_h
- h_blocks = triton.cdiv(group_size, block_h)
+ if ATTN16:
+ block_rows, h_blocks = decode_row_layout(q_len, group_size, hd_pad)
+ block_n, split_warps, split_stages = attn_decode_config(dev, hd_pad, block_rows)
+ else:
+ block_n, split_warps, split_stages = max(16, 8192 // hd_pad), 4, 2
+ block_m = triton.next_power_of_2(q_len)
+ block_h = max(16 // block_m, 1)
+ block_rows = block_m * block_h
+ h_blocks = triton.cdiv(group_size, block_h)
programs = bsz * kvh * h_blocks
# The live split count and split length are runtime kernel arguments derived from the
@@ -289,39 +311,71 @@ class BCAttn:
window_left, window_right = _normalize_window(self.window_size)
cache_t = "*i32" if self.quant else "*fp16"
+ # 1.6 path: upstream's 16-byte divisibility hints (whole allocations: cache tensors, graph statics, partials, the
+ # generator's block table), which keep the AOT kernel's vectorized loads (trace0: 324 vs 257 us per call without)
+ a16 = ":16" if ATTN16 else ""
sig = {
- "q": "*fp16", "k_cache": cache_t, "v_cache": cache_t,
- "block_table": "*i32", "cache_seqlens": "*i32", "out": "*fp16",
- "partial_o": "*fp32", "partial_ml": "*fp32",
- "k_scales": "*fp16", "v_scales": "*fp16", "h32": "*fp16",
+ "q": "*fp16" + a16, "k_cache": cache_t + a16, "v_cache": cache_t + a16,
+ "block_table": "*i32" + a16, "cache_seqlens": "*i32", "out": "*fp16" + a16,
+ "partial_o": "*fp32" + a16, "partial_ml": "*fp32" + a16,
+ "k_scales": "*fp16" + a16, "v_scales": "*fp16" + a16, "h32": "*fp16" + a16,
"split_len": "i32", "num_pages_per_seq": "i32", "num_splits": "i32",
"sinks": "*fp32",
} | {n: "constexpr" for n in (
"QCK", "QCV", "q_len", "kv_append_len", "n_q_heads", "n_kv_heads",
"page_size", "head_dim", "HD_PAD", "scale", "CAUSAL", "WINDOW_LEFT", "WINDOW_RIGHT",
- "SOFTCAP", "FINAL", "HAS_SINKS", "BLOCK_M", "BLOCK_H", "BLOCK_ROWS", "BLOCK_N")}
+ "SOFTCAP", "FINAL", "HAS_SINKS") + (() if ATTN16 else ("BLOCK_M", "BLOCK_H")) + ("BLOCK_ROWS", "BLOCK_N")}
consts = dict(
QCK = self.k_bits, QCV = self.v_bits,
q_len = q_len, kv_append_len = q_len, n_q_heads = qh, n_kv_heads = kvh,
page_size = PAGE_SIZE, head_dim = hd, HD_PAD = hd_pad, scale = float(self.sm_scale),
CAUSAL = bool(causal), WINDOW_LEFT = window_left, WINDOW_RIGHT = window_right,
SOFTCAP = float(self.softcap or 0.0), FINAL = False, HAS_SINKS = False,
- BLOCK_M = block_m, BLOCK_H = block_h, BLOCK_ROWS = block_rows, BLOCK_N = block_n,
+ BLOCK_ROWS = block_rows, BLOCK_N = block_n,
)
- k_split = _compile_kernel(dev, _paged_attn_decode_split_kernel, sig, consts, 4, 2)
+ if not ATTN16:
+ consts |= dict(BLOCK_M = block_m, BLOCK_H = block_h)
+ qcfg = None
+ if ATTN16 and self.quant and self.k_bits > 0 and self.v_bits > 0:
+ from . import qdec_cuda
+ qcfg = None if not qdec_cuda.GRAPH_ENABLED else qdec_cuda.make_cfg(q_len, qh, kvh, hd, self.k_bits, self.v_bits, PAGE_SIZE, causal, self.sm_scale,
+ block_rows, window_left, window_right, self.softcap or 0.0, q_len)
+ if qcfg is not None and h_blocks != 1 and not qcfg.get("rows_kernel"):
+ qcfg = None
+ if qcfg is not None and qcfg.get("rows_kernel"):
+ block_rows, h_blocks = qcfg["block_rows"], 1 # one program per kv head holds all its rows (cu/qdec_rows.cu)
+ programs = bsz * kvh
+ if qcfg is not None:
+ # CUDA tensor-core split kernel (cu/qdec.cu): same argument list as the Triton one; 16-token slabs, one
+ # CTA per SM-share instead of two
+ key = ("qdec", dev.index, tuple(sorted(qcfg.items())))
+ k_split = _kernel_cache.get(key)
+ if k_split is None:
+ k_split = _kernel_cache[key] = ext.TritonKernel(
+ qdec_cuda.cubin_for(qcfg), "qdec_split_rows" if qcfg.get("rows_kernel") else "qdec_split", qcfg["nw"], qdec_cuda.geometry(qcfg)["shared"])
+ block_n = 16
+ splits_cap = max(1, min(qdec_cuda.split_cap(qcfg, dev, programs), 128))
+ else:
+ k_split = _compile_kernel(dev, _paged_attn_decode_split_kernel, sig, consts, split_warps, split_stages)
sig_c = {
- "partial_o": "*fp32", "partial_ml": "*fp32", "out": "*fp16", "h32": "*fp16",
+ "partial_o": "*fp32" + a16, "partial_ml": "*fp32" + a16, "out": "*fp16" + a16, "h32": "*fp16" + a16,
"num_splits": "i32", "sinks": "*fp32",
} | {n: "constexpr" for n in (
- "QCV", "HAS_SINKS", "q_len", "n_q_heads", "n_kv_heads", "head_dim", "HD_PAD",
- "BLOCK_M", "BLOCK_H", "BLOCK_ROWS")}
+ "QCV", "HAS_SINKS", "q_len", "n_q_heads", "n_kv_heads", "head_dim", "HD_PAD")
+ + (("V_DIM", "BLOCK_ROWS", "ROWS_SUB", "D_SUB") if ATTN16 else ("BLOCK_M", "BLOCK_H", "BLOCK_ROWS"))}
consts_c = dict(
QCV = self.v_bits, HAS_SINKS = self.sinks is not None, q_len = q_len,
n_q_heads = qh, n_kv_heads = kvh, head_dim = hd, HD_PAD = hd_pad,
- BLOCK_M = block_m, BLOCK_H = block_h, BLOCK_ROWS = block_rows,
)
+ if ATTN16:
+ rows_sub, d_sub = combine_subtiles(block_rows, hd_pad)
+ consts_c |= dict(V_DIM = hd, BLOCK_ROWS = block_rows, ROWS_SUB = rows_sub, D_SUB = d_sub)
+ else:
+ consts_c |= dict(BLOCK_M = block_m, BLOCK_H = block_h, BLOCK_ROWS = block_rows)
k_combine = _compile_kernel(dev, _paged_attn_decode_combine_kernel, sig_c, consts_c, 4, 1)
+ if ATTN16:
+ k_combine.grid_y = (block_rows // rows_sub) * (hd_pad // d_sub)
k_update = None
if not self.quant:
@@ -379,7 +433,7 @@ class BCAttn:
q, kv, o, partial_o, partial_ml,
gate_a, gate_b,
k_split, k_combine, k_update,
- block_n, splits_cap,
+ block_n, splits_cap, programs,
xp, yp,
)
diff --git a/exllamav3/modules/attention_fn/cu/qdec.cu b/exllamav3/modules/attention_fn/cu/qdec.cu
new file mode 100644
index 0000000..b9475d5
--- /dev/null
+++ b/exllamav3/modules/attention_fn/cu/qdec.cu
@@ -0,0 +1,295 @@
+// Quantized-KV flash-decoding split kernel (sm_80+): tensor-core QK^T / PV straight from packed bit-plane words.
+// Same launch contract as triton_paged_cu._paged_attn_decode_split_kernel for QCK>0 and QCV>0 (partials feed the
+// existing combine kernel). Compile-time config through -D macros, see qdec_cuda.py.
+//
+// Per warp: slabs of 16 tokens. S^T (16 tokens x 8 rows) = Kdeq (A, from smem words, dequantized into the mma
+// fragment layout) x q^T (B). P^T is transposed in registers (movmatrix) into the B fragment of O^T = V^T x P^T,
+// whose A fragment is dequantized from V words the same way. Warps are independent (no block barriers in the loop);
+// data arrives through a per-warp cp.async ring of ST slabs.
+#define G (HD / 32)
+#define GROUP (NQH / NKV)
+#define ROWS (QLEN * GROUP)
+#define NT ((ROWS + 7) / 8)
+#define GPT (NKV * HD / 32)
+#define KCHW (G * KB)
+#define VCHW (G * VB)
+#define KSTRW (KCHW + ((KCHW % 8 == 4) ? 0 : 4))
+#define VSTRW (VCHW + ((VCHW % 8 == 4) ? 0 : 4))
+#define KDATA_B (16 * KSTRW * 4)
+#define VDATA_B (16 * VSTRW * 4)
+#define SC_B (((16 * G * 2) + 15) / 16 * 16)
+#define STAGE_B (KDATA_B + VDATA_B + 2 * SC_B)
+#define QSTR (HD + 8)
+#define NTHREADS (NW * 32)
+#define LOG2E 1.4426950408889634f
+#define NSL (HD / 16)
+
+// dynamic smem layout: [Qs fp16 NT*8 x QSTR][ring: NW x ST x STAGE_B] (epilogue reuses the ring for the cross-warp merge)
+
+__device__ __forceinline__ void cp_sc(void* dst, const void* src, bool pred)
+{
+ int sz = pred ? (G * 2) : 0;
+ if (G * 2 == 16) asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;" :: "r"(smem_u32(dst)), "l"(src), "r"(sz));
+ else asm volatile("cp.async.ca.shared.global [%0], [%1], 8, %2;" :: "r"(smem_u32(dst)), "l"(src), "r"(sz));
+}
+extern "C" __global__ void __launch_bounds__(NTHREADS)
+qdec_split(
+ const u16* __restrict__ q, const u32* __restrict__ k_cache, const u32* __restrict__ v_cache,
+ const int* __restrict__ block_table, const int* __restrict__ cache_seqlens, u16* out_unused,
+ float* __restrict__ partial_o, float* __restrict__ partial_ml,
+ const u16* __restrict__ k_scales, const u16* __restrict__ v_scales, const u16* __restrict__ h32,
+ int split_len, int num_pages_per_seq, int num_splits, const float* sinks_unused,
+ void* s0, void* s1)
+{
+ extern __shared__ __align__(16) unsigned char smem[];
+ u16* Qs = (u16*)smem;
+ unsigned char* ring = smem + ((NT * 8 * QSTR * 2 + 15) / 16) * 16;
+
+ const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
+ const int g = lane >> 2, t = lane & 3;
+ const int pid = blockIdx.x, split = blockIdx.y;
+ if (split >= num_splits) return;
+ const int batch = pid / NKV, kvh = pid % NKV;
+
+ const int total_k = cache_seqlens[batch] + QLEN; // kv_append_len == q_len (cache already holds the new tokens)
+ const int n_start = split * split_len;
+ const int n_end = min(n_start + split_len, total_k);
+
+ // ---- q rows -> rotated (h32) fp16 in smem
+ {
+ float* hs = (float*)(ring); // 32x32 fp32 scratch, ring is idle until the loop
+ for (int i = tid; i < 1024; i += NTHREADS) hs[i] = h2f(h32[i]);
+ __syncthreads();
+ for (int idx = tid; idx < NT * 8 * HD; idx += NTHREADS) {
+ int r = idx / HD, d = idx % HD, gi = d >> 5, c = d & 31;
+ float acc = 0.f;
+ if (r < ROWS) {
+ int row_q = r % QLEN, hl = r / QLEN;
+ const u16* qp = q + ((size_t)((batch * QLEN + row_q) * NQH + kvh * GROUP + hl)) * HD + gi * 32;
+ #pragma unroll
+ for (int k = 0; k < 32; k++) acc += h2f(qp[k]) * hs[k * 32 + c];
+ }
+ u32 hh = pack_h2(acc, 0.f) & 0xFFFFu;
+ Qs[r * QSTR + d] = (u16)hh;
+ }
+ __syncthreads();
+ }
+
+ float m[NT][2], l[NT][2], qabs[NT][2];
+ bool rvalid[NT][2];
+ #pragma unroll
+ for (int j = 0; j < NT; j++)
+ #pragma unroll
+ for (int e = 0; e < 2; e++) {
+ int r = 8 * j + 2 * t + e;
+ m[j][e] = -INFINITY; l[j][e] = 0.f;
+ rvalid[j][e] = r < ROWS;
+ qabs[j][e] = (float)(total_k - QLEN + (r % QLEN));
+ }
+ float O[NSL][NT][4];
+ #pragma unroll
+ for (int i = 0; i < NSL; i++)
+ #pragma unroll
+ for (int j = 0; j < NT; j++) { O[i][j][0] = O[i][j][1] = O[i][j][2] = O[i][j][3] = 0.f; }
+
+ unsigned char* wring = ring + (size_t)warp * ST * STAGE_B;
+ const int nslabs = (n_end > n_start) ? (n_end - n_start + 15) / 16 : 0;
+ const int my_n = (nslabs > warp) ? (nslabs - warp + NW - 1) / NW : 0;
+
+ auto fill = [&](int it) {
+ unsigned char* st = wring + (it % ST) * STAGE_B;
+ u32* ksm = (u32*)st; u32* vsm = (u32*)(st + KDATA_B);
+ u16* ksc = (u16*)(st + KDATA_B + VDATA_B); u16* vsc = (u16*)(st + KDATA_B + VDATA_B + SC_B);
+ if (it < my_n) {
+ int n0 = n_start + (warp + it * NW) * 16;
+ int page = n0 / PAGE;
+ long long phys = block_table[batch * num_pages_per_seq + page];
+ long long row0 = phys * PAGE + (n0 - page * PAGE);
+ #pragma unroll
+ for (int c = lane; c < 16 * (KCHW / 4); c += 32) {
+ int tk = c / (KCHW / 4), pt = c % (KCHW / 4);
+ cp16(ksm + tk * KSTRW + pt * 4, k_cache + (row0 + tk) * (GPT * KB) + kvh * KCHW + pt * 4, n0 + tk < n_end);
+ }
+ #pragma unroll
+ for (int c = lane; c < 16 * (VCHW / 4); c += 32) {
+ int tk = c / (VCHW / 4), pt = c % (VCHW / 4);
+ cp16(vsm + tk * VSTRW + pt * 4, v_cache + (row0 + tk) * (GPT * VB) + kvh * VCHW + pt * 4, n0 + tk < n_end);
+ }
+ if (lane < 16) cp_sc(ksc + lane * G, k_scales + (row0 + lane) * GPT + kvh * G, n0 + lane < n_end);
+ else cp_sc(vsc + (lane - 16) * G, v_scales + (row0 + lane - 16) * GPT + kvh * G, n0 + lane - 16 < n_end);
+ }
+ asm volatile("cp.async.commit_group;");
+ };
+
+ #pragma unroll
+ for (int s = 0; s < ST - 1; s++) fill(s);
+
+ const float sl = SCALE * LOG2E;
+ for (int it = 0; it < my_n; it++) {
+ __syncwarp();
+ fill(it + ST - 1);
+ asm volatile("cp.async.wait_group %0;" :: "n"(ST - 1));
+ __syncwarp();
+ unsigned char* st = wring + (it % ST) * STAGE_B;
+ const u32* ksm = (const u32*)st; const u32* vsm = (const u32*)(st + KDATA_B);
+ const u16* ksc = (const u16*)(st + KDATA_B + VDATA_B); const u16* vsc = (const u16*)(st + KDATA_B + VDATA_B + SC_B);
+ const int n0 = n_start + (warp + it * NW) * 16;
+
+ // ---- S^T = Kdeq x q^T
+ float S[NT][4];
+ #pragma unroll
+ for (int j = 0; j < NT; j++) { S[j][0] = S[j][1] = S[j][2] = S[j][3] = 0.f; }
+ const u32* kr0 = ksm + g * KSTRW;
+ const u32* kr1 = ksm + (g + 8) * KSTRW;
+ #pragma unroll
+ for (int gi = 0; gi < G; gi++) {
+ u32 sc0 = scale2<KB>(ksc[g * G + gi], ksc[g * G + gi]);
+ u32 sc1 = scale2<KB>(ksc[(g + 8) * G + gi], ksc[(g + 8) * G + gi]);
+ #pragma unroll
+ for (int h = 0; h < 2; h++) {
+ int p0 = 16 * h + 2 * t, p1 = p0 + 8, ks = gi * 2 + h;
+ u32 a0 = dequant2<KB>(raw_pair<KB>(kr0 + gi * KB, p0), sc0);
+ u32 a1 = dequant2<KB>(raw_pair<KB>(kr1 + gi * KB, p0), sc1);
+ u32 a2 = dequant2<KB>(raw_pair<KB>(kr0 + gi * KB, p1), sc0);
+ u32 a3 = dequant2<KB>(raw_pair<KB>(kr1 + gi * KB, p1), sc1);
+ #pragma unroll
+ for (int j = 0; j < NT; j++) {
+ const u16* qp = Qs + (8 * j + g) * QSTR + 16 * ks + 2 * t;
+ u32 b0 = *(const u32*)qp, b1 = *(const u32*)(qp + 8);
+ mma16816(S[j], a0, a1, a2, a3, b0, b1);
+ }
+ }
+ }
+
+ // ---- online softmax (log2 domain), rows 2t / 2t+1 of every n-tile
+ u32 plo[NT], phi[NT];
+ #pragma unroll
+ for (int j = 0; j < NT; j++) {
+ float s[4]; bool ok[4];
+ #pragma unroll
+ for (int e = 0; e < 4; e++) {
+ int tk = n0 + g + ((e >> 1) << 3);
+ int ri = e & 1;
+ ok[e] = rvalid[j][ri] && tk < n_end && (!CAUSAL || (float)tk <= qabs[j][ri]);
+ s[e] = ok[e] ? S[j][e] * sl : -INFINITY;
+ }
+ float alpha[2];
+ #pragma unroll
+ for (int ri = 0; ri < 2; ri++) {
+ float mx = fmaxf(s[ri], s[2 + ri]);
+ mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, 4));
+ mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, 8));
+ mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, 16));
+ float mn = fmaxf(m[j][ri], mx);
+ float me = (mn == -INFINITY) ? 0.f : mn;
+ alpha[ri] = (m[j][ri] == -INFINITY) ? 0.f : exp2f(m[j][ri] - me);
+ float p0 = ok[ri] ? exp2f(s[ri] - me) : 0.f;
+ float p1 = ok[2 + ri] ? exp2f(s[2 + ri] - me) : 0.f;
+ s[ri] = p0; s[2 + ri] = p1;
+ l[j][ri] = l[j][ri] * alpha[ri] + p0 + p1;
+ m[j][ri] = mn;
+ }
+ #pragma unroll
+ for (int i = 0; i < NSL; i++) {
+ O[i][j][0] *= alpha[0]; O[i][j][1] *= alpha[1]; O[i][j][2] *= alpha[0]; O[i][j][3] *= alpha[1];
+ }
+ plo[j] = movtrans(pack_h2(s[0], s[1]));
+ phi[j] = movtrans(pack_h2(s[2], s[3]));
+ }
+
+ // ---- O^T += Vdeq^T x P^T ; tokens 2t, 2t+1, 2t+8, 2t+9 of the slab
+ const u32* vA = vsm + (2 * t) * VSTRW;
+ const u32* vB = vsm + (2 * t + 1) * VSTRW;
+ const u32* vC = vsm + (2 * t + 8) * VSTRW;
+ const u32* vD = vsm + (2 * t + 9) * VSTRW;
+ #pragma unroll
+ for (int gi = 0; gi < G; gi++) {
+ u32 sAB = scale2<VB>(vsc[(2 * t) * G + gi], vsc[(2 * t + 1) * G + gi]);
+ u32 sCD = scale2<VB>(vsc[(2 * t + 8) * G + gi], vsc[(2 * t + 9) * G + gi]);
+ #pragma unroll
+ for (int h = 0; h < 2; h++) {
+ int p1 = 16 * h + g, p2 = p1 + 8, i = gi * 2 + h;
+ u32 a0 = dequant2<VB>(raw_one<VB>(vA + gi * VB, p1) | (raw_one<VB>(vB + gi * VB, p1) << 16), sAB);
+ u32 a1 = dequant2<VB>(raw_one<VB>(vA + gi * VB, p2) | (raw_one<VB>(vB + gi * VB, p2) << 16), sAB);
+ u32 a2 = dequant2<VB>(raw_one<VB>(vC + gi * VB, p1) | (raw_one<VB>(vD + gi * VB, p1) << 16), sCD);
+ u32 a3 = dequant2<VB>(raw_one<VB>(vC + gi * VB, p2) | (raw_one<VB>(vD + gi * VB, p2) << 16), sCD);
+ #pragma unroll
+ for (int j = 0; j < NT; j++) mma16816(O[i][j], a0, a1, a2, a3, plo[j], phi[j]);
+ }
+ }
+ }
+
+ // ---- row sums across the 8 token lanes
+ #pragma unroll
+ for (int j = 0; j < NT; j++)
+ #pragma unroll
+ for (int ri = 0; ri < 2; ri++) {
+ float v = l[j][ri];
+ v += __shfl_xor_sync(0xffffffffu, v, 4);
+ v += __shfl_xor_sync(0xffffffffu, v, 8);
+ v += __shfl_xor_sync(0xffffffffu, v, 16);
+ l[j][ri] = v;
+ }
+
+ // ---- merge warps through smem (ring is free: drain async copies first)
+ asm volatile("cp.async.wait_all;");
+ __syncthreads();
+ float* Osm = (float*)ring; // [NW][NT*8][HD]
+ float* Msm = Osm + NW * NT * 8 * HD; // [NW][NT*8]
+ float* Lsm = Msm + NW * NT * 8;
+ #pragma unroll
+ for (int j = 0; j < NT; j++) {
+ #pragma unroll
+ for (int i = 0; i < NSL; i++) {
+ float* ob = Osm + ((size_t)warp * NT * 8 + 8 * j) * HD;
+ ob[(2 * t) * HD + 16 * i + g] = O[i][j][0];
+ ob[(2 * t + 1) * HD + 16 * i + g] = O[i][j][1];
+ ob[(2 * t) * HD + 16 * i + g + 8] = O[i][j][2];
+ ob[(2 * t + 1) * HD + 16 * i + g + 8] = O[i][j][3];
+ }
+ if (g == 0) {
+ #pragma unroll
+ for (int ri = 0; ri < 2; ri++) {
+ Msm[warp * NT * 8 + 8 * j + 2 * t + ri] = m[j][ri];
+ Lsm[warp * NT * 8 + 8 * j + 2 * t + ri] = l[j][ri];
+ }
+ }
+ }
+ __syncthreads();
+
+ const size_t pbase = (size_t)(pid * num_splits + split);
+ float* po = partial_o + pbase * BLOCK_ROWS * HD_PAD;
+ float* pml = partial_ml + pbase * BLOCK_ROWS * 2;
+ for (int idx = tid; idx < BLOCK_ROWS * HD_PAD; idx += NTHREADS) {
+ int r = idx / HD_PAD, d = idx % HD_PAD;
+ float v = 0.f;
+ if (r < NT * 8 && d < HD) {
+ float M = -INFINITY;
+ #pragma unroll
+ for (int w = 0; w < NW; w++) M = fmaxf(M, Msm[w * NT * 8 + r]);
+ float Ms = (M == -INFINITY) ? 0.f : M;
+ #pragma unroll
+ for (int w = 0; w < NW; w++) {
+ float mw = Msm[w * NT * 8 + r];
+ float f = (mw == -INFINITY) ? 0.f : exp2f(mw - Ms);
+ v += Osm[((size_t)w * NT * 8 + r) * HD + d] * f;
+ }
+ }
+ po[idx] = v;
+ }
+ for (int r = tid; r < BLOCK_ROWS; r += NTHREADS) {
+ float M = -INFINITY, L = 0.f;
+ if (r < NT * 8) {
+ #pragma unroll
+ for (int w = 0; w < NW; w++) M = fmaxf(M, Msm[w * NT * 8 + r]);
+ float Ms = (M == -INFINITY) ? 0.f : M;
+ #pragma unroll
+ for (int w = 0; w < NW; w++) {
+ float mw = Msm[w * NT * 8 + r];
+ L += (mw == -INFINITY) ? 0.f : Lsm[w * NT * 8 + r] * exp2f(mw - Ms);
+ }
+ }
+ pml[r * 2] = (M == -INFINITY) ? M : M * 0.6931471805599453f; // back to natural-log units for the combine kernel
+ pml[r * 2 + 1] = L;
+ }
+}
diff --git a/exllamav3/modules/attention_fn/cu/qdec_common.cuh b/exllamav3/modules/attention_fn/cu/qdec_common.cuh
new file mode 100644
index 0000000..253aae0
--- /dev/null
+++ b/exllamav3/modules/attention_fn/cu/qdec_common.cuh
@@ -0,0 +1,66 @@
+// shared helpers of the qdec kernels (typedefs, cp.async, fp16x2 math, mma, bit-plane dequant); prepended by qdec_cuda.py
+typedef unsigned int u32;
+typedef unsigned short u16;
+
+__device__ __forceinline__ u32 smem_u32(const void* p) { return (u32)__cvta_generic_to_shared(p); }
+__device__ __forceinline__ void cp16(void* dst, const void* src, bool pred)
+{
+ int sz = pred ? 16 : 0;
+ asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;" :: "r"(smem_u32(dst)), "l"(src), "r"(sz));
+}
+__device__ __forceinline__ u32 hsub2(u32 a, u32 b) { u32 d; asm("sub.rn.f16x2 %0, %1, %2;" : "=r"(d) : "r"(a), "r"(b)); return d; }
+__device__ __forceinline__ u32 hmul2(u32 a, u32 b) { u32 d; asm("mul.rn.f16x2 %0, %1, %2;" : "=r"(d) : "r"(a), "r"(b)); return d; }
+__device__ __forceinline__ u32 hfma2(u32 a, u32 b, u32 c) { u32 d; asm("fma.rn.f16x2 %0, %1, %2, %3;" : "=r"(d) : "r"(a), "r"(b), "r"(c)); return d; }
+
+__device__ __forceinline__ void mma16816(float* c, u32 a0, u32 a1, u32 a2, u32 a3, u32 b0, u32 b1)
+{
+ asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};"
+ : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) : "r"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(b0), "r"(b1));
+}
+__device__ __forceinline__ u32 movtrans(u32 a) { u32 d; asm volatile("movmatrix.sync.aligned.m8n8.trans.b16 %0, %1;" : "=r"(d) : "r"(a)); return d; }
+
+__device__ __forceinline__ u32 pack_h2(float lo, float hi)
+{
+ u32 d; asm("cvt.rn.f16x2.f32 %0, %1, %2;" : "=r"(d) : "f"(hi), "f"(lo)); return d;
+}
+__device__ __forceinline__ float h2f(u16 h) { float f; asm("cvt.f32.f16 %0, %1;" : "=f"(f) : "h"(h)); return f; }
+
+// inverse of the grid step as fp16 bits (2^-(B-1)), duplicated in both halves
+template<int B> __device__ __forceinline__ u32 inv2() { return (u32)((15 - (B - 1)) << 10) * 0x10001u; }
+template<int B> __device__ __forceinline__ u32 c2() { return (u32)(0x6400 | (1 << (B - 1))) * 0x10001u; }
+
+// half2(scale_a, scale_b) -> half2 of grid-step scales
+template<int B> __device__ __forceinline__ u32 scale2(u16 a, u16 b) { return hmul2((u32)a | ((u32)b << 16), inv2<B>()); }
+
+// two adjacent raw values (positions p, p+1, p even) of a token's group -> packed in the two 16-bit halves
+template<int B> __device__ __forceinline__ u32 raw_pair(const u32* base, int p)
+{
+ u32 raw = 0; int pb = 0; bool first = true;
+ if (B & 8) { u32 v = (base[pb + (p >> 2)] >> ((p & 3) << 3)) & 0xFFFFu; raw = (v & 0xFFu) | ((v & 0xFF00u) << 8); pb += 8; first = false; }
+ if (B & 4) { u32 v = (base[pb + (p >> 3)] >> ((p & 7) << 2)) & 0xFFu; u32 x = (v & 0xFu) | ((v & 0xF0u) << 12); raw = first ? x : ((raw << 4) | x); pb += 4; first = false; }
+ if (B & 2) { u32 v = (base[pb + (p >> 4)] >> ((p & 15) << 1)) & 0xFu; u32 x = (v & 3u) | ((v & 12u) << 14); raw = first ? x : ((raw << 2) | x); pb += 2; first = false; }
+ if (B & 1) { u32 v = (base[pb + (p >> 5)] >> (p & 31)) & 3u; u32 x = (v & 1u) | ((v & 2u) << 15); raw = first ? x : ((raw << 1) | x); }
+ return raw;
+}
+// one raw value at position p
+template<int B> __device__ __forceinline__ u32 raw_one(const u32* base, int p)
+{
+ u32 raw = 0; int pb = 0; bool first = true;
+ if (B & 8) { raw = (base[pb + (p >> 2)] >> ((p & 3) << 3)) & 0xFFu; pb += 8; first = false; }
+ if (B & 4) { u32 x = (base[pb + (p >> 3)] >> ((p & 7) << 2)) & 0xFu; raw = first ? x : ((raw << 4) | x); pb += 4; first = false; }
+ if (B & 2) { u32 x = (base[pb + (p >> 4)] >> ((p & 15) << 1)) & 3u; raw = first ? x : ((raw << 2) | x); pb += 2; first = false; }
+ if (B & 1) { u32 x = (base[pb + (p >> 5)] >> (p & 31)) & 1u; raw = first ? x : ((raw << 1) | x); }
+ return raw;
+}
+// packed raw halves + half2 grid-step scale -> half2 values (raw - (2^(B-1) - 0.5)) * scale, one rounding
+template<int B> __device__ __forceinline__ u32 dequant2(u32 raw2, u32 s2)
+{
+ u32 x = hsub2(raw2 | 0x64006400u, c2<B>());
+ return hfma2(x, s2, hmul2(s2, 0x38003800u)); // 0x3800 = 0.5
+}
+
+__device__ __forceinline__ void cp4(void* dst, const void* src, bool pred)
+{
+ int sz = pred ? 4 : 0;
+ asm volatile("cp.async.ca.shared.global [%0], [%1], 4, %2;" :: "r"(smem_u32(dst)), "l"(src), "r"(sz));
+}
diff --git a/exllamav3/modules/attention_fn/cu/qdec_rows.cu b/exllamav3/modules/attention_fn/cu/qdec_rows.cu
new file mode 100644
index 0000000..e2026db
--- /dev/null
+++ b/exllamav3/modules/attention_fn/cu/qdec_rows.cu
@@ -0,0 +1,322 @@
+// Quantized-KV flash-decoding split kernel for MANY query rows (verify steps: q_len x GQA group up to ~56 rows per kv head).
+// Same launch contract / partial layout as qdec.cu (the Triton combine kernel reduces the partials), but the CTA's NW warps
+// cooperate on ONE 16-token slab instead of streaming independent slabs, splitting the head dimension between them
+// (NW = hd/32: one 32-dim quantization group per warp), so the O accumulators (hd x rows fp32) fit the registers however
+// many rows there are and no K/V dequantization is repeated:
+// * S^T = Kdeq x q^T : each warp dequantizes only ITS group of K and MMAs a partial S over it; the NW partial S tiles
+// (16 tokens x 8 rows per row tile, fp32) go through smem (barrier A);
+// * softmax: row tile j is owned by warp j % NW, which sums the partials of its tile, runs the online softmax for it and
+// publishes P (as the MMA B fragment) and the O rescale factor in smem (barrier B);
+// * O^T = Vdeq^T x P^T : each warp dequantizes only ITS slice of V and owns that slice of the accumulators of all rows,
+// so there is no cross-warp merge at the end.
+// Per-warp cp.async ring of ST slabs of the warp's own slice of the packed K/V words.
+#define G (HD / 32)
+#define GW (G / NW) // 32-dim quantization groups per warp
+#define GROUP (NQH / NKV)
+#define ROWS (QLEN * GROUP)
+#define NT ((ROWS + 7) / 8)
+#define GPT (NKV * HD / 32)
+#define KCHW (G * KB)
+#define VCHW (G * VB)
+#define KWW (GW * KB) // words per token of one warp's K slice
+#define VWW (GW * VB)
+#define KSW (KWW + ((KWW % 8 == 4) ? 0 : 4))
+#define VSW (VWW + ((VWW % 8 == 4) ? 0 : 4))
+#define KCP ((KWW % 4 == 0) ? 4 : 1) // words per cp.async
+#define VCP ((VWW % 4 == 0) ? 4 : 1)
+#define KDATA_B (16 * KSW * 4)
+#define VDATA_B (16 * VSW * 4)
+#define SC_B (((16 * G * 2) + 15) / 16 * 16)
+#define STAGE_B (KDATA_B + VDATA_B + 2 * SC_B)
+#define NTHREADS (NW * 32)
+#define LOG2E 1.4426950408889634f
+#define NSLW (2 * GW) // 16-dim output slabs per warp
+#define OWN ((NT + NW - 1) / NW) // row tiles owned per warp
+#define SX_B (NW * NT * 32 * 16) // partial S exchange
+#define PX_B (NT * 32 * 16) // P fragments (2 words) + rescale factors (2 floats) per row tile and lane
+
+// dynamic smem layout: [Sx][Px][ring: NW x ST x STAGE_B] (q lives in registers as this warp's MMA B fragments)
+
+__device__ __forceinline__ void cp_sc(void* dst, const void* src, bool pred)
+{
+ int sz = pred ? (G * 2) : 0;
+ if (G * 2 == 16) asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;" :: "r"(smem_u32(dst)), "l"(src), "r"(sz));
+ else asm volatile("cp.async.ca.shared.global [%0], [%1], 8, %2;" :: "r"(smem_u32(dst)), "l"(src), "r"(sz));
+}
+template<int CP> __device__ __forceinline__ void cpw(void* dst, const void* src, bool pred)
+{
+ if (CP == 4) cp16(dst, src, pred); else cp4(dst, src, pred);
+}
+
+#ifndef ABL
+#define ABL 0
+#endif
+extern "C" __global__ void __launch_bounds__(NTHREADS)
+qdec_split_rows(
+ const u16* __restrict__ q, const u32* __restrict__ k_cache, const u32* __restrict__ v_cache,
+ const int* __restrict__ block_table, const int* __restrict__ cache_seqlens, u16* out_unused,
+ float* __restrict__ partial_o, float* __restrict__ partial_ml,
+ const u16* __restrict__ k_scales, const u16* __restrict__ v_scales, const u16* __restrict__ h32,
+ int split_len, int num_pages_per_seq, int num_splits, const float* sinks_unused,
+ void* s0, void* s1)
+{
+ extern __shared__ __align__(16) unsigned char smem[];
+ float4* Sx = (float4*)smem;
+ uint2* Pp = (uint2*)(smem + SX_B);
+ float2* Pa = (float2*)(smem + SX_B + NT * 32 * 8);
+ unsigned char* ring = smem + SX_B + PX_B;
+
+ const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
+ const int g = lane >> 2, t = lane & 3;
+ const int pid = blockIdx.x, split = blockIdx.y;
+ if (split >= num_splits) return; // uniform across the CTA
+ const int batch = pid / NKV, kvh = pid % NKV;
+
+ const int total_k = cache_seqlens[batch] + QLEN;
+ const int n_start = split * split_len;
+ const int n_end = min(n_start + split_len, total_k);
+
+ // ---- q rows -> rotated (h32) fp16, kept as this warp's B fragments (head-dim groups warp*GW ..)
+ u32 qb[2 * GW][NT][2];
+ {
+ float* hs = (float*)(ring); // 32x32 fp32 scratch, ring is idle until the loop
+ for (int i = tid; i < 1024; i += NTHREADS) hs[i] = h2f(h32[i]);
+ __syncthreads();
+ #pragma unroll
+ for (int kk = 0; kk < 2 * GW; kk++) {
+ const int ks = warp * 2 * GW + kk, gi = ks >> 1, cb = 16 * (ks & 1) + 2 * t;
+ #pragma unroll
+ for (int j = 0; j < NT; j++) {
+ const int r = 8 * j + g;
+ float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f;
+ if (r < ROWS) {
+ const uint4* qv = (const uint4*)(q + ((size_t)((batch * QLEN + r % QLEN) * NQH + kvh * GROUP + r / QLEN)) * HD + gi * 32);
+ #pragma unroll 1
+ for (int v = 0; v < 4; v++) {
+ uint4 w4 = qv[v];
+ u32 w[4] = {w4.x, w4.y, w4.z, w4.w};
+ #pragma unroll
+ for (int k = 0; k < 8; k++) {
+ float x = h2f((u16)((w[k >> 1] >> ((k & 1) * 16)) & 0xFFFFu));
+ const float* hr = hs + (v * 8 + k) * 32 + cb;
+ a0 += x * hr[0]; a1 += x * hr[1]; a2 += x * hr[8]; a3 += x * hr[9];
+ }
+ }
+ }
+ qb[kk][j][0] = (pack_h2(a0, 0.f) & 0xFFFFu) | (pack_h2(a1, 0.f) << 16);
+ qb[kk][j][1] = (pack_h2(a2, 0.f) & 0xFFFFu) | (pack_h2(a3, 0.f) << 16);
+ }
+ }
+ __syncthreads();
+ }
+
+ float m[OWN][2], l[OWN][2], qabs[OWN][2];
+ bool rvalid[OWN][2];
+ #pragma unroll
+ for (int o = 0; o < OWN; o++)
+ #pragma unroll
+ for (int e = 0; e < 2; e++) {
+ int r = 8 * (warp + o * NW) + 2 * t + e;
+ m[o][e] = -INFINITY; l[o][e] = 0.f;
+ rvalid[o][e] = r < ROWS;
+ qabs[o][e] = (float)(total_k - QLEN + (r % QLEN));
+ }
+ float O[NSLW][NT][4];
+ #pragma unroll
+ for (int i = 0; i < NSLW; i++)
+ #pragma unroll
+ for (int j = 0; j < NT; j++) { O[i][j][0] = O[i][j][1] = O[i][j][2] = O[i][j][3] = 0.f; }
+
+ unsigned char* wring = ring + (size_t)warp * ST * STAGE_B;
+ const int nslabs = (n_end > n_start) ? (n_end - n_start + 15) / 16 : 0;
+
+ auto fill = [&](int it) {
+ unsigned char* st = wring + (it % ST) * STAGE_B;
+ u32* ksm = (u32*)st; u32* vsm = (u32*)(st + KDATA_B);
+ u16* ksc = (u16*)(st + KDATA_B + VDATA_B); u16* vsc = (u16*)(st + KDATA_B + VDATA_B + SC_B);
+ if (it < nslabs) {
+ int n0 = n_start + it * 16;
+ int page = n0 / PAGE;
+ long long phys = block_table[batch * num_pages_per_seq + page];
+ long long row0 = phys * PAGE + (n0 - page * PAGE);
+ #pragma unroll
+ for (int c = lane; c < 16 * (KWW / KCP); c += 32) {
+ int tk = c / (KWW / KCP), pt = c % (KWW / KCP);
+ cpw<KCP>(ksm + tk * KSW + pt * KCP, k_cache + (row0 + tk) * (GPT * KB) + kvh * KCHW + warp * KWW + pt * KCP, n0 + tk < n_end);
+ }
+ #pragma unroll
+ for (int c = lane; c < 16 * (VWW / VCP); c += 32) {
+ int tk = c / (VWW / VCP), pt = c % (VWW / VCP);
+ cpw<VCP>(vsm + tk * VSW + pt * VCP, v_cache + (row0 + tk) * (GPT * VB) + kvh * VCHW + warp * VWW + pt * VCP, n0 + tk < n_end);
+ }
+ if (lane < 16) cp_sc(ksc + lane * G, k_scales + (row0 + lane) * GPT + kvh * G, n0 + lane < n_end);
+ else cp_sc(vsc + (lane - 16) * G, v_scales + (row0 + lane - 16) * GPT + kvh * G, n0 + lane - 16 < n_end);
+ }
+ asm volatile("cp.async.commit_group;");
+ };
+
+ #pragma unroll
+ for (int s = 0; s < ST - 1; s++) fill(s);
+
+ const float sl = SCALE * LOG2E;
+ for (int it = 0; it < nslabs; it++) {
+ __syncwarp();
+ fill(it + ST - 1);
+ asm volatile("cp.async.wait_group %0;" :: "n"(ST - 1));
+ __syncwarp();
+ unsigned char* st = wring + (it % ST) * STAGE_B;
+ const u32* ksm = (const u32*)st; const u32* vsm = (const u32*)(st + KDATA_B);
+ const u16* ksc = (const u16*)(st + KDATA_B + VDATA_B); const u16* vsc = (const u16*)(st + KDATA_B + VDATA_B + SC_B);
+ const int n0 = n_start + it * 16;
+
+ // ---- partial S^T over this warp's head-dim groups
+ float S[NT][4];
+ #pragma unroll
+ for (int j = 0; j < NT; j++) { S[j][0] = S[j][1] = S[j][2] = S[j][3] = 0.f; }
+ const u32* kr0 = ksm + g * KSW;
+ const u32* kr1 = ksm + (g + 8) * KSW;
+ #pragma unroll
+ for (int gi = 0; gi < GW; gi++) {
+ const int gg = warp * GW + gi;
+ u32 sc0 = scale2<KB>(ksc[g * G + gg], ksc[g * G + gg]);
+ u32 sc1 = scale2<KB>(ksc[(g + 8) * G + gg], ksc[(g + 8) * G + gg]);
+ #pragma unroll
+ for (int h = 0; h < 2; h++) {
+ int p0 = 16 * h + 2 * t, p1 = p0 + 8;
+ u32 a0 = dequant2<KB>(raw_pair<KB>(kr0 + gi * KB, p0), sc0);
+ u32 a1 = dequant2<KB>(raw_pair<KB>(kr1 + gi * KB, p0), sc1);
+ u32 a2 = dequant2<KB>(raw_pair<KB>(kr0 + gi * KB, p1), sc0);
+ u32 a3 = dequant2<KB>(raw_pair<KB>(kr1 + gi * KB, p1), sc1);
+ #pragma unroll
+ for (int j = 0; j < NT; j++) {
+ mma16816(S[j], a0, a1, a2, a3, qb[gi * 2 + h][j][0], qb[gi * 2 + h][j][1]);
+ }
+ }
+ }
+
+ // ---- partial S tiles -> smem (barrier A) ; the owner of a row tile sums them and does its online softmax
+ float4* sxw = Sx;
+ #pragma unroll
+ for (int j = 0; j < NT; j++) sxw[(warp * NT + j) * 32 + lane] = make_float4(S[j][0], S[j][1], S[j][2], S[j][3]);
+ if (ABL != 1) __syncthreads();
+ #pragma unroll
+ for (int o = 0; o < OWN; o++) {
+ const int j = warp + o * NW;
+ if (j < NT && ABL != 1) {
+ float4 acc = make_float4(0.f, 0.f, 0.f, 0.f);
+ #pragma unroll
+ for (int w = 0; w < NW; w++) {
+ float4 v = sxw[(w * NT + j) * 32 + lane];
+ acc.x += v.x; acc.y += v.y; acc.z += v.z; acc.w += v.w;
+ }
+ float sv[4] = {acc.x, acc.y, acc.z, acc.w};
+ float s[4]; bool ok[4];
+ #pragma unroll
+ for (int e = 0; e < 4; e++) {
+ int tk = n0 + g + ((e >> 1) << 3);
+ int ri = e & 1;
+ ok[e] = rvalid[o][ri] && tk < n_end && (!CAUSAL || (float)tk <= qabs[o][ri]);
+ s[e] = ok[e] ? sv[e] * sl : -INFINITY;
+ }
+ float alpha[2];
+ #pragma unroll
+ for (int ri = 0; ri < 2; ri++) {
+ float mx = fmaxf(s[ri], s[2 + ri]);
+ mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, 4));
+ mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, 8));
+ mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, 16));
+ float mn = fmaxf(m[o][ri], mx);
+ float me = (mn == -INFINITY) ? 0.f : mn;
+ alpha[ri] = (m[o][ri] == -INFINITY) ? 0.f : exp2f(m[o][ri] - me);
+ float p0 = ok[ri] ? exp2f(s[ri] - me) : 0.f;
+ float p1 = ok[2 + ri] ? exp2f(s[2 + ri] - me) : 0.f;
+ s[ri] = p0; s[2 + ri] = p1;
+ l[o][ri] = l[o][ri] * alpha[ri] + p0 + p1;
+ m[o][ri] = mn;
+ }
+ Pp[j * 32 + lane] = make_uint2(movtrans(pack_h2(s[0], s[1])), movtrans(pack_h2(s[2], s[3])));
+ Pa[j * 32 + lane] = make_float2(alpha[0], alpha[1]);
+ }
+ }
+ if (ABL != 1) __syncthreads();
+ u32 plo[NT], phi[NT];
+ #pragma unroll
+ for (int j = 0; j < NT; j++) {
+ uint2 pp = Pp[j * 32 + lane]; float2 al = Pa[j * 32 + lane];
+ plo[j] = pp.x; phi[j] = pp.y;
+ #pragma unroll
+ for (int i = 0; i < NSLW; i++) {
+ O[i][j][0] *= al.x; O[i][j][1] *= al.y; O[i][j][2] *= al.x; O[i][j][3] *= al.y;
+ }
+ }
+
+ // ---- O^T slice += Vdeq^T x P^T ; tokens 2t, 2t+1, 2t+8, 2t+9 of the slab
+ const u32* vA = vsm + (2 * t) * VSW;
+ const u32* vB = vsm + (2 * t + 1) * VSW;
+ const u32* vC = vsm + (2 * t + 8) * VSW;
+ const u32* vD = vsm + (2 * t + 9) * VSW;
+ #pragma unroll
+ for (int gi = 0; gi < GW; gi++) {
+ const int gg = warp * GW + gi;
+ u32 sAB = scale2<VB>(vsc[(2 * t) * G + gg], vsc[(2 * t + 1) * G + gg]);
+ u32 sCD = scale2<VB>(vsc[(2 * t + 8) * G + gg], vsc[(2 * t + 9) * G + gg]);
+ #pragma unroll
+ for (int h = 0; h < 2; h++) {
+ int p1 = 16 * h + g, p2 = p1 + 8, i = gi * 2 + h;
+ u32 a0 = dequant2<VB>(raw_one<VB>(vA + gi * VB, p1) | (raw_one<VB>(vB + gi * VB, p1) << 16), sAB);
+ u32 a1 = dequant2<VB>(raw_one<VB>(vA + gi * VB, p2) | (raw_one<VB>(vB + gi * VB, p2) << 16), sAB);
+ u32 a2 = dequant2<VB>(raw_one<VB>(vC + gi * VB, p1) | (raw_one<VB>(vD + gi * VB, p1) << 16), sCD);
+ u32 a3 = dequant2<VB>(raw_one<VB>(vC + gi * VB, p2) | (raw_one<VB>(vD + gi * VB, p2) << 16), sCD);
+ #pragma unroll
+ for (int j = 0; j < NT; j++) mma16816(O[i][j], a0, a1, a2, a3, plo[j], phi[j]);
+ }
+ }
+ }
+
+ // ---- row sums across the 8 token lanes (owned tiles)
+ #pragma unroll
+ for (int o = 0; o < OWN; o++)
+ #pragma unroll
+ for (int ri = 0; ri < 2; ri++) {
+ float v = l[o][ri];
+ v += __shfl_xor_sync(0xffffffffu, v, 4);
+ v += __shfl_xor_sync(0xffffffffu, v, 8);
+ v += __shfl_xor_sync(0xffffffffu, v, 16);
+ l[o][ri] = v;
+ }
+ asm volatile("cp.async.wait_all;");
+
+ // ---- partials: every warp writes its own head-dim slice of all rows; m / l come from warp 0 (identical in all warps)
+ const size_t pbase = (size_t)(pid * num_splits + split);
+ float* po = partial_o + pbase * BLOCK_ROWS * HD_PAD;
+ float* pml = partial_ml + pbase * BLOCK_ROWS * 2;
+ #pragma unroll
+ for (int j = 0; j < NT; j++) {
+ #pragma unroll
+ for (int i = 0; i < NSLW; i++) {
+ const int d = 16 * (warp * NSLW + i) + g;
+ float* ob = po + (size_t)(8 * j + 2 * t) * HD_PAD + d;
+ ob[0] = O[i][j][0];
+ ob[HD_PAD] = O[i][j][1];
+ ob[8] = O[i][j][2];
+ ob[HD_PAD + 8] = O[i][j][3];
+ }
+ }
+ for (int idx = tid; idx < (BLOCK_ROWS - NT * 8) * HD_PAD; idx += NTHREADS) po[(size_t)NT * 8 * HD_PAD + idx] = 0.f;
+ if (g == 0) {
+ #pragma unroll
+ for (int o = 0; o < OWN; o++) {
+ const int j = warp + o * NW;
+ if (j < NT) {
+ #pragma unroll
+ for (int ri = 0; ri < 2; ri++) {
+ int r = 8 * j + 2 * t + ri;
+ pml[r * 2] = (m[o][ri] == -INFINITY) ? m[o][ri] : m[o][ri] * 0.6931471805599453f; // natural-log units for the combine kernel
+ pml[r * 2 + 1] = l[o][ri];
+ }
+ }
+ }
+ }
+ if (warp == 0)
+ for (int r = NT * 8 + lane; r < BLOCK_ROWS; r += 32) { pml[r * 2] = -INFINITY; pml[r * 2 + 1] = 0.f; }
+}
diff --git a/exllamav3/modules/attention_fn/qdec_cuda.py b/exllamav3/modules/attention_fn/qdec_cuda.py
new file mode 100644
index 0000000..a8fba7f
--- /dev/null
+++ b/exllamav3/modules/attention_fn/qdec_cuda.py
@@ -0,0 +1,227 @@
+"""
+CUDA split kernel for quantized-KV decode attention (cu/qdec.cu), compiled at first use with NVRTC to a cubin cached on
+disk, launched through the driver API. Replaces triton_paged_cu._paged_attn_decode_split_kernel when both K and V are
+packed (QCK > 0, QCV > 0) on sm_80+ with full (non-windowed) attention and no softcap; the Triton combine kernel
+reduces its partials, so the downstream contract is unchanged. Returns None / raises QdecUnsupported when a call
+shape is outside what the kernel covers, so callers fall back to the Triton kernels.
+"""
+import hashlib
+import math
+import os
+
+import torch
+import triton
+
+_SRC = os.path.join(os.path.dirname(__file__), "cu", "qdec.cu")
+_SRC_ROWS = os.path.join(os.path.dirname(__file__), "cu", "qdec_rows.cu") # many-row kernel (verify steps), see qdec_rows.cu
+_COMMON = os.path.join(os.path.dirname(__file__), "cu", "qdec_common.cuh")
+ROWS_MODE = os.environ.get("EXL3_QDEC_ROWS", "1") # 0: no many-row kernel, 1: only where qdec.cu cannot, 2: always
+_CACHE = os.path.expanduser(os.environ.get("EXL3_QDEC_CACHE", "~/.cache/exl3_qdec"))
+_kernels = {}
+
+
+class QdecUnsupported(RuntimeError):
+ pass
+
+
+def geometry(cfg):
+ """Shared-memory sizing, mirrors the macros of qdec.cu / qdec_rows.cu"""
+ hd, kb, vb = cfg["hd"], cfg["kb"], cfg["vb"]
+ if cfg.get("rows_kernel"):
+ g = hd // 32
+ nw = cfg["nw"]
+ gw = g // nw
+ rows = cfg["qlen"] * (cfg["nqh"] // cfg["nkv"])
+ nt = (rows + 7) // 8
+ kww, vww = gw * kb, gw * vb
+ ksw = kww + (0 if kww % 8 == 4 else 4)
+ vsw = vww + (0 if vww % 8 == 4 else 4)
+ sc_b = (16 * g * 2 + 15) // 16 * 16
+ stage_b = 16 * ksw * 4 + 16 * vsw * 4 + 2 * sc_b
+ sx = nw * nt * 32 * 16 + nt * 32 * 16
+ return dict(nt=nt, rows=rows, stage_b=stage_b, shared=sx + max(nw * cfg["st"] * stage_b, 4096))
+ g = hd // 32
+ group = cfg["nqh"] // cfg["nkv"]
+ rows = cfg["qlen"] * group
+ nt = (rows + 7) // 8
+ kchw, vchw = g * kb, g * vb
+ kstr = kchw + (0 if kchw % 8 == 4 else 4)
+ vstr = vchw + (0 if vchw % 8 == 4 else 4)
+ sc_b = (16 * g * 2 + 15) // 16 * 16
+ stage_b = 16 * kstr * 4 + 16 * vstr * 4 + 2 * sc_b
+ ring = cfg["nw"] * cfg["st"] * stage_b
+ qs = (nt * 8 * (hd + 8) * 2 + 15) // 16 * 16
+ merge = (cfg["nw"] * nt * 8 * hd + 2 * cfg["nw"] * nt * 8) * 4
+ return dict(nt=nt, rows=rows, stage_b=stage_b, shared=qs + max(ring, merge, 4096))
+
+
+def supported(cfg):
+ hd = cfg["hd"]
+ if hd % 64 != 0 or hd > 256 or not (2 <= cfg["kb"] <= 8) or not (2 <= cfg["vb"] <= 8):
+ return False
+ if cfg["nqh"] % cfg["nkv"] != 0 or cfg["page"] % 16 != 0:
+ return False
+ geo = geometry(cfg)
+ if cfg.get("rows_kernel"):
+ # one warp per 32-dim group; O accumulator regs per thread: 2 * nt * 4
+ return (hd // 32) % cfg["nw"] == 0 and geo["nt"] <= 8
+ if geo["rows"] > 32 or geo["nt"] * hd > 512: # O accumulator regs: hd/16 * nt * 4 per thread
+ return False
+ return True
+
+
+def _compile(cfg):
+ from cuda.bindings import nvrtc
+ defs = dict(HD=cfg["hd"], KB=cfg["kb"], VB=cfg["vb"], NKV=cfg["nkv"], NQH=cfg["nqh"], QLEN=cfg["qlen"],
+ PAGE=cfg["page"], NW=cfg["nw"], ST=cfg["st"], CAUSAL=int(cfg["causal"]), BLOCK_ROWS=cfg["block_rows"],
+ HD_PAD=triton.next_power_of_2(cfg["hd"]), SCALE=repr(float(cfg["scale"])) + "f")
+ if os.environ.get("EXL3_QDEC_ABL"):
+ defs["ABL"] = int(os.environ["EXL3_QDEC_ABL"])
+ src = "#define INFINITY __int_as_float(0x7f800000)\n" + open(_COMMON).read() + "\n" + \
+ open(_SRC_ROWS if cfg.get("rows_kernel") else _SRC).read()
+ major, minor = torch.cuda.get_device_capability()
+ opts = [f"--gpu-architecture=sm_{major}{minor}", "-std=c++17", "-default-device", "--fmad=true"]
+ opts += [f"-D{k}={v}" for k, v in defs.items()]
+ key = hashlib.sha1((src + " ".join(opts)).encode()).hexdigest()[:20]
+ path = os.path.join(_CACHE, key + ".cubin")
+ if os.path.exists(path):
+ return open(path, "rb").read()
+
+ def chk(r):
+ if r[0] != nvrtc.nvrtcResult.NVRTC_SUCCESS:
+ raise RuntimeError(f"nvrtc: {r[0]}")
+ return r[1:] if len(r) > 1 else None
+ prog, = chk(nvrtc.nvrtcCreateProgram(src.encode(), b"qdec.cu", 0, [], []))
+ rc = nvrtc.nvrtcCompileProgram(prog, len(opts), [o.encode() for o in opts])
+ if rc[0] != nvrtc.nvrtcResult.NVRTC_SUCCESS:
+ n, = chk(nvrtc.nvrtcGetProgramLogSize(prog))
+ buf = b" " * n
+ nvrtc.nvrtcGetProgramLog(prog, buf)
+ raise RuntimeError("qdec nvrtc compile failed:\n" + buf.decode(errors="replace"))
+ n, = chk(nvrtc.nvrtcGetCUBINSize(prog))
+ cubin = b" " * n
+ chk(nvrtc.nvrtcGetCUBIN(prog, cubin))
+ os.makedirs(_CACHE, exist_ok=True)
+ tmp = path + f".{os.getpid()}"
+ open(tmp, "wb").write(cubin)
+ os.replace(tmp, path)
+ return cubin
+
+
+class _Kernel:
+ def __init__(self, cfg):
+ from cuda.bindings import driver
+ self.cfg = cfg
+ self.cubin = _compile(cfg)
+ self.shared = geometry(cfg)["shared"]
+ torch.cuda.current_stream() # context
+ r, self.mod = driver.cuModuleLoadData(self.cubin)
+ assert r == driver.CUresult.CUDA_SUCCESS, r
+ r, self.fn = driver.cuModuleGetFunction(self.mod, b"qdec_split_rows" if cfg.get("rows_kernel") else b"qdec_split")
+ assert r == driver.CUresult.CUDA_SUCCESS, r
+ if self.shared > 48 * 1024:
+ r, = driver.cuFuncSetAttribute(self.fn, driver.CUfunction_attribute.CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, self.shared)
+ assert r == driver.CUresult.CUDA_SUCCESS, r
+
+ def blocks_per_sm(self):
+ """resident CTAs per SM for this kernel's block size / shared memory / registers"""
+ if not hasattr(self, "_bps"):
+ from cuda.bindings import driver
+ r, n = driver.cuOccupancyMaxActiveBlocksPerMultiprocessor(self.fn, 32 * self.cfg["nw"], self.shared)
+ assert r == driver.CUresult.CUDA_SUCCESS, r
+ self._bps = max(1, n)
+ return self._bps
+
+ def launch(self, grid, ptrs, ints):
+ """ptrs: 11 device pointer ints (q .. h32 incl. out), ints: split_len, num_pages_per_seq, num_splits"""
+ import ctypes
+ from cuda.bindings import driver
+ vals = list(ptrs) + list(ints) + [0, 0, 0] # + sinks, 2 scratch slots (unused)
+ types = [ctypes.c_void_p] * len(ptrs) + [ctypes.c_int] * len(ints) + [ctypes.c_void_p] * 3
+ stream = torch.cuda.current_stream().cuda_stream
+ r, = driver.cuLaunchKernel(self.fn, grid[0], grid[1], 1, 32 * self.cfg["nw"], 1, 1, self.shared, stream, (tuple(vals), tuple(types)), 0)
+ assert r == driver.CUresult.CUDA_SUCCESS, r
+
+
+def get_kernel(cfg):
+ key = tuple(sorted(cfg.items()))
+ k = _kernels.get(key)
+ if k is None:
+ k = _kernels[key] = _Kernel(cfg)
+ return k
+
+
+def rows_nw(hd):
+ """warps per CTA of the many-row kernel (each takes hd/32/nw 32-dim groups)"""
+ return int(os.environ.get("EXL3_QDEC_RNW", "0")) or (4 if (hd // 32) % 4 == 0 else 2)
+
+
+def pick_nw_st(cfg):
+ """(warps per CTA, ring depth), measured on a 3090 at 128K context (K/V bits 4/4, 6/6, 8/8): 8 x 2 for hd128 with
+ narrow codes, 4 x 2 otherwise; shrinks until the shared memory fits the opt-in limit"""
+ c = dict(cfg)
+ if cfg.get("rows_kernel"):
+ c.update(nw=rows_nw(cfg["hd"]))
+ for st in ((int(os.environ["EXL3_QDEC_RST"]),) if os.environ.get("EXL3_QDEC_RST") else (3, 2, 1)):
+ c.update(st=st)
+ if geometry(c)["shared"] <= 99 * 1024:
+ return c["nw"], st
+ raise QdecUnsupported("no ring configuration fits")
+ narrow = cfg["hd"] == 128 and cfg["kb"] + cfg["vb"] <= 8
+ for nw, st in (((8, 2), (4, 2), (4, 1), (2, 2), (2, 1)) if narrow else ((4, 2), (4, 1), (2, 2), (2, 1))):
+ c.update(nw=nw, st=st)
+ if geometry(c)["shared"] <= 99 * 1024:
+ return nw, st
+ raise QdecUnsupported("no ring configuration fits")
+
+
+ENABLED = os.environ.get("EXL3_QDEC", "1") != "0" and not torch.version.hip
+# graph (BC) path switch (EXL3_QDEC_GRAPH=0 keeps the Triton split kernel in captured graphs)
+GRAPH_ENABLED = os.environ.get("EXL3_QDEC_GRAPH", "1") != "0"
+_sm = {}
+
+
+def make_cfg(q_len, n_q_heads, n_kv_heads, head_dim, k_bits, v_bits, page_size, causal, sm_scale, block_rows,
+ window_left, window_right, softcap, kv_append_len):
+ """Kernel config for a call, or None when the Triton kernels must run it"""
+ if (not ENABLED or window_left >= 0 or window_right >= 0 or softcap or kv_append_len != q_len
+ or k_bits == 0 or v_bits == 0):
+ return None
+ cfg = dict(hd=head_dim, kb=k_bits, vb=v_bits, nkv=n_kv_heads, nqh=n_q_heads, qlen=q_len, page=page_size,
+ nw=4, st=2, causal=bool(causal), scale=float(sm_scale), block_rows=block_rows)
+ old_ok = supported(cfg) and geometry(cfg)["nt"] * 8 <= block_rows
+ # the many-row kernel also serves 2-row hd256 steps (qdec.cu needs 74 KB there: one CTA per SM)
+ if ROWS_MODE == "2" or (ROWS_MODE == "1" and (not old_ok or (cfg["hd"] >= 256 and cfg["qlen"] == 2))):
+ rc = dict(cfg, rows_kernel=True, nw=rows_nw(cfg["hd"]), block_rows=max(16, triton.next_power_of_2(geometry(cfg)["rows"])))
+ if supported(rc):
+ cfg = rc
+ old_ok = True
+ if not old_ok:
+ return None
+ try:
+ cfg["nw"], cfg["st"] = pick_nw_st(cfg)
+ except QdecUnsupported:
+ return None
+ return cfg
+
+
+def split_cap(cfg, device, programs):
+ """kv splits per program: one full wave of resident CTAs (the many-row kernel's CTAs are small and several fit an SM;
+ qdec.cu keeps one CTA's share per SM)"""
+ sm = sm_count(device)
+ if cfg.get("rows_kernel") and not os.environ.get("EXL3_QDEC_SPL"):
+ sm *= get_kernel(cfg).blocks_per_sm()
+ elif os.environ.get("EXL3_QDEC_SPL"):
+ return int(os.environ["EXL3_QDEC_SPL"])
+ return max(1, sm // programs)
+
+
+def sm_count(device):
+ idx = device.index if device.index is not None else torch.cuda.current_device()
+ if idx not in _sm:
+ _sm[idx] = torch.cuda.get_device_properties(idx).multi_processor_count
+ return _sm[idx]
+
+
+def cubin_for(cfg):
+ return _compile(cfg)
diff --git a/exllamav3/modules/attention_fn/triton_paged.py b/exllamav3/modules/attention_fn/triton_paged.py
index d556310..dbea7a4 100644
--- a/exllamav3/modules/attention_fn/triton_paged.py
+++ b/exllamav3/modules/attention_fn/triton_paged.py
@@ -702,6 +702,27 @@ _qc_staging = int(os.environ.get("EXL3_QC_STAGING", "1"))
# path reads less gmem (short trailing chunks over long contexts, low bitrates)
_qc_prefill_two_pass_min_q = int(os.environ.get("EXL3_QC_PF_TWO_PASS_MIN_Q", "256"))
+# CUDA, 128 < head_dim <= 256, one sequence: after the staging pass the window is contiguous fp16, so the chunk runs as one
+# FlashAttention-2 call (torch SDPA flash backend) over past + chunk keys with a bottom-right aligned causal mask. RTX 3090,
+# Qwen3.8 geometry (hd 256), whole 64K prompt in 2048-row chunks: x0.80 of the Triton kernel per layer, error vs an fp32
+# reference within x1.06 of the Triton kernel's; at hd 128 the Triton kernel is faster (x1.15-1.27), so it keeps those.
+# EXL3_PF_FA2=0 restores the Triton kernel
+_pf_fa2 = os.environ.get("EXL3_PF_FA2", "1") == "1" and torch.version.hip is None
+
+def _prefill_fa2_contig(q, kd, vd, past, n_kvh, head_dim, scale, out):
+ from torch.nn.attention import sdpa_kernel, SDPBackend
+ from torch.nn.attention.bias import causal_lower_right
+ q_len = q.shape[1]
+ k1 = kd.view(1, -1, n_kvh, head_dim)[:, :past + q_len]
+ v1 = vd.view(1, -1, n_kvh, head_dim)[:, :past + q_len]
+ with sdpa_kernel([SDPBackend.FLASH_ATTENTION]):
+ o = torch.nn.functional.scaled_dot_product_attention(
+ q.transpose(1, 2), k1.transpose(1, 2), v1.transpose(1, 2),
+ attn_mask = causal_lower_right(q_len, past + q_len), scale = scale, enable_gqa = True,
+ )
+ out.copy_(o.transpose(1, 2))
+ return out
+
def _get_h32(device):
if device not in _h32_cache:
h = torch.ones(1, 1, dtype = torch.float32)
@@ -1068,6 +1089,12 @@ def _paged_attn_decode_combine_kernel(
_decode_sm_count = {}
+# A/B switch, read once at import: CUDA decode runs the upstream exllamav3 1.6.0 (MIT) kernels in triton_paged_cu.py;
+# EXL3_ATTN16=0 keeps the kernels in this file. ROCm always keeps them
+ATTN16 = (not torch.version.hip) and os.environ.get("EXL3_ATTN16", "1") != "0"
+_ATTN16_DEBUG = os.environ.get("EXL3_ATTN16_DEBUG") == "1"; _ATTN16_SEEN = set() # one line per new call shape
+
+
def paged_attn_triton_decode(
q: torch.Tensor,
k: torch.Tensor | None,
@@ -1095,6 +1122,30 @@ def paged_attn_triton_decode(
"""Flash-decoding paged attention for short queries: the kv sequence is split across
programs (sized from the block table, so no host sync on cache_seqlens) and reduced in a
second pass. GQA sibling q heads share K/V tiles within a program."""
+ if qc is not None and not os.environ.get("FLINT_ATTN_KEEP"):
+ # quantized cache decode (3090, head_dim 128, k/v 4-8 bit): 64-key tiles, single stage = -15..-25 % kernel time
+ # vs the 16-bit-sized default (profile at 60K ctx: kv8 2.47 -> 1.90 ms, kv4 2.22 -> 1.69 ms, 49 layers)
+ if block_n is None: block_n = 64
+ if num_stages == 2: num_stages = 1
+ if os.environ.get("FLINT_ATTN_BN"): block_n = int(os.environ["FLINT_ATTN_BN"])
+ if os.environ.get("FLINT_ATTN_NW"): num_warps = int(os.environ["FLINT_ATTN_NW"])
+ if os.environ.get("FLINT_ATTN_NS"): num_stages = int(os.environ["FLINT_ATTN_NS"])
+ # attn1 (3090): the 1.6 kernels win with a sliding window (x3-10 at 20-64K) or a quantized cache (x1.25-1.31 at q_len 8,
+ # 20-64K) but lose with an fp16 cache at q_len 8 (x0.66-0.85): there the pre-1.6 kernels stay
+ if _ATTN16_DEBUG:
+ _k = (tuple(q.shape), tuple(k_cache.shape), str(window_size), qc is not None, split_batch)
+ if _k not in _ATTN16_SEEN:
+ _ATTN16_SEEN.add(_k); print(" -- attn16 eager decode", _k, "new" if ATTN16 and (qc is not None or _normalize_window(window_size)[0] >= 0) else "old", flush = True)
+ if ATTN16 and (qc is not None or _normalize_window(window_size)[0] >= 0):
+ from .triton_paged_cu import paged_attn_triton_decode_cu, NoFittingConfig
+ try:
+ return paged_attn_triton_decode_cu(
+ q, k, v, k_cache, v_cache, block_table, cache_seqlens, causal, softmax_scale, window_size,
+ softcap, sinks, out, block_n, num_splits, max_kv_len, qc, pre_appended_len,
+ n_kv_heads_override, num_warps, num_stages, split_batch)
+ except NoFittingConfig:
+ if _ATTN16_DEBUG: print(" -- attn16 NoFittingConfig -> pre-1.6 kernels", flush = True)
+ pass # nothing fits this device's shared memory: the pre-1.6 kernels below
_check_tensor("q", q)
_check_tensor("block_table", block_table, None)
_check_tensor("cache_seqlens", cache_seqlens, None)
@@ -1174,7 +1225,9 @@ def paged_attn_triton_decode(
_decode_sm_count[dev] = torch.cuda.get_device_properties(q.device).multi_processor_count
target = 2 * _decode_sm_count[dev]
programs_split = programs if split_batch is None else programs // bsz * split_batch
- num_splits = max(1, min(target // programs_split, triton.cdiv(max_k_len, 4 * block_n), 128))
+ # CUDA: >= 1 key block per split (upstream exllamav3 1.6.0, MIT; same rule as libtorch/attention.cpp split_config),
+ # so short contexts fill the SMs; ROCm keeps 4
+ num_splits = max(1, min(target // programs_split, triton.cdiv(max_k_len, (4 if torch.version.hip else 1) * block_n), 128))
split_len = triton.cdiv(triton.cdiv(max_k_len, num_splits), block_n) * block_n
if num_splits > 1:
@@ -1876,6 +1929,13 @@ def paged_attn_triton_prefill(
qc = None
k_scales, v_scales, qck, qcv = q, q, 0, 0
h32 = q
+ if (_pf_fa2 and bsz == 1 and max_kv_len is not None and kv_append_len == q_len
+ and 128 < head_dim <= 256 and head_dim % 8 == 0 and v_dim == head_dim
+ and window_left < 0 and window_right < 0 and not softcap and not has_sinks
+ and num_splits is None and block_m is None and q.is_contiguous()):
+ if out is None:
+ out = torch.empty_like(q)
+ return _prefill_fa2_contig(q, kd, vd, max_kv_len, n_kvh, head_dim, softmax_scale, out)
else:
k_scales, v_scales, qck, qcv = q, q, 0, 0
h32 = q
@@ -1884,14 +1944,18 @@ def paged_attn_triton_prefill(
# prefers narrower kv tiles (measured: 167 vs 153 TFLOPS on RTX 5090 at BN 32 vs 64)
blackwell = torch.cuda.get_device_capability(q.device)[0] >= 10
if hd_pad <= 128:
- cfg = (128, 32, 8, 2) if blackwell else (128, 64, 8, 2)
+ # CUDA: four warps over the tile like upstream exllamav3 1.6.0 (MIT; "eight warps split the rows below the 16-row MMA
+ # granularity and stall the dots", issue #384); ROCm keeps its eight
+ cfg = (128, 32, 8, 2) if blackwell else ((128, 64, 8, 2) if torch.version.hip else (128, 32, 4, 2))
elif hd_pad <= 256:
# gfx1151, MiMo geometry (qk 192 -> 256 tile, 16 q heads per kv head), 2048-row chunk:
# (128, 32, 8, 2) runs 3-4x faster than (64, 32, 8, 2) at every past length measured
# (tools/prefill/attn_bench.py: 62.7 vs 194 ms at 14k past with v_dim 128)
- cfg = (128, 32, 8, 2) if torch.version.hip else (64, 32, 8, 2)
+ cfg = (128, 32, 8, 2) if torch.version.hip else (64, 32, 4, 2)
else:
- cfg = (32, 16, 4, 2)
+ # CUDA, head_dim 512 (Gemma-4 global layers): 32-key tiles run x1.25-1.35 over 16 keys at 512-4096-row chunks on an
+ # RTX 3090 (fp16 staged window, 21.8K-token prompt); ROCm keeps its tile
+ cfg = (32, 16, 4, 2) if torch.version.hip else (32, 32, 4, 2)
_cfg_env = os.environ.get("EXL3_ATTN_PREFILL_CFG")
if _cfg_env:
cfg = tuple(int(x) for x in _cfg_env.split(","))
@@ -1956,6 +2020,13 @@ def paged_attn_triton_prefill(
num_warps=2, num_stages=3,
)
+ # 8-bit K+V, head_dim 128, 128-key tile: left alone, ptxas caps the kernel at 40 registers with ~3250 spill
+ # slots (255 regs / ~560 spills when uncapped; same math, only the register allocation differs). The driver
+ # then sizes local memory for every resident thread: +1.3 GiB of non-torch device memory the first time a short
+ # chunk (q_len < 256, the direct path) runs, which made Flint kv 8,8 OOM at 256K on a 24 GiB card.
+ # EXL3_QC_PF_MAXNREG overrides the cap (0 = compiler default)
+ _maxnreg = int(os.environ.get("EXL3_QC_PF_MAXNREG", "255" if qc is not None and qck + qcv >= 16 else "0"))
+ _launch_opts = {"maxnreg": _maxnreg} if _maxnreg else {}
grid = (q_blocks, bsz * n_q_heads, num_splits)
# int64 index math only when an element offset can actually cross 2^31 (q/out, or the
# fp32 partial buffer); common geometries keep pure int32 codegen
@@ -1974,7 +2045,7 @@ def paged_attn_triton_prefill(
bool(causal), int(window_left), int(window_right),
window_left >= 0, window_right >= 0, float(softcap or 0.0),
has_sinks, wide_index, block_m, block_n,
- num_warps=num_warps, num_stages=ns,
+ num_warps=num_warps, num_stages=ns, **_launch_opts,
)
if qc is not None and not num_stages_forced:
diff --git a/exllamav3/modules/attention_fn/triton_paged_cu.py b/exllamav3/modules/attention_fn/triton_paged_cu.py
new file mode 100644
index 0000000..755bca7
--- /dev/null
+++ b/exllamav3/modules/attention_fn/triton_paged_cu.py
@@ -0,0 +1,902 @@
+"""
+CUDA-only paged decode attention (flash-decoding split + combine kernels).
+
+Ported from upstream exllamav3 1.6.0 (MIT licence, Turboderp), modules/attention_fn/triton_paged.py
+(_paged_attn_decode_split_kernel, _paged_attn_decode_combine_kernel, decode_row_layout, combine_subtiles,
+paged_attn_triton_decode, _paged_kv_update_rows_kernel) and modules/attention_fn/smem.py (the shared-memory
+ladder, trimmed to what the decode launcher uses). Changes from 1.6.0:
+ - head_dim == v_head_dim (Kyojin has no asymmetric V head dim): the combine kernel's V_DIM is passed as head_dim
+ - split_batch (DFlash verify rows, triton_paged.paged_attn_triton_decode_rows) is kept
+ - ATTN_SPLIT_WARPS_STAGES / attn_decode_config (util/backend.py upstream) are inlined for CUDA: (4, 2)
+
+What the 1.6 kernels change against the Kyojin ones in triton_paged.py:
+ - sliding-window layers split only the keys >= (first query position - window) across programs
+ - a kv head's (query position, sibling q head) rows are packed densely (decode_row_layout)
+ - the combine kernel walks the splits S_BLK at a time and is sub-tiled over grid axis 1
+ - the eager KV append is row-tiled
+
+triton_paged.py dispatches here only when torch.version.hip is falsy and EXL3_ATTN16 != "0"; ROCm keeps calling
+the original kernels there. bc_attn.py (CUDA only) compiles its decode kernels from this module under the same switch.
+The QSA sparse kernels keep reducing through triton_paged._paged_attn_decode_combine_kernel (their partial layout).
+"""
+
+import math
+import os
+
+import torch
+import triton
+import triton.language as tl
+
+from .triton_paged import (
+ _get_h32, _rot_h32, _qc_load_kt, _qc_load_v,
+ _normalize_window, _check_tensor, _prep_sinks, _same_device,
+)
+
+# The EXL3_ATTN16 A/B switch lives in triton_paged.ATTN16 (read once at import)
+
+
+# ---- shared-memory ladder (upstream smem.py) ------------------------------------------------------------------
+
+_limit = {}
+_env_limit = int(os.environ.get("EXL3_TRITON_SMEM_LIMIT", "0") or "0")
+_debug = bool(os.environ.get("EXL3_TRITON_SMEM_DEBUG"))
+_picks = {}
+
+
+class NoFittingConfig(RuntimeError):
+ """No candidate in a ladder fits the device's shared memory."""
+
+
+def _dev_index(device) -> int:
+ idx = device.index if hasattr(device, "index") else device
+ return torch.cuda.current_device() if idx is None else idx
+
+
+def smem_limit(device) -> int:
+ """Dynamic shared memory per block the device grants (the opt-in maximum), in bytes."""
+ idx = _dev_index(device)
+ lim = _limit.get(idx)
+ if lim is None:
+ props = torch.cuda.get_device_properties(idx)
+ lim = getattr(props, "shared_memory_per_block_optin", 0)
+ if not lim:
+ lim = 64 * 1024 if props.major < 8 else 96 * 1024
+ if _env_limit:
+ lim = min(lim, _env_limit)
+ _limit[idx] = lim
+ return lim
+
+
+def pick_config(device, name: str, key, candidates, probe):
+ """First config in `candidates` whose compiled kernel fits the device's shared memory (cached per key)."""
+ idx = _dev_index(device)
+ limit = smem_limit(idx)
+ full_key = (torch.cuda.get_device_capability(idx), limit, name, key)
+ cfg = _picks.get(full_key, ...)
+ if cfg is None:
+ raise NoFittingConfig(f"{name}: no tile configuration fits the device's {limit} B of dynamic shared memory")
+ if cfg is not ...:
+ return cfg
+ need = None
+ for cand in candidates:
+ need = probe(cand)
+ if _debug:
+ print(f" -- smem: {name} {key} config {cand}: {need} B ({'fits' if need <= limit else 'over'} {limit} B)", flush = True)
+ if need <= limit:
+ _picks[full_key] = cand
+ return cand
+ _picks[full_key] = None
+ raise NoFittingConfig(
+ f"{name}: no tile configuration fits the device's {limit} B of dynamic shared memory "
+ f"(the smallest candidate needs {need} B)"
+ )
+
+
+def shared_bytes(kernel, args, **kwargs) -> int:
+ """Compile-only warmup of a JIT kernel with the launch's real arguments."""
+ return kernel.run(*args, grid = (1,), warmup = True, **kwargs).metadata.shared
+
+
+def halving_ladder(value: int, minimum: int = 16):
+ """value, value / 2, ... down to `minimum`."""
+ cands = [value]
+ while value // 2 >= minimum:
+ value //= 2
+ cands.append(value)
+ return cands
+
+
+def attn_decode_config(device, hd_pad: int, qc_block_rows: int | None = None) -> tuple[int, int, int]:
+ """(block_n, num_warps, num_stages) for the decode split kernel (upstream util/backend.py, CUDA branch).
+ hd_pad 512 (Gemma-4 global layers): 32 keys x 1 stage instead of 16 x 2, with the 16-row programs of decode_row_layout
+ (RTX 3090, 6-bit cache, 8K-32K keys: x1.35-1.5 at 1 row, x2.8 at 9 verify rows together with the row cap; 2 or 3 stages
+ give back most of the 1-row gain, 64 keys lose).
+ Quantized caches with HD_PAD <= 256 (qc_block_rows = the program's BLOCK_ROWS): the same budget, a kv tile of
+ 2^18 / (BLOCK_ROWS * HD_PAD) keys with one stage. The quantized split loop is bound by per-tile work (barriers, row
+ reductions, layout conversions), not by residency or DRAM bandwidth, so the widest tile that stays in registers wins
+ (RTX 3090: Qwen3.8 KV6, hd 256, x0.86 at 64K context and x0.93 at 8 verify rows; Gemma-3 KV8, hd 128, x0.82)"""
+ if hd_pad >= 512:
+ return 32, 4, 1
+ if qc_block_rows is not None:
+ return max(16, 262144 // (qc_block_rows * hd_pad)), 4, 1
+ return max(16, 8192 // hd_pad), 4, 2
+
+
+# ---- row-tiled KV append (upstream _paged_kv_update_rows_kernel) ----------------------------------------------
+
+# Row-tiled variant of the append above for the eager paths. For one token, all kv heads form one contiguous
+# n_kv_heads * head_dim row in both the source [bsz, len, n_kv, hd] and the cache [pages, page_size, n_kv, hd],
+# so a program copies BLOCK_T tokens x the whole row with one page lookup per token, instead of one small program
+# per (token, kv head). A pure copy: the cache contents are identical. _paged_kv_update_kernel stays for bc_attn,
+# which AOT-compiles it for the graph path
+def _paged_kv_update_rows_kernel(
+ k,
+ v,
+ k_cache,
+ v_cache,
+ block_table,
+ cache_seqlens,
+ num_pages_per_seq,
+ kv_append_len,
+ t_blocks,
+ ROW: tl.constexpr,
+ page_size: tl.constexpr,
+ BLOCK_T: tl.constexpr,
+ BLOCK_W: tl.constexpr,
+):
+ pid = tl.program_id(0)
+ batch = pid // t_blocks
+ t = (pid - batch * t_blocks) * BLOCK_T + tl.arange(0, BLOCK_T)
+ tmask = t < kv_append_len
+ logical_t = tl.load(cache_seqlens + batch) + t
+ page = logical_t // page_size
+ phys = tl.load(block_table + batch * num_pages_per_seq + page, mask=tmask, other=0)
+ dst_row = (phys.to(tl.int64) * page_size + (logical_t - page * page_size)) * ROW
+ src_row = (batch * kv_append_len + t).to(tl.int64) * ROW
+ for w0 in tl.static_range(0, ROW, BLOCK_W):
+ w = w0 + tl.arange(0, BLOCK_W)
+ m = tmask[:, None] & (w < ROW)[None, :]
+ src = src_row[:, None] + w[None, :]
+ dst = dst_row[:, None] + w[None, :]
+ tl.store(k_cache + dst, tl.load(k + src, mask=m), mask=m)
+ tl.store(v_cache + dst, tl.load(v + src, mask=m), mask=m)
+
+
+
+_KV_UPDATE_BLOCK_T = 8
+_KV_UPDATE_WARPS = 4
+
+
+def _paged_kv_update_rows(k, v, k_cache, v_cache, block_table, cache_seqlens, num_pages_per_seq, bsz, kv_append_len,
+ n_kv_heads, page_size, head_dim):
+ """Append kv_append_len new tokens per sequence to the paged cache (eager paths); contiguous tensors only,
+ the caller falls back to the per-head kernel otherwise"""
+ row = n_kv_heads * head_dim
+ t_blocks = triton.cdiv(kv_append_len, _KV_UPDATE_BLOCK_T)
+ _paged_kv_update_rows_kernel[(bsz * t_blocks,)](
+ k, v, k_cache, v_cache, block_table, cache_seqlens, num_pages_per_seq, kv_append_len, t_blocks,
+ row, page_size, _KV_UPDATE_BLOCK_T, min(1024, triton.next_power_of_2(row)),
+ num_warps = _KV_UPDATE_WARPS,
+ )
+
+
+
+# ---- software-pipelined quantized tile loads ------------------------------------------------------------------
+# The quantized split loop feeds loaded words to ALU unpacking, not to a dot, so Triton's loop pipeliner never overlaps
+# the loads with compute (num_stages is moot). The kernel therefore issues the NEXT tile's raw words (and scales) before
+# it expands and consumes the current one: _qp_* load, _qe_* expand. Same values as _qc_load_kt / _qc_load_v.
+
+def _qp_ld_k(qh, row_words, mask_n, pbase, W: tl.constexpr, BITS: tl.constexpr, head_dim: tl.constexpr, HD_PAD: tl.constexpr):
+ WPH: tl.constexpr = head_dim * W // 32
+ WPH_PAD: tl.constexpr = HD_PAD * W // 32
+ garr = tl.arange(0, WPH_PAD)
+ cols = (garr // W) * BITS + pbase + (garr % W)
+ if WPH_PAD > WPH:
+ return tl.load(qh + row_words[None, :] + cols[:, None], mask = mask_n[None, :] & (garr < WPH)[:, None], other = 0)
+ return tl.load(qh + row_words[None, :] + cols[:, None], mask = mask_n[None, :], other = 0)
+
+
+def _qp_ld_v(qh, row_words, mask_n, pbase, W: tl.constexpr, BITS: tl.constexpr, head_dim: tl.constexpr, HD_PAD: tl.constexpr):
+ WPH: tl.constexpr = head_dim * W // 32
+ WPH_PAD: tl.constexpr = HD_PAD * W // 32
+ garr = tl.arange(0, WPH_PAD)
+ cols = (garr // W) * BITS + pbase + (garr % W)
+ if WPH_PAD > WPH:
+ return tl.load(qh + row_words[:, None] + cols[None, :], mask = mask_n[:, None] & (garr < WPH)[None, :], other = 0)
+ return tl.load(qh + row_words[:, None] + cols[None, :], mask = mask_n[:, None], other = 0)
+
+
+def _qp_planes_k(qwords, scales, tok_rows, kv_head, mask_n,
+ BITS: tl.constexpr, n_kv_heads: tl.constexpr, head_dim: tl.constexpr, HD_PAD: tl.constexpr):
+ """Raw (HD_PAD-orientation) plane word tiles of one K tile + its scales; absent planes are (1, 1) zeros."""
+ GPT: tl.constexpr = n_kv_heads * head_dim // 32
+ G: tl.constexpr = head_dim // 32
+ G_PAD: tl.constexpr = HD_PAD // 32
+ qh = qwords + kv_head * (G * BITS)
+ row_words = tok_rows * (GPT * BITS)
+ z = tl.zeros((1, 1), tl.int32)
+ w8 = z
+ w4 = z
+ w2 = z
+ w1 = z
+ pbase = 0
+ if BITS & 8:
+ w8 = _qp_ld_k(qh, row_words, mask_n, pbase, 8, BITS, head_dim, HD_PAD)
+ pbase += 8
+ if BITS & 4:
+ w4 = _qp_ld_k(qh, row_words, mask_n, pbase, 4, BITS, head_dim, HD_PAD)
+ pbase += 4
+ if BITS & 2:
+ w2 = _qp_ld_k(qh, row_words, mask_n, pbase, 2, BITS, head_dim, HD_PAD)
+ pbase += 2
+ if BITS & 1:
+ w1 = _qp_ld_k(qh, row_words, mask_n, pbase, 1, BITS, head_dim, HD_PAD)
+ garr = tl.arange(0, G_PAD)
+ sc = tl.load(scales + tok_rows[None, :] * GPT + (kv_head * G + garr)[:, None],
+ mask = mask_n[None, :] & (garr < G)[:, None], other = 0.0)
+ return w8, w4, w2, w1, sc
+
+
+def _qp_planes_v(qwords, scales, tok_rows, kv_head, mask_n,
+ BITS: tl.constexpr, n_kv_heads: tl.constexpr, head_dim: tl.constexpr, HD_PAD: tl.constexpr):
+ GPT: tl.constexpr = n_kv_heads * head_dim // 32
+ G: tl.constexpr = head_dim // 32
+ G_PAD: tl.constexpr = HD_PAD // 32
+ qh = qwords + kv_head * (G * BITS)
+ row_words = tok_rows * (GPT * BITS)
+ z = tl.zeros((1, 1), tl.int32)
+ w8 = z
+ w4 = z
+ w2 = z
+ w1 = z
+ pbase = 0
+ if BITS & 8:
+ w8 = _qp_ld_v(qh, row_words, mask_n, pbase, 8, BITS, head_dim, HD_PAD)
+ pbase += 8
+ if BITS & 4:
+ w4 = _qp_ld_v(qh, row_words, mask_n, pbase, 4, BITS, head_dim, HD_PAD)
+ pbase += 4
+ if BITS & 2:
+ w2 = _qp_ld_v(qh, row_words, mask_n, pbase, 2, BITS, head_dim, HD_PAD)
+ pbase += 2
+ if BITS & 1:
+ w1 = _qp_ld_v(qh, row_words, mask_n, pbase, 1, BITS, head_dim, HD_PAD)
+ garr = tl.arange(0, G_PAD)
+ sc = tl.load(scales + tok_rows[:, None] * GPT + (kv_head * G + garr)[None, :],
+ mask = mask_n[:, None] & (garr < G)[None, :], other = 0.0)
+ return w8, w4, w2, w1, sc
+
+
+def _qe_k(w8, w4, w2, w1, sc, BITS: tl.constexpr, head_dim: tl.constexpr, HD_PAD: tl.constexpr):
+ """(HD_PAD, BLOCK_N) fp16 tile from _qp_planes_k output; bit-identical to _qc_load_kt."""
+ G_PAD: tl.constexpr = HD_PAD // 32
+ raw = tl.zeros((1, 1), tl.int32)
+ first = True
+ if BITS & 8:
+ raw = _qe_plane_k(w8, 8, HD_PAD)
+ first = False
+ if BITS & 4:
+ p = _qe_plane_k(w4, 4, HD_PAD)
+ raw = p if first else (raw << 4) | p
+ first = False
+ if BITS & 2:
+ p = _qe_plane_k(w2, 2, HD_PAD)
+ raw = p if first else (raw << 2) | p
+ first = False
+ if BITS & 1:
+ p = _qe_plane_k(w1, 1, HD_PAD)
+ raw = p if first else (raw << 1) | p
+ scx = tl.reshape(tl.broadcast_to(sc[:, None, :], (G_PAD, 32, sc.shape[1])), (HD_PAD, sc.shape[1]))
+ mh = (1 << (BITS - 1)) - 0.5
+ inv_m = 1.0 / (1 << (BITS - 1))
+ return ((raw.to(tl.float32) - mh) * (scx.to(tl.float32) * inv_m)).to(tl.float16)
+
+
+def _qe_v(w8, w4, w2, w1, sc, BITS: tl.constexpr, head_dim: tl.constexpr, HD_PAD: tl.constexpr):
+ """(BLOCK_N, HD_PAD) fp16 tile from _qp_planes_v output; bit-identical to _qc_load_v."""
+ G_PAD: tl.constexpr = HD_PAD // 32
+ raw = tl.zeros((1, 1), tl.int32)
+ first = True
+ if BITS & 8:
+ raw = _qe_plane_v(w8, 8, HD_PAD)
+ first = False
+ if BITS & 4:
+ p = _qe_plane_v(w4, 4, HD_PAD)
+ raw = p if first else (raw << 4) | p
+ first = False
+ if BITS & 2:
+ p = _qe_plane_v(w2, 2, HD_PAD)
+ raw = p if first else (raw << 2) | p
+ first = False
+ if BITS & 1:
+ p = _qe_plane_v(w1, 1, HD_PAD)
+ raw = p if first else (raw << 1) | p
+ scx = tl.reshape(tl.broadcast_to(sc[:, :, None], (sc.shape[0], G_PAD, 32)), (sc.shape[0], HD_PAD))
+ mh = (1 << (BITS - 1)) - 0.5
+ inv_m = 1.0 / (1 << (BITS - 1))
+ return ((raw.to(tl.float32) - mh) * (scx.to(tl.float32) * inv_m)).to(tl.float16)
+
+
+def _qe_plane_k(w, W: tl.constexpr, HD_PAD: tl.constexpr):
+ VPW: tl.constexpr = 32 // W
+ nib = (w[:, None, :] >> (tl.arange(0, VPW) * W)[None, :, None]) & ((1 << W) - 1)
+ return tl.reshape(nib, (HD_PAD, w.shape[1]))
+
+
+def _qe_plane_v(w, W: tl.constexpr, HD_PAD: tl.constexpr):
+ VPW: tl.constexpr = 32 // W
+ nib = (w[:, :, None] >> (tl.arange(0, VPW) * W)[None, None, :]) & ((1 << W) - 1)
+ return tl.reshape(nib, (w.shape[0], HD_PAD))
+
+
+# ---- decode kernels (upstream 1.6.0 triton_paged.py) ----------------------------------------------------------
+
+def _paged_attn_decode_split_kernel(
+ q,
+ k_cache,
+ v_cache,
+ block_table,
+ cache_seqlens,
+ out,
+ partial_o,
+ partial_ml,
+ k_scales,
+ v_scales,
+ h32,
+ split_len, # runtime: derived from the block-table bound, changes as it grows
+ num_pages_per_seq, # runtime: block-table width can grow without recompiling
+ num_splits, # runtime: the grid may be launched wider (graph path); extra splits idle
+ sinks, # last runtime arg: the BC launch appends it after the patched ints
+ QCK: tl.constexpr,
+ QCV: tl.constexpr,
+ q_len: tl.constexpr,
+ kv_append_len: tl.constexpr,
+ n_q_heads: tl.constexpr,
+ n_kv_heads: tl.constexpr,
+ page_size: tl.constexpr,
+ head_dim: tl.constexpr,
+ HD_PAD: tl.constexpr, # power of two >= head_dim: tile width, zero-padded columns
+ scale: tl.constexpr,
+ CAUSAL: tl.constexpr,
+ WINDOW_LEFT: tl.constexpr,
+ WINDOW_RIGHT: tl.constexpr,
+ SOFTCAP: tl.constexpr,
+ FINAL: tl.constexpr, # num_splits == 1: skip the combine pass, store directly to out
+ HAS_SINKS: tl.constexpr,
+ BLOCK_ROWS: tl.constexpr,
+ BLOCK_N: tl.constexpr,
+):
+ """Flash-decoding phase 1: one program per (batch, kv_head, row block, kv split). The rows of a
+ kv head are its (query position, sibling q head) pairs packed densely (decode_row_layout), so a
+ program reads and dequantizes each K/V tile once for up to BLOCK_ROWS of them."""
+ pid = tl.program_id(0)
+ split = tl.program_id(1)
+
+ group_size = n_q_heads // n_kv_heads
+ h_blocks = tl.cdiv(q_len * group_size, BLOCK_ROWS)
+ h_block = pid % h_blocks
+ bh = pid // h_blocks
+ batch = bh // n_kv_heads
+ kv_head = bh - batch * n_kv_heads
+
+ rows = tl.arange(0, BLOCK_ROWS)
+ row_idx = h_block * BLOCK_ROWS + rows
+ row_q = row_idx % q_len
+ row_h_local = row_idx // q_len
+ q_head = kv_head * group_size + row_h_local
+ valid_row = row_idx < q_len * group_size
+
+ offs_d = tl.arange(0, HD_PAD)
+ d_mask = offs_d < head_dim
+ q_base = ((batch * q_len + row_q) * n_q_heads + q_head) * head_dim
+ q_tile = tl.load(q + q_base[:, None] + offs_d[None, :], mask=valid_row[:, None] & d_mask[None, :], other=0.0)
+ if QCK > 0:
+ q_tile = _rot_h32(q_tile, h32, BLOCK_ROWS, HD_PAD)
+
+ total_k_len = tl.load(cache_seqlens + batch) + kv_append_len
+ q_abs = total_k_len - q_len + row_q
+
+ if WINDOW_LEFT >= 0:
+ # Sliding-window layers only need keys >= (first query position - window): split that range, not the whole
+ # sequence, across the programs. Splitting the sequence and skipping the tiles below the window leaves the
+ # window to the one or two splits that cover it (10x slower at 64K than at 16K for a 2048 window). The
+ # skipped keys carry exactly zero weight, so the result is unchanged
+ w_lo = tl.maximum(total_k_len - q_len - WINDOW_LEFT, 0)
+ w_lo = (w_lo // BLOCK_N) * BLOCK_N
+ w_span = tl.cdiv(tl.cdiv(total_k_len - w_lo, num_splits), BLOCK_N) * BLOCK_N
+ n_start = w_lo + split * w_span
+ n_end = tl.minimum(n_start + w_span, total_k_len)
+ else:
+ n_start = split * split_len
+ n_end = tl.minimum(n_start + split_len, total_k_len)
+
+ m = tl.full((BLOCK_ROWS,), -float("inf"), tl.float32)
+ l = tl.full((BLOCK_ROWS,), 0.0, tl.float32)
+ acc = tl.zeros((BLOCK_ROWS, HD_PAD), tl.float32)
+
+ # quantized K and V: software-pipelined loads (see _qp_planes_k); the dummies keep the loop-carried names defined
+ z0 = tl.zeros((1, 1), tl.int32)
+ zs = tl.zeros((1, 1), tl.float16)
+ kw8 = z0
+ kw4 = z0
+ kw2 = z0
+ kw1 = z0
+ vw8 = z0
+ vw4 = z0
+ vw2 = z0
+ vw1 = z0
+ ksc = zs
+ vsc = zs
+ if QCK > 0 and QCV > 0:
+ offs_p = n_start + tl.arange(0, BLOCK_N)
+ page_p = offs_p // page_size
+ phys_p = tl.load(block_table + batch * num_pages_per_seq + page_p, mask=offs_p < n_end, other=0)
+ rows_p = phys_p * page_size + (offs_p - page_p * page_size)
+ kw8, kw4, kw2, kw1, ksc = _qp_planes_k(k_cache, k_scales, rows_p, kv_head, offs_p < n_end, QCK, n_kv_heads, head_dim, HD_PAD)
+ vw8, vw4, vw2, vw1, vsc = _qp_planes_v(v_cache, v_scales, rows_p, kv_head, offs_p < n_end, QCV, n_kv_heads, head_dim, HD_PAD)
+
+ for n0 in range(n_start, n_end, BLOCK_N):
+ offs_n = n0 + tl.arange(0, BLOCK_N)
+ page = offs_n // page_size
+ page_off = offs_n - page * page_size
+ phys = tl.load(
+ block_table + batch * num_pages_per_seq + page,
+ mask=offs_n < n_end,
+ other=0,
+ )
+
+ if QCK > 0 and QCV > 0:
+ offs_x = offs_n + BLOCK_N
+ page_x = offs_x // page_size
+ phys_x = tl.load(block_table + batch * num_pages_per_seq + page_x, mask=offs_x < n_end, other=0)
+ rows_x = phys_x * page_size + (offs_x - page_x * page_size)
+ nk8, nk4, nk2, nk1, nksc = _qp_planes_k(k_cache, k_scales, rows_x, kv_head, offs_x < n_end, QCK, n_kv_heads, head_dim, HD_PAD)
+ nv8, nv4, nv2, nv1, nvsc = _qp_planes_v(v_cache, v_scales, rows_x, kv_head, offs_x < n_end, QCV, n_kv_heads, head_dim, HD_PAD)
+
+ if QCK > 0 and QCV > 0:
+ k_tile = _qe_k(kw8, kw4, kw2, kw1, ksc, QCK, head_dim, HD_PAD)
+ elif QCK > 0:
+ tok_rows = phys * page_size + page_off
+ k_tile = _qc_load_kt(k_cache, k_scales, tok_rows, kv_head, offs_d, offs_n < n_end, QCK, n_kv_heads, head_dim, HD_PAD)
+ else:
+ k_ptrs = k_cache + (((phys[None, :] * page_size + page_off[None, :]) * n_kv_heads + kv_head) * head_dim + offs_d[:, None])
+ if HD_PAD > head_dim:
+ k_tile = tl.load(k_ptrs, mask=(offs_n[None, :] < n_end) & d_mask[:, None], other=0.0)
+ else:
+ k_tile = tl.load(k_ptrs, mask=offs_n[None, :] < n_end, other=0.0)
+ scores = tl.dot(q_tile, k_tile) * scale
+ if SOFTCAP > 0.0:
+ scores_scaled = scores / SOFTCAP
+ scores = (2.0 / (1.0 + tl.exp(-2.0 * scores_scaled)) - 1.0) * SOFTCAP
+
+ valid = valid_row[:, None] & (offs_n[None, :] < n_end)
+ if CAUSAL:
+ valid = valid & (offs_n[None, :] <= q_abs[:, None])
+ if WINDOW_LEFT >= 0:
+ valid = valid & (offs_n[None, :] >= q_abs[:, None] - WINDOW_LEFT)
+ if WINDOW_RIGHT >= 0:
+ valid = valid & (offs_n[None, :] <= q_abs[:, None] + WINDOW_RIGHT)
+ scores = tl.where(valid, scores, -float("inf"))
+
+ m_new = tl.maximum(m, tl.max(scores, axis=1))
+ m_exp = tl.where(m_new == -float("inf"), 0.0, m_new)
+ p = tl.exp(scores - m_exp[:, None])
+ p = tl.where(valid, p, 0.0)
+ alpha = tl.where(m == -float("inf"), 0.0, tl.exp(m - m_exp))
+ l_new = l * alpha + tl.sum(p, axis=1)
+
+ if QCK > 0 and QCV > 0:
+ v_tile = _qe_v(vw8, vw4, vw2, vw1, vsc, QCV, head_dim, HD_PAD)
+ elif QCV > 0:
+ tok_rows_v = phys * page_size + page_off
+ v_tile = _qc_load_v(v_cache, v_scales, tok_rows_v, kv_head, offs_d, offs_n < n_end, QCV, n_kv_heads, head_dim, HD_PAD)
+ else:
+ v_ptrs = v_cache + (((phys[:, None] * page_size + page_off[:, None]) * n_kv_heads + kv_head) * head_dim + offs_d[None, :])
+ if HD_PAD > head_dim:
+ v_tile = tl.load(v_ptrs, mask=(offs_n[:, None] < n_end) & d_mask[None, :], other=0.0)
+ else:
+ v_tile = tl.load(v_ptrs, mask=offs_n[:, None] < n_end, other=0.0)
+ acc = acc * alpha[:, None] + tl.dot(p.to(v_tile.dtype), v_tile)
+ m = m_new
+ l = l_new
+ if QCK > 0 and QCV > 0:
+ kw8 = nk8
+ kw4 = nk4
+ kw2 = nk2
+ kw1 = nk1
+ ksc = nksc
+ vw8 = nv8
+ vw4 = nv4
+ vw2 = nv2
+ vw1 = nv1
+ vsc = nvsc
+
+ if FINAL:
+ if HAS_SINKS:
+ sink = tl.load(sinks + q_head, mask=valid_row, other=0.0).to(tl.float32)
+ m_top = tl.maximum(m, sink)
+ alpha_s = tl.where(m == -float("inf"), 0.0, tl.exp(m - m_top))
+ acc = acc * alpha_s[:, None]
+ l = l * alpha_s + tl.exp(sink - m_top)
+ out_tile = acc / tl.where(l[:, None] == 0.0, 1.0, l[:, None])
+ if QCV > 0:
+ out_tile = _rot_h32(out_tile, h32, BLOCK_ROWS, HD_PAD)
+ out_base = ((batch * q_len + row_q) * n_q_heads + q_head) * head_dim
+ tl.store(out + out_base[:, None] + offs_d[None, :], out_tile, mask=valid_row[:, None] & d_mask[None, :])
+ else:
+ if split < num_splits:
+ po_base = (pid * num_splits + split) * BLOCK_ROWS * HD_PAD
+ tl.store(partial_o + po_base + rows[:, None] * HD_PAD + offs_d[None, :], acc)
+ ml_base = (pid * num_splits + split) * BLOCK_ROWS * 2
+ tl.store(partial_ml + ml_base + rows * 2, m)
+ tl.store(partial_ml + ml_base + rows * 2 + 1, l)
+
+
+def _paged_attn_decode_combine_kernel(
+ partial_o,
+ partial_ml,
+ out,
+ h32,
+ num_splits, # runtime
+ sinks, # last runtime arg: the BC launch appends it after the patched int
+ QCV: tl.constexpr,
+ HAS_SINKS: tl.constexpr,
+ q_len: tl.constexpr,
+ n_q_heads: tl.constexpr,
+ n_kv_heads: tl.constexpr,
+ head_dim: tl.constexpr,
+ HD_PAD: tl.constexpr,
+ V_DIM: tl.constexpr, # output lanes per head (< head_dim when V rides zero-padded in the cache)
+ BLOCK_ROWS: tl.constexpr,
+ ROWS_SUB: tl.constexpr,
+ D_SUB: tl.constexpr,
+):
+ """Flash-decoding phase 2: reduce the per-split partial accumulators. The output row is
+ written V_DIM wide per head: with an asymmetric V head dim the padded lanes are dropped
+ here, so the result feeds o_proj directly. Grid axis 1 splits
+ the program's (BLOCK_ROWS, HD_PAD) tile into (ROWS_SUB, D_SUB) sub-tiles so the serial
+ walk over the splits runs on many CTAs (decode launches only a few programs)."""
+ pid = tl.program_id(0)
+ sub = tl.program_id(1)
+ D_CHUNKS: tl.constexpr = HD_PAD // D_SUB
+ r_c = sub // D_CHUNKS
+ d_c = sub - r_c * D_CHUNKS
+
+ group_size = n_q_heads // n_kv_heads
+ h_blocks = tl.cdiv(q_len * group_size, BLOCK_ROWS)
+ h_block = pid % h_blocks
+ bh = pid // h_blocks
+ batch = bh // n_kv_heads
+ kv_head = bh - batch * n_kv_heads
+
+ # Same dense (query, head) rows as the split kernel
+ rows = r_c * ROWS_SUB + tl.arange(0, ROWS_SUB)
+ row_idx = h_block * BLOCK_ROWS + rows
+ row_q = row_idx % q_len
+ row_h_local = row_idx // q_len
+ q_head = kv_head * group_size + row_h_local
+ valid_row = row_idx < q_len * group_size
+
+ offs_d = d_c * D_SUB + tl.arange(0, D_SUB)
+ d_mask = offs_d < head_dim
+
+ # Splits are walked S_BLK at a time as one masked tile load per pass: a scalar loop with a
+ # runtime trip count and no pipelining serializes a full load latency per split (65 splits
+ # at a 2K sparse context cost 20 us), a tile load amortizes it
+ S_BLK: tl.constexpr = 16
+ offs_s = tl.arange(0, S_BLK)
+ m_max = tl.full((ROWS_SUB,), -float("inf"), tl.float32)
+ for s0 in range(0, num_splits, S_BLK):
+ sidx = s0 + offs_s
+ s_mask = sidx < num_splits
+ ml_idx = ((pid * num_splits + sidx)[:, None] * BLOCK_ROWS + rows[None, :]) * 2
+ m_s = tl.load(partial_ml + ml_idx, mask=s_mask[:, None], other=-float("inf"))
+ m_max = tl.maximum(m_max, tl.max(m_s, axis=0))
+
+ if HAS_SINKS:
+ # Learned per-head sink joins the softmax denominator at the final reduction
+ sink = tl.load(sinks + q_head, mask=valid_row, other=0.0).to(tl.float32)
+ m_max = tl.maximum(m_max, sink)
+
+ l_sum = tl.zeros((ROWS_SUB,), tl.float32)
+ acc = tl.zeros((ROWS_SUB, D_SUB), tl.float32)
+ m_safe = tl.where(m_max == -float("inf"), 0.0, m_max)
+ for s0 in range(0, num_splits, S_BLK):
+ sidx = s0 + offs_s
+ s_mask = sidx < num_splits
+ ml_idx = ((pid * num_splits + sidx)[:, None] * BLOCK_ROWS + rows[None, :]) * 2
+ m_s = tl.load(partial_ml + ml_idx, mask=s_mask[:, None], other=-float("inf"))
+ l_s = tl.load(partial_ml + ml_idx + 1, mask=s_mask[:, None], other=0.0)
+ w = tl.where(m_s == -float("inf"), 0.0, tl.exp(m_s - m_safe[None, :]))
+ po_idx = (pid * num_splits + sidx)[:, None, None] * (BLOCK_ROWS * HD_PAD) \
+ + rows[None, :, None] * HD_PAD + offs_d[None, None, :]
+ o_s = tl.load(partial_o + po_idx, mask=s_mask[:, None, None], other=0.0)
+ acc += tl.sum(o_s * w[:, :, None], axis=0)
+ l_sum += tl.sum(l_s * w, axis=0)
+
+ if HAS_SINKS:
+ l_sum += tl.exp(sink - m_safe)
+ out_tile = acc / tl.where(l_sum[:, None] == 0.0, 1.0, l_sum[:, None])
+ if QCV > 0:
+ out_tile = _rot_h32(out_tile, h32, ROWS_SUB, D_SUB) # 32-wide groups: D_SUB % 32 == 0
+ out_base = ((batch * q_len + row_q) * n_q_heads + q_head) * V_DIM
+ tl.store(out + out_base[:, None] + offs_d[None, :], out_tile, mask=valid_row[:, None] & (offs_d < V_DIM)[None, :])
+
+
+def decode_row_layout(q_len: int, group_size: int, hd_pad: int) -> tuple[int, int]:
+ """(BLOCK_ROWS, row blocks per kv head) for the decode split / combine kernels.
+
+ A kv head's rows are its q_len * group_size (query position, sibling q head) pairs, packed densely
+ and cut into programs of up to 32 rows, each of which reads and dequantizes the head's K/V tiles
+ once. (Padding query positions up to a power of two and giving a program 16 / that many heads used
+ to split a 6-head group across three programs for a 5-token verify step, tripling the tile work.)
+ 32 rows pays off at every head_dim up to 256 on Ampere, Blackwell and RDNA3 alike, the fp32
+ accumulator notwithstanding, since the tile loads dominate; at least 16 rows, the dots' minimum.
+ At head_dim 512 the 32 x 512 fp32 accumulator of a 4-warp program spills: 16-row programs are x1.8-1.95 faster
+ on a 9-row verify (72 rows per kv head) although each one re-reads the head's K/V (RTX 3090, 6-bit cache)."""
+ rows = q_len * group_size
+ block_rows = max(16, min(16 if hd_pad >= 512 else 32, triton.next_power_of_2(rows)))
+ return block_rows, triton.cdiv(rows, block_rows)
+
+
+def combine_subtiles(block_rows: int, hd_pad: int) -> tuple[int, int]:
+ """(ROWS_SUB, D_SUB) for the combine kernel: the smallest sub-tile whose h32 rotation still
+ forms a >= 16-row tl.dot (ROWS_SUB * D_SUB >= 512), D_SUB a multiple of 32."""
+ d_sub = min(128, hd_pad)
+ rows_sub = min(block_rows, max(1, 512 // d_sub))
+ while rows_sub * d_sub < 512 and d_sub < hd_pad:
+ d_sub *= 2
+ if rows_sub * d_sub < 512:
+ rows_sub, d_sub = block_rows, hd_pad
+ return rows_sub, d_sub
+
+
+
+
+# ---- launcher (upstream paged_attn_triton_decode; Kyojin's split_batch kept) -----------------------------------
+
+_decode_sm_count = {}
+
+
+_QDEC_CHECK = os.environ.get("EXL3_QDEC_CHECK") == "1"
+_QDEC_STATS = []
+
+
+def paged_attn_triton_decode_cu(
+ q: torch.Tensor,
+ k: torch.Tensor | None,
+ v: torch.Tensor | None,
+ k_cache: torch.Tensor,
+ v_cache: torch.Tensor,
+ block_table: torch.Tensor,
+ cache_seqlens: torch.Tensor,
+ causal: bool = False,
+ softmax_scale: float | None = None,
+ window_size: int | tuple[int, int] | None = None,
+ softcap: float = 0.0,
+ sinks: torch.Tensor | None = None,
+ out: torch.Tensor | None = None,
+ block_n: int | None = None,
+ num_splits: int | None = None,
+ max_kv_len: int | None = None,
+ qc: tuple | None = None, # (k_scales, v_scales, k_bits, v_bits): caches are packed int32
+ pre_appended_len: int = 0, # new tokens already written to the cache; count but don't append
+ n_kv_heads_override: int | None = None,
+ num_warps: int | None = None,
+ num_stages: int | None = None,
+ split_batch: int | None = None, # batch size the split count is derived from (default: bsz)
+) -> torch.Tensor:
+ """Flash-decoding paged attention for short queries: the kv sequence is split across
+ programs (sized from the block table, so no host sync on cache_seqlens) and reduced in a
+ second pass. GQA sibling q heads share K/V tiles within a program."""
+ _check_tensor("q", q)
+ _check_tensor("block_table", block_table, None)
+ _check_tensor("cache_seqlens", cache_seqlens, None)
+
+ bsz, q_len, n_q_heads, head_dim = q.shape
+ if qc is None:
+ _check_tensor("k_cache", k_cache)
+ _check_tensor("v_cache", v_cache)
+ if q.ndim != 4 or k_cache.ndim != 4 or v_cache.ndim != 4:
+ raise ValueError("q, k_cache and v_cache must be rank-4 tensors")
+ _, page_size, n_kv_heads, cache_dim = k_cache.shape
+ if v_cache.shape != k_cache.shape:
+ raise ValueError("v_cache must have the same shape as k_cache")
+ if cache_dim != head_dim:
+ raise ValueError("q and cache head dimensions must match")
+ else:
+ page_size = k_cache.shape[1]
+ n_kv_heads = n_kv_heads_override
+ if not _same_device(q, k_cache, v_cache, block_table, cache_seqlens):
+ raise ValueError("q, caches, block_table and cache_seqlens must be on the same CUDA device")
+ if n_q_heads % n_kv_heads != 0:
+ raise ValueError("n_q_heads must be divisible by n_kv_heads")
+ if head_dim > 512:
+ raise ValueError("paged_attn_triton_decode supports head_dim <= 512")
+ if qc is not None and head_dim % 32 != 0:
+ raise ValueError("quantized caches need head_dim to be a multiple of 32")
+ hd_pad = triton.next_power_of_2(head_dim) # tile width; non-power-of-two dims are zero-padded
+ if q_len > 16:
+ raise ValueError("paged_attn_triton_decode supports q_len <= 16")
+
+ kv_append_len = pre_appended_len
+ if k is not None or v is not None:
+ if k is None or v is None:
+ raise ValueError("k and v must be provided together")
+ _check_tensor("k", k)
+ _check_tensor("v", v)
+ if k.shape[:1] != (bsz,) or k.shape[2:] != (n_kv_heads, head_dim):
+ raise ValueError("k/v shape must be [batch, seqlen_new, kv_heads, head_dim]")
+ kv_append_len = k.shape[1]
+
+ if out is None:
+ out = torch.empty_like(q)
+
+ if softmax_scale is None:
+ softmax_scale = 1.0 / math.sqrt(head_dim)
+ window_left, window_right = _normalize_window(window_size)
+ sinks, has_sinks = _prep_sinks(sinks, n_q_heads, q)
+
+ if qc is not None:
+ k_scales, v_scales, qck, qcv = qc
+ h32 = _get_h32(q.device)
+ else:
+ k_scales, v_scales, qck, qcv = q, q, 0, 0
+ h32 = q
+
+ # K + V tiles in smem across num_stages; on small-smem devices the ladder halves the kv tile
+ qc_rows = decode_row_layout(q_len, n_q_heads // n_kv_heads, hd_pad)[0] if qc is not None else None
+ cfg_block_n, cfg_warps, cfg_stages = attn_decode_config(q.device, hd_pad, qc_rows)
+ if num_warps is None:
+ num_warps = cfg_warps
+ if num_stages is None:
+ num_stages = cfg_stages
+ candidates = halving_ladder(cfg_block_n) if block_n is None else [block_n]
+
+ group_size = n_q_heads // n_kv_heads
+ block_rows, h_blocks = decode_row_layout(q_len, group_size, hd_pad)
+ num_pages_per_seq = block_table.shape[1]
+
+ # Upper bound on kv length: caller-provided hint, else from the block table shape
+ # (cache_seqlens stays on the device; no sync). A loose bound wastes split parallelism when
+ # the table is allocated much larger than the live sequence
+ max_k_len = num_pages_per_seq * page_size + kv_append_len
+ if max_kv_len is not None:
+ max_k_len = min(max_k_len, max_kv_len + kv_append_len)
+
+ programs = bsz * n_kv_heads * h_blocks
+ dev = q.device.index
+ if dev not in _decode_sm_count:
+ _decode_sm_count[dev] = torch.cuda.get_device_properties(q.device).multi_processor_count
+ target = 2 * _decode_sm_count[dev]
+ programs_split = programs if split_batch is None else programs // bsz * split_batch
+ req_splits = num_splits
+
+ if qc is not None and qck > 0 and qcv > 0:
+ from . import qdec_cuda
+ qcfg = qdec_cuda.make_cfg(q_len, n_q_heads, n_kv_heads, head_dim, qck, qcv, page_size, causal, softmax_scale,
+ block_rows, window_left, window_right, softcap, kv_append_len)
+ if qcfg is not None and (h_blocks == 1 or qcfg.get("rows_kernel")):
+ if qcfg.get("rows_kernel"):
+ # many-row kernel (cu/qdec_rows.cu): all of a kv head's (query, head) rows in one program
+ block_rows, h_blocks = qcfg["block_rows"], 1
+ programs = bsz * n_kv_heads
+ programs_split = programs if split_batch is None else programs // bsz * split_batch
+ # tensor-core CUDA split kernel on the packed words (cu/qdec.cu): one CTA per SM-share, 16-token slabs
+ qsplits = req_splits if req_splits is not None else \
+ max(1, min(qdec_cuda.split_cap(qcfg, q.device, programs_split), triton.cdiv(max_k_len, 16), 128))
+ qsplit_len = triton.cdiv(triton.cdiv(max_k_len, qsplits), 16) * 16
+ partial_o = torch.empty(programs * qsplits * block_rows * hd_pad, dtype = torch.float32, device = q.device)
+ partial_ml = torch.empty(programs * qsplits * block_rows * 2, dtype = torch.float32, device = q.device)
+ with torch.cuda.device(q.device):
+ qdec_cuda.get_kernel(qcfg).launch(
+ (programs, qsplits),
+ [q.data_ptr(), k_cache.data_ptr(), v_cache.data_ptr(), block_table.data_ptr(), cache_seqlens.data_ptr(),
+ out.data_ptr(), partial_o.data_ptr(), partial_ml.data_ptr(), k_scales.data_ptr(), v_scales.data_ptr(),
+ h32.data_ptr()],
+ [qsplit_len, num_pages_per_seq, qsplits])
+ rows_sub, d_sub = combine_subtiles(block_rows, hd_pad)
+ _paged_attn_decode_combine_kernel[(programs, (block_rows // rows_sub) * (hd_pad // d_sub))](
+ partial_o, partial_ml, out, h32,
+ qsplits, sinks, qcv, has_sinks, q_len, n_q_heads, n_kv_heads, head_dim, hd_pad, head_dim,
+ block_rows, rows_sub, d_sub,
+ num_warps=4, num_stages=1,
+ )
+ if _QDEC_CHECK:
+ ref = paged_attn_triton_decode_cu.__wrapped_ref__(q, k, v, k_cache, v_cache, block_table, cache_seqlens, causal,
+ softmax_scale, window_size, softcap, sinks, None, block_n, num_splits, max_kv_len, qc, pre_appended_len,
+ n_kv_heads_override, num_warps, num_stages, split_batch)
+ d = (ref.float() - out.float()).abs().max().item(); mx = ref.float().abs().max().item()
+ _QDEC_STATS.append((d, mx, d / max(mx, 1e-9), q_len, head_dim, qck, qcv))
+ return out
+
+ def prepare(block_n):
+ """Split count, partial buffers and the split kernel's argument list for one kv tile."""
+ splits = req_splits
+ if splits is None:
+ splits = max(1, min(target // programs_split, triton.cdiv(max_k_len, 1 * block_n), 128))
+ split_len = triton.cdiv(triton.cdiv(max_k_len, splits), block_n) * block_n
+ if splits > 1:
+ partial_o = torch.empty(programs * splits * block_rows * hd_pad, dtype = torch.float32, device = q.device)
+ partial_ml = torch.empty(programs * splits * block_rows * 2, dtype = torch.float32, device = q.device)
+ else:
+ partial_o = q # unused
+ partial_ml = q # unused
+ args = (
+ q, k_cache, v_cache, block_table, cache_seqlens, out, partial_o, partial_ml,
+ k_scales, v_scales, h32,
+ split_len, num_pages_per_seq, splits, sinks,
+ qck, qcv, q_len, kv_append_len, n_q_heads, n_kv_heads,
+ page_size, head_dim, hd_pad, float(softmax_scale),
+ bool(causal), int(window_left), int(window_right), float(softcap or 0.0),
+ splits == 1, has_sinks, block_rows, block_n,
+ )
+ return args, splits, partial_o, partial_ml
+
+ with torch.cuda.device(q.device):
+ pick_key = (head_dim, hd_pad, qck, qcv, q_len, block_rows, h_blocks, bool(causal), window_left >= 0,
+ window_right >= 0, has_sinks, num_warps, num_stages, candidates[0])
+ block_n = pick_config(
+ q.device, "paged_attn_decode_cu", pick_key, candidates,
+ lambda bn: shared_bytes(_paged_attn_decode_split_kernel, prepare(bn)[0],
+ num_warps = num_warps, num_stages = num_stages))
+ args, num_splits, partial_o, partial_ml = prepare(block_n)
+
+ if k is not None and kv_append_len:
+ if all(t.is_contiguous() for t in (k, v, k_cache, v_cache, block_table)):
+ _paged_kv_update_rows(k, v, k_cache, v_cache, block_table, cache_seqlens, num_pages_per_seq, bsz,
+ kv_append_len, n_kv_heads, page_size, head_dim)
+ else:
+ from .triton_paged import _paged_kv_update_kernel
+ update_block_d = triton.next_power_of_2(head_dim)
+ _paged_kv_update_kernel[(bsz * kv_append_len, n_kv_heads, triton.cdiv(head_dim, update_block_d))](
+ k, v, k_cache, v_cache, block_table, cache_seqlens,
+ num_pages_per_seq, kv_append_len, n_kv_heads, page_size, head_dim, update_block_d,
+ num_warps=2, num_stages=3,
+ )
+
+ _paged_attn_decode_split_kernel[(programs, num_splits)](
+ *args, num_warps = num_warps, num_stages = num_stages,
+ )
+
+ if num_splits > 1:
+ rows_sub, d_sub = combine_subtiles(block_rows, hd_pad)
+ _paged_attn_decode_combine_kernel[(programs, (block_rows // rows_sub) * (hd_pad // d_sub))](
+ partial_o, partial_ml, out, h32,
+ num_splits, sinks, qcv, has_sinks, q_len, n_q_heads, n_kv_heads, head_dim, hd_pad, head_dim,
+ block_rows, rows_sub, d_sub,
+ num_warps=4, num_stages=1,
+ )
+ return out
+
+
+if _QDEC_CHECK:
+ import atexit
+ _orig = paged_attn_triton_decode_cu
+
+ def _ref_call(*a):
+ from . import qdec_cuda
+ qdec_cuda.ENABLED = False
+ try:
+ return _orig(*a)
+ finally:
+ qdec_cuda.ENABLED = True
+ paged_attn_triton_decode_cu.__wrapped_ref__ = _ref_call
+
+ @atexit.register
+ def _report():
+ if _QDEC_STATS:
+ w = max(_QDEC_STATS, key = lambda r: r[2])
+ print(f"QDEC_CHECK {len(_QDEC_STATS)} calls; worst rel diff {w[2]:.3e} (abs {w[0]:.3e}, ref max {w[1]:.3e}, q_len {w[3]}, hd {w[4]}, bits {w[5]}/{w[6]}); "
+ f"mean rel {sum(r[2] for r in _QDEC_STATS) / len(_QDEC_STATS):.3e}", flush = True)
diff --git a/exllamav3/modules/attn.py b/exllamav3/modules/attn.py
index b41c67b..22abca6 100644
--- a/exllamav3/modules/attn.py
+++ b/exllamav3/modules/attn.py
@@ -132,6 +132,24 @@ def prepare_flash_attn(input_ids: torch.Tensor, params: dict) -> torch.Tensor:
return input_ids
+def split_params_by_sequence(params: dict, bsz: int) -> list[dict]:
+ """One params dict per sequence of a paged batch: the block table row, the cache length and the positions of that
+ sequence (views, made once per forward and shared by all attention layers). Run after prepare_inputs, which makes
+ the positions an alias of the cache lengths."""
+ assert params.get("position_ids") is None, "per-sequence attention does not take position_ids"
+ positions = params.get("positions")
+ out = []
+ for b in range(bsz):
+ p = dict(params)
+ p.pop("dev_cache", None)
+ p["block_table"] = params["block_table"][b:b + 1]
+ p["cache_seqlens"] = params["cache_seqlens"][b:b + 1]
+ if positions is not None:
+ p["positions"] = p["cache_seqlens"] if positions is params["cache_seqlens"] else positions[b:b + 1]
+ out.append(p)
+ return out
+
+
def prepare_for_attn(input_ids: torch.Tensor, params: dict) -> torch.Tensor:
"""
Add attn parameters to state
@@ -445,6 +463,7 @@ class Attention(Module):
self.prealloc_qkvh_1 = None
self.prealloc_qkv_out_1 = None
self.prealloc_qkv_cptrs_1 = None
+ self.prealloc_qkv_m = {}
self.prealloc_qkv_carrier = None
@@ -634,6 +653,7 @@ class Attention(Module):
self.prealloc_qkvh_1 = None
self.prealloc_qkv_out_1 = None
self.prealloc_qkv_cptrs_1 = None
+ self.prealloc_qkv_m = {}
self.prealloc_qkv_carrier = None
@@ -654,7 +674,16 @@ class Attention(Module):
attn_mode = params.get("attn_mode", "flash_attn_nc")
match attn_mode:
case "flash_attn":
- x = self.decode_flash_attn(x, bsz, seqlen, params)
+ if bsz > 1 and params.get("row_inv_per_seq"):
+ # Row-invariant multi-job step (generator/row_groups.py): the attention block of each sequence is the
+ # block it would run alone. The split plan of the paged decode, the QSA selection and the graph path
+ # all follow the batch size and the longest sequence of the batch.
+ seq_params = params.get("row_inv_seq_params")
+ if seq_params is None:
+ seq_params = params["row_inv_seq_params"] = split_params_by_sequence(params, bsz)
+ x = torch.cat([self.decode_flash_attn(x[b:b + 1], 1, seqlen, seq_params[b]) for b in range(bsz)], dim = 0)
+ else:
+ x = self.decode_flash_attn(x, bsz, seqlen, params)
case "flash_attn_nc":
x = self.decode_flash_attn_nc(x, bsz, seqlen, params)
case _:
@@ -902,13 +931,19 @@ class Attention(Module):
qg, kv = self.prealloc_qkv_out_1
c_ptrs = self.prealloc_qkv_cptrs_1
else:
- qkvh = torch.empty((mq.num_src, m, self.q_proj.in_features), dtype = torch.half, device = x.device)
- if self.interleaved_gate:
- qg = torch.empty((1, m, 2 * n_q), dtype = torch.half, device = x.device)
- else:
- qg = torch.empty((2, m, n_q), dtype = torch.half, device = x.device)
- kv = torch.empty((2, m, n_kv), dtype = torch.half, device = x.device)
- c_ptrs = mq.c_ptrs([qg[0], kv[0], kv[1]] + ([qg[1]] if self.g_proj is not None else []))
+ # Per-m buffers + output-pointer table, built once: the pointer upload is a host-to-device copy, which a CUDA graph
+ # capture of an m > 1 step (batched decode, MTP / ngram verify) cannot contain, and the addresses stay stable
+ pre = self.prealloc_qkv_m.get((m, x.device))
+ if pre is None:
+ qkvh = torch.empty((mq.num_src, m, self.q_proj.in_features), dtype = torch.half, device = x.device)
+ if self.interleaved_gate:
+ qg = torch.empty((1, m, 2 * n_q), dtype = torch.half, device = x.device)
+ else:
+ qg = torch.empty((2, m, n_q), dtype = torch.half, device = x.device)
+ kv = torch.empty((2, m, n_kv), dtype = torch.half, device = x.device)
+ c_ptrs = mq.c_ptrs([qg[0], kv[0], kv[1]] + ([qg[1]] if self.g_proj is not None else []))
+ pre = self.prealloc_qkv_m[(m, x.device)] = (qkvh, qg, kv, c_ptrs)
+ qkvh, qg, kv, c_ptrs = pre
ext.exl3_mgemm(
x,
mq.ptrs_trellis,
@@ -1305,6 +1340,13 @@ class Attention(Module):
# QSA dense regime: the past is bounded by the sparse threshold, which lets the
# quantized-cache prefill size its staging to the window instead of the job's pages
max_kv_len = int(qsa_seqlens_cpu.max().item()) if qsa_seqlens_cpu is not None else None
+ # CUDA: prefill-sized chunks take the bound from the host copy of cache_seqlens (built on the CPU by the
+ # generator, no sync), as upstream exllamav3 1.6.0 (MIT) attn.py does. Without it the quantized-cache prefill
+ # stages (dequantizes) the job's whole page span for every chunk (+19.8 % TTFT on a 178K-token prompt, RTX 3090)
+ if max_kv_len is None and seqlen > 16 and not torch.version.hip:
+ cs_host = params.get("cache_seqlens")
+ if isinstance(cs_host, torch.Tensor) and cs_host.device.type == "cpu" and cs_host.numel():
+ max_kv_len = int(cs_host.max())
if (
1 < seqlen <= MAX_BSZN_GEMV_R and non_causal_spans is None and
os.environ.get("EXL3_VERIFY_ATTN_LOOP", "0") != "0"
diff --git a/exllamav3/modules/block_sparse_mlp.py b/exllamav3/modules/block_sparse_mlp.py
index bac39e2..8cdb480 100644
--- a/exllamav3/modules/block_sparse_mlp.py
+++ b/exllamav3/modules/block_sparse_mlp.py
@@ -44,10 +44,32 @@ MTILE_T1, MTILE_T2 = 16, 32
# Fused-kernel row capacity per expert when the wide tiles apply: with them the fused kernel
# beats the batched reconstruct tier up to 256 rows (Qwen3.8 4k chunk: 128 -> 256 rows +3%)
FUSED_ROWS_WIDE = int(os.environ.get("EXL3_MOE_FUSED_ROWS_WIDE", 256))
+# Grouped prefill tier (exl3_moe_grouped: token-parallel hadamard kernels + two grouped one-CTA-per-tile GEMMs) for the
+# experts above MOEG_LO rows, instead of the persistent expert-group kernel's 64-row launch. Needs the deterministic slot
+# path, the mul1 codebook and 2..6 bit tensors; EXL3_MOE_GROUPED=0 restores the persistent kernel
+MOEG = os.environ.get("EXL3_MOE_GROUPED", "1") != "0"
+MOEG_LO = int(os.environ.get("EXL3_MOE_GROUPED_LO", 33))
+# Row capacity of the grouped tier per expert (the persistent kernel is capped by its temp buffers, this tier is not); experts above
+# it take the batched reconstruct tier as before
+MOEG_ROWS = int(os.environ.get("EXL3_MOE_GROUPED_ROWS", 1 << 20))
# Deterministic (slot + gather) accumulation for the fused kernel's outputs; EXL3_MOE_FUSED_DET=0
# restores the atomic adds
FUSED_DET = os.environ.get("EXL3_MOE_FUSED_DET", "1") != "0"
MAX_BSZN = 8 # must match MAX_BSZN in exllamav3_ext/libtorch/blocksparse_mlp.h
+# Row chunking: 9..EXL3_MOE_ROW_CHUNK_MAX rows of a pack without a fused MoE kernel run as <= MAX_BSZN-row slices through
+# the bszN decode kernels instead of the per-expert tier (host readback of the expert counts + one launch group per expert,
+# per layer); rows are independent in an MoE block. 0 disables. Measured on an RTX 3090 (Qwen3-30B-A3B 3INST)
+_ROW_CHUNK_MAX = int(os.environ.get("EXL3_MOE_ROW_CHUNK_MAX", "64"))
+# Fused exl3_moe kernel for 3INST packs (no mcg / mul1 codebook, e.g. upstream-quantized public packs), CUDA. Without it their
+# > MAX_BSZN-row blocks take the row chunks above or the per-expert tier. 0 restores that.
+_FUSED_3INST = os.environ.get("EXL3_MOE_FUSED_3INST", "1") != "0"
+# ... but up to this many rows the row chunks stay faster (2 bszN slices beat one exl3_moe launch at 9-16 rows on a 3090)
+_FUSED_3INST_MIN = int(os.environ.get("EXL3_MOE_FUSED_3INST_MIN", "16"))
+# Sync-free fused tier bound: top-k picks distinct experts, so no expert holds more rows than there are tokens and
+# num_tokens <= fused_rows already keeps every expert inside the fused tier (the num_tokens * top_k bound skipped the
+# expert-count readback only up to fused_rows / top_k tokens). EXL3_MOE_SYNC_FREE_TOKENS=0 restores the top-k bound.
+# CUDA default only (measured there); ROCm keeps the top-k bound unless set to 1
+SYNC_FREE_TOKENS = os.environ.get("EXL3_MOE_SYNC_FREE_TOKENS", "1" if torch.version.hip is None else "0") != "0"
# Expert-deduplicated grouped MoE (verify batches decode each picked expert once for all of its
@@ -202,6 +224,9 @@ class ExpertsCFG:
out_bszn: torch.Tensor | None = None # (MAX_BSZN, H) fp32 routed sum of the bsz<=MAX_BSZN path
+# Routed-weighted per-expert Hessians for the quantizer (see Linear.cap_rkey, convert_model.build_rwh_blends)
+_RWH = os.environ.get("EXL3_RWH", "0") == "1"
+
class BlockSparseMLP(BlockSparseMLP_CPU, Module):
def __init__(
@@ -498,6 +523,12 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
qbits_key = qbits_key,
)
+ if _RWH and qmap:
+ for lin, nm in ((gate, "input"), (up, "input"), (down, "down")):
+ if lin is not None:
+ lin.cap_rkey = f"{qmap}.r{idx}.{nm}"
+ lin.qmap_q = f"{qmap}.q{idx}.{nm}"
+
self.ups.append(up)
if gate is not None:
self.gates.append(gate)
@@ -539,6 +570,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
self.is_quantized = False
self.support_fused = False
+ self.fused_3inst = False
self.support_quant_paths = False
self.multi_gate = None
self.multi_up = None
@@ -898,10 +930,12 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
)
self.support_fused = (
hasattr(ext, "exl3_moe") and hasattr(ext, "exl3_moe_max_concurrency") and
- cbs[0] == cbs[1] == cbs[2] and cbs[0] in ((True, False), (False, True)) and
+ cbs[0] == cbs[1] == cbs[2] and
+ cbs[0] in (((True, False), (False, True), (False, False)) if _FUSED_3INST else ((True, False), (False, True))) and
self.support_quant_paths and
(self.fused_fp16_interm or self.interm_dtype in (None, torch.half))
)
+ self.fused_3inst = self.support_fused and cbs[0] == (False, False)
# One K for the whole layer: the grouped GEMV is templated on the experts' trellis
# bitrate and gate/up/down share it (the allocator assigns per layer).
ks = {multi.K for multi in (self.multi_gate, self.multi_up, self.multi_down)}
@@ -1199,6 +1233,28 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
return None
from .expert_store import get_store
return get_store(self.config).register(self, device)
+ def _moeg_ok(self):
+ # Grouped prefill tier preconditions (see MOEG), evaluated once
+ ok = self.__dict__.get("_moeg_ok_cache")
+ if ok is None:
+ ok = self._moeg_ok_eval()
+ self._moeg_ok_cache = ok
+ return ok
+
+ def _moeg_ok_eval(self):
+ if not MOEG or self.fused_mode_buffers is None or not self.gated or not self.mtile_ok:
+ return False
+ if self.activation_fn_idx not in (0, 1):
+ return False
+ I = self.fused_mode_buffers.temp_intermediate_g.shape[2]
+ H = self.hidden_size
+ if H % 128 or I % 128 or H % 32 or I % 32:
+ return False
+ if not (self.multi_gate.mul1 and self.multi_up.mul1 and self.multi_down.mul1):
+ return False
+ if not hasattr(ext, "exl3_moe_grouped"):
+ return False
+ return bool(ext.exl3_moe_grouped_supported(self.multi_gate.K, self.multi_up.K, self.multi_down.K))
def load_routing(self, **kwargs):
@@ -1402,8 +1458,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
slot = None
if scratch is not None:
# groups were laid out after the fused slots, in plan order, len(grp) * cmax each
- slot = sum(c for c in expert_count_list[:self.num_local_experts or self.num_experts]
- if 0 < c <= self.fused_rows) if self.fused_mode_buffers is not None else 0
+ slot = self._fused_slots if self.fused_mode_buffers is not None else 0
for grp in groups:
out_slab = None
if scratch is not None:
@@ -1491,6 +1546,427 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
act = g_tensor_cache.get(self.device, (self.num_experts_per_tok + 1, I), torch.half, "dec_shf_act"),
)
+ def _fq_grouped_ok(self, y: torch.Tensor) -> bool:
+ """Eligibility for the foreign-quant grouped decode path (Bolt latent
+ MoE: gateless relu2, IQ2_XXS routed experts, Q8_0 latent projs). Any
+ configuration this does not cover returns False and the caller falls
+ through to the established paths. BOLT_FQ_MOE_GROUPED=0 disables."""
+ if os.environ.get("BOLT_FQ_MOE_GROUPED", "1") == "0":
+ return False
+ if not hasattr(ext, "fq_moe_iq2xxs_grouped"):
+ return False
+ if self.gated:
+ return False
+ if y.dtype != torch.half or not y.is_contiguous():
+ return False
+ from .foreign_linear import ForeignLinear
+ if self.latent_in is None or self.latent_out is None:
+ return False
+ if not (isinstance(self.latent_in, ForeignLinear) and self.latent_in.format == "q8_0"):
+ return False
+ if not (isinstance(self.latent_out, ForeignLinear) and self.latent_out.format == "q8_0"):
+ return False
+ if len(self.ups) != self.num_experts or len(self.downs) != self.num_experts:
+ return False
+ for m in self.ups + self.downs:
+ if not (isinstance(m, ForeignLinear) and m.format == "iq2_xxs"):
+ return False
+ if m.packed is None or not m.packed.is_contiguous():
+ return False
+ if self.shared_experts is not None:
+ se = self.shared_experts
+ if len(getattr(se, "ups", [None])) != 1 or len(getattr(se, "downs", [None])) != 1:
+ return False
+ for m in se.ups + se.downs:
+ if not (isinstance(m, ForeignLinear) and m.format == "iq2_xxs"):
+ return False
+ if m.packed is None or not m.packed.is_contiguous():
+ return False
+ if self.router_pre_norm is not None or self.routed_pre_norm is not None:
+ return False
+ if self.routed_post_norm is not None or self.shared_gate is not None:
+ return False
+ if self.shared_experts_post_norm is not None:
+ return False
+ if self.alt_residual_channel or self.tp_reduce or self.tp_mode is not None:
+ return False
+ if self.routing_device is not None or self.cpu_split_first is not None:
+ return False
+ if self.cpu_offload:
+ return False
+ K = self.expert_size
+ I = self.intermediate_size
+ if K % 256 != 0 or I % 256 != 0 or K > 4096 or I > 4096:
+ return False
+ if self.ups[0].in_features != K or self.ups[0].out_features != I:
+ return False
+ if self.downs[0].in_features != I or self.downs[0].out_features != K:
+ return False
+ return True
+
+ def _forward_foreign_grouped(self, x, y, selected_experts, routing_weights,
+ params, out_dtype, eshape):
+ """Grouped foreign MoE for batch-1 latent decode. Returns the routed
+ sum projected back to the residual width (same value as the dense
+ per-expert torch path within fp16 tolerance), or None when ineligible.
+ Skips the dense path's argsort / bincount+tolist host sync /
+ index_select / index_add_ as well as its 2*topk launches: experts run
+ in one fq_moe_iq2xxs_grouped call (slot kernel + weighted fold)."""
+ if not self._fq_grouped_ok(y):
+ return None
+ S = self.num_experts_per_tok
+ if tuple(selected_experts.shape) != (1, S):
+ return None
+ sel = selected_experts.reshape(-1)
+ wts = routing_weights.reshape(-1)
+ if wts.dtype != torch.half:
+ return None
+ if not sel.is_contiguous():
+ sel = sel.contiguous()
+ if not wts.is_contiguous():
+ wts = wts.contiguous()
+ h = y.reshape(1, -1)
+ dev = h.device
+ K = h.shape[1]
+ # Expert pointer tables (weights are static: rebuild only when the
+ # allocations change).
+ tbl = getattr(self, "_fq_ptrs", None)
+ if tbl is None or tbl[0] != self.ups[0].packed.data_ptr() or \
+ tbl[1] != self.downs[0].packed.data_ptr() or tbl[4] != dev:
+ up_ptrs = torch.tensor([u.packed.data_ptr() for u in self.ups],
+ dtype=torch.int64, device=dev)
+ down_ptrs = torch.tensor([d.packed.data_ptr() for d in self.downs],
+ dtype=torch.int64, device=dev)
+ up_stride = (self.ups[0].in_features // 256) * 66
+ down_stride = (self.downs[0].in_features // 256) * 66
+ tbl = (self.ups[0].packed.data_ptr(), self.downs[0].packed.data_ptr(),
+ up_ptrs, down_ptrs, dev, up_stride, down_stride)
+ self._fq_ptrs = tbl
+ _, _, up_ptrs, down_ptrs, _, up_stride, down_stride = tbl
+ if getattr(self, "_fq_partial", None) is None or \
+ self._fq_partial.shape != (S, K) or self._fq_partial.device != dev:
+ self._fq_partial = torch.empty((S, K), dtype=torch.float, device=dev)
+ self._fq_routed = torch.empty((1, K), dtype=torch.float, device=dev)
+ ext.fq_moe_iq2xxs_grouped(h, sel, wts, up_ptrs, down_ptrs,
+ up_stride, down_stride,
+ self._fq_partial, self._fq_routed)
+ final_hidden_states = self.latent_out.forward(self._fq_routed, params)
+ if self.shared_experts is not None:
+ se_params = {**params, "moe_valu": True} if _MOE_VALU else params
+ se = self._forward_foreign_shared(x, se_params)
+ if se is None:
+ se = self.shared_experts.forward(x, se_params)
+ final_hidden_states = final_hidden_states + se.to(torch.float)
+ if out_dtype is not None:
+ final_hidden_states = final_hidden_states.to(out_dtype)
+ return final_hidden_states
+
+ def _fq_grouped_kq_ok(self, y: torch.Tensor) -> str | None:
+ """Eligibility for the KQ grouped decode path (MiniCPM SwiGLU MoE:
+ gated, ForeignLinear KQ/IQ4_XS routed experts, no latent). Returns the
+ format string or None. MCPM_FQ_MOE_GROUPED=0 disables."""
+ if os.environ.get("MCPM_FQ_MOE_GROUPED", "1") == "0":
+ return None
+ if not self.gated:
+ return None
+ if y.dtype != torch.half or not y.is_contiguous():
+ return None
+ from .foreign_linear import ForeignLinear
+ if self.latent_in is not None or self.latent_out is not None:
+ return None
+ if len(self.gates) != self.num_experts or len(self.ups) != self.num_experts \
+ or len(self.downs) != self.num_experts:
+ return None
+ fmt = None
+ for m in self.gates + self.ups + self.downs:
+ if not isinstance(m, ForeignLinear):
+ return None
+ if m.format not in ("q4_k", "q5_k", "q6_k", "iq4_xs"):
+ return None
+ if fmt is None:
+ fmt = m.format
+ elif m.format != fmt:
+ return None # mixed formats (Q4_K_M gate/up vs down) need separate dots
+ if m.packed is None or not m.packed.is_contiguous():
+ return None
+ if self.router_pre_norm is not None or self.routed_pre_norm is not None:
+ return None
+ if self.routed_post_norm is not None:
+ return None
+ if self.shared_experts_post_norm is not None:
+ return None
+ if self.alt_residual_channel or self.tp_reduce or self.tp_mode is not None:
+ return None
+ if self.routing_device is not None or self.cpu_split_first is not None:
+ return None
+ if self.cpu_offload:
+ return None
+ K = self.expert_size
+ I = self.intermediate_size
+ if K % 256 != 0 or I % 256 != 0:
+ return None
+ if self.gates[0].in_features != K or self.gates[0].out_features != I:
+ return None
+ if self.downs[0].in_features != I or self.downs[0].out_features != K:
+ return None
+ if self.activation_fn not in ("silu", None):
+ return None
+ return fmt
+
+ def _forward_foreign_grouped_kq(self, x, y, selected_experts, routing_weights,
+ params, out_dtype, eshape):
+ """Grouped KQ MoE for batch-1 SwiGLU decode. One fq_moe kernel runs
+ all selected experts (gate+up dots, torch-half SwiGLU, down dots,
+ weighted fold), replacing the per-expert torch loop (top-k launches
+ + python dispatch per layer). Returns routed+shared sum or None."""
+ fmt = self._fq_grouped_kq_ok(y)
+ if fmt is None:
+ return None
+ S = self.num_experts_per_tok
+ if tuple(selected_experts.shape) != (1, S):
+ return None
+ sel = selected_experts.reshape(-1)
+ wts = routing_weights.reshape(-1)
+ if wts.dtype != torch.half:
+ return None
+ if not sel.is_contiguous():
+ sel = sel.contiguous()
+ if not wts.is_contiguous():
+ wts = wts.contiguous()
+ h = y.reshape(1, -1)
+ dev = h.device
+ K = h.shape[1]
+ _BB = {"q4_k": 144, "q5_k": 176, "q6_k": 210, "iq4_xs": 136}
+ bb = _BB[fmt]
+ tbl = getattr(self, "_fq_kq_ptrs", None)
+ if tbl is None or tbl[0] != self.gates[0].packed.data_ptr() or tbl[4] != dev:
+ gate_ptrs = torch.tensor([m.packed.data_ptr() for m in self.gates],
+ dtype=torch.int64, device=dev)
+ up_ptrs = torch.tensor([m.packed.data_ptr() for m in self.ups],
+ dtype=torch.int64, device=dev)
+ down_ptrs = torch.tensor([m.packed.data_ptr() for m in self.downs],
+ dtype=torch.int64, device=dev)
+ tbl = (self.gates[0].packed.data_ptr(), gate_ptrs, up_ptrs, down_ptrs, dev)
+ self._fq_kq_ptrs = tbl
+ _, gate_ptrs, up_ptrs, down_ptrs, _ = tbl
+ I = self.intermediate_size
+ gate_stride = (K // 256) * bb
+ up_stride = gate_stride
+ down_stride = (I // 256) * bb
+ if getattr(self, "_fq_kq_partial", None) is None or \
+ self._fq_kq_partial.shape != (S, K) or self._fq_kq_partial.device != dev:
+ self._fq_kq_partial = torch.empty((S, K), dtype=torch.float, device=dev)
+ self._fq_kq_routed = torch.empty((1, K), dtype=torch.float, device=dev)
+ _FN = {"q4_k": "fq_moe_q4k_grouped_q8", "q5_k": "fq_moe_q5k_grouped_q8",
+ "q6_k": "fq_moe_q6k_grouped_q8", "iq4_xs": "fq_moe_iq4xs_grouped_q8"}
+ getattr(ext, _FN[fmt])(h, sel, wts, gate_ptrs, up_ptrs, down_ptrs,
+ gate_stride, up_stride, down_stride,
+ self._fq_kq_partial, self._fq_kq_routed)
+ final_hidden_states = self._fq_kq_routed
+ if self.shared_experts is not None:
+ se_params = {**params, "moe_valu": True} if _MOE_VALU else params
+ se = self.shared_experts.forward(x, se_params)
+ if self.shared_gate is not None:
+ ext.add_sigmoid_gate_proj(se, x, final_hidden_states,
+ self.shared_gate.inner.weight)
+ else:
+ final_hidden_states = final_hidden_states + se.to(torch.float)
+ if out_dtype is not None:
+ final_hidden_states = final_hidden_states.to(out_dtype)
+ return final_hidden_states
+
+ def _forward_foreign_shared(self, x, params):
+ """Fused dense shared-expert up+relu2 (fq_mlp.cu) + ForeignLinear
+ down for batch-1 decode. Bit-identical to the shared MLP torch path
+ (same up dot grid, torch-exact relu2 epilogue, same down dot), so it
+ only kills the torch relu/square launches, the intermediate u
+ allocation, and u's global round-trip. Any configuration this does
+ not cover returns None and the caller falls through to the torch
+ path. BOLT_FQ_MLP_SHARED=0 disables."""
+ if os.environ.get("BOLT_FQ_MLP_SHARED", "1") == "0":
+ return None
+ if not hasattr(ext, "fq_mlp_shared_iq2xxs"):
+ return None
+ se = self.shared_experts
+ if se is None or se.num_slices != 1:
+ return None
+ if se.activation_fn != "relu2" or se.interm_dtype == torch.float:
+ return None
+ from .foreign_linear import ForeignLinear
+ up, down = se.ups[0], se.downs[0]
+ if not (isinstance(up, ForeignLinear) and up.format == "iq2_xxs"):
+ return None
+ if not (isinstance(down, ForeignLinear) and down.format == "iq2_xxs"):
+ return None
+ if up.packed is None or down.packed is None:
+ return None
+ K, I = up.in_features, up.out_features
+ if down.in_features != I or I != se.intermediate_size:
+ return None
+ if x.shape[-1] != K or x.numel() != K:
+ return None
+ xr = x.reshape(1, K)
+ if xr.dtype != torch.half or not xr.is_contiguous():
+ return None
+ dev = xr.device
+ h = getattr(self, "_fq_shared_h", None)
+ if h is None or tuple(h.shape) != (1, I) or h.device != dev:
+ h = torch.empty((1, I), dtype=torch.half, device=dev)
+ self._fq_shared_h = h
+ ext.fq_mlp_shared_iq2xxs(xr, up.packed.reshape(I, -1, 66), h)
+ return down.forward(h, params)
+
+ def _forward_foreign_prefill_grouped(self, x, y, selected_experts, routing_weights,
+ params, out_dtype, eshape):
+ """MiniCPM IQ4_XS prefill MoE (rows >= MCPM_FQ_PF_GROUPED_MIN): two fused
+ Triton grouped GEMMs over expert-sorted rows (gate+up+SwiGLU, then
+ down x routing weight) that decode the IQ4_XS weights in the K loop
+ (fq_moe_prefill.py), tile map built on device (no host sync, ~15
+ launches per layer instead of thousands). Same fp16-rounded weights
+ and fp32 accumulation as the per-expert path. Returns the block output
+ or None. MCPM_FQ_PF_GROUPED=0 disables."""
+ if os.environ.get("MCPM_FQ_PF_GROUPED", "1") == "0":
+ return None
+ R = y.shape[0]
+ if R < int(os.environ.get("MCPM_FQ_PF_GROUPED_MIN", "256")):
+ return None
+ if self._fq_grouped_kq_ok(y) != "iq4_xs" or self.act_limit or self.activation_fn not in ("silu", None):
+ return None
+ if (self.num_local_experts or self.num_experts) != self.num_experts:
+ return None
+ top_k = self.num_experts_per_tok
+ if tuple(selected_experts.shape) != (R, top_k) or selected_experts.dtype != torch.long:
+ return None
+ from .fq_moe_prefill import build_tiles, gmm_iq4, perm_cols
+ E = self.num_experts
+ dev = y.device
+ K = y.shape[1]
+ I = self.intermediate_size
+ wts = routing_weights
+ if wts.dtype != torch.half:
+ wts = wts.to(torch.half)
+ flat_expert = selected_experts.reshape(-1)
+ order = flat_expert.argsort(stable=True)
+ token_sorted = order // top_k
+ weight_sorted = wts.reshape(-1)[order]
+ counts = _scatter_expert_count(flat_expert, E + 1)[:E]
+ M = R * top_k
+ tile_e, tile_r0, offs = build_tiles(counts, M, 64)
+ tbl = getattr(self, "_fq_pf_ptrs", None)
+ if tbl is None or tbl[0] != self.gates[0].packed.data_ptr() or tbl[3] != dev:
+ gu = torch.tensor([m.packed.data_ptr() for m in self.gates + self.ups], dtype=torch.int64, device=dev)
+ dn_p = torch.tensor([m.packed.data_ptr() for m in self.downs], dtype=torch.int64, device=dev)
+ tbl = (self.gates[0].packed.data_ptr(), gu, dn_p, dev)
+ self._fq_pf_ptrs = tbl
+ _, gu_ptrs, dn_ptrs, _ = tbl
+ xs = perm_cols(y.index_select(0, token_sorted))
+ a = torch.empty((M, I), dtype=torch.half, device=dev)
+ gmm_iq4(xs, gu_ptrs, a, tile_e, tile_r0, offs, I, K, E, swiglu=True)
+ dn = torch.empty((M, K), dtype=torch.half, device=dev)
+ gmm_iq4(a, dn_ptrs, dn, tile_e, tile_r0, offs, K, I, E, wrow=weight_sorted)
+ inv = torch.empty_like(order)
+ inv[order] = torch.arange(order.numel(), device=dev) # row of each (token, k) pick in the sorted layout
+ final_hidden_states = dn.index_select(0, inv).view(R, top_k, K).float().sum(1)
+ final_hidden_states = final_hidden_states.reshape(eshape)
+ if self.shared_experts:
+ y_se = self.shared_experts.forward(x, {**params, "moe_valu": True} if _MOE_VALU else params)
+ if self.shared_gate:
+ ext.add_sigmoid_gate(y_se, self.shared_gate.forward(x, params), final_hidden_states)
+ else:
+ final_hidden_states += y_se
+ if out_dtype is not None:
+ final_hidden_states = final_hidden_states.to(out_dtype)
+ return final_hidden_states
+
+ def _forward_foreign_prefill(self, x, y, selected_experts, routing_weights,
+ params, out_dtype, eshape):
+ """Lean foreign prefill MoE (rows > 1): the dense per-expert torch
+ path (full-fp16 dequant + cublas mm per expert) WITHOUT the EXL3
+ tier machinery around it (fused/recon tier planning, numpy slot
+ tables, prefill-shaped scratch + gather, extra syncs). Same op
+ sequence per expert (sort, index_select, up, act, down, weighted
+ index_add_), hence bitwise-identical to the stock dense path for
+ foreign configs; only the scaffolding is skipped. Returns the
+ full block output (routed + shared + latent_out, like the tail
+ below), or None when ineligible. BOLT_FQ_PF=0 disables."""
+ if os.environ.get("BOLT_FQ_PF", "1") == "0":
+ return None
+ if not self._fq_grouped_ok(y):
+ return None
+ if (self.num_local_experts or self.num_experts) != self.num_experts:
+ return None
+ R = y.shape[0]
+ if R <= 1:
+ return None
+ if tuple(selected_experts.shape)[0] != R:
+ return None
+ num_tokens, top_k = selected_experts.shape
+ if top_k != self.num_experts_per_tok:
+ return None
+ if selected_experts.dtype != torch.long:
+ return None
+ if not selected_experts.is_contiguous():
+ selected_experts = selected_experts.contiguous()
+ wts = routing_weights
+ if wts.dtype != torch.half:
+ wts = wts.to(torch.half)
+ if not wts.is_contiguous():
+ wts = wts.contiguous()
+ if not x.is_contiguous() or x.dtype != torch.half:
+ return None
+ num_ex = self.num_experts
+ E = num_ex
+ dev = y.device
+ K = y.shape[1]
+ flat_expert = selected_experts.reshape(-1)
+ flat_weight = wts.reshape(-1)
+ flat_token = buffered_interleaved_arange(num_tokens, top_k, device=dev)
+ order = flat_expert.argsort(stable=True)
+ token_sorted = flat_token[order]
+ weight_sorted = flat_weight[order]
+ expert_count = _scatter_expert_count(flat_expert, E + 1)
+ expert_count_list = expert_count.tolist()
+ final_hidden_states = torch.zeros((R, K), dtype=torch.float, device=dev)
+ # Single sorted gather; per-expert narrow views (no per-expert copy).
+ # Same values through the same kernels -> bitwise-identical
+ # (gated A/B: pf_1g.sh). BOLT_FQ_PF1G=0 restores per-expert
+ # index_select.
+ one_gather = os.environ.get("BOLT_FQ_PF1G", "1") != "0"
+ xs_all = y.index_select(0, token_sorted) if one_gather else None
+ start = 0
+ for expert_idx in range(num_ex):
+ count = expert_count_list[expert_idx]
+ end = start + count
+ if count > 0:
+ top_x = token_sorted[start:end]
+ w = weight_sorted[start:end].unsqueeze(1)
+ if one_gather:
+ current_state = xs_all.narrow(0, start, count)
+ else:
+ current_state = y.index_select(0, top_x)
+ u = self.ups[expert_idx].forward(current_state, params)
+ if self.gated:
+ g = self.gates[expert_idx].forward(current_state, params)
+ a = u if self.interm_dtype == torch.half else torch.empty_like(u, dtype=torch.half)
+ self.activation_fn_call(g, u, a, self.act_limit)
+ else:
+ a = self.gateless_act(u)
+ if a.dtype != torch.half:
+ a = a.half()
+ current_state = self.downs[expert_idx].forward(a, params)
+ current_state.mul_(w)
+ final_hidden_states.index_add_(0, top_x, current_state)
+ start = end
+ final_hidden_states = final_hidden_states.reshape(eshape)
+ if self.latent_out is not None:
+ final_hidden_states = self.latent_out.forward(final_hidden_states.to(torch.half), params)
+ if self.shared_experts:
+ y_se = self.shared_experts.forward(x, {**params, "moe_valu": True} if _MOE_VALU else params)
+ final_hidden_states += y_se
+ if out_dtype is not None:
+ final_hidden_states = final_hidden_states.to(out_dtype)
+ return final_hidden_states
+
def forward(
self,
x: torch.Tensor,
@@ -1498,6 +1974,11 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
out_dtype: torch.dtype | None = None
) -> torch.Tensor:
+ if _ROW_CHUNK_MAX and MAX_BSZN < x.numel() // x.shape[-1] <= \
+ (min(_ROW_CHUNK_MAX, _FUSED_3INST_MIN) if self.support_fused else _ROW_CHUNK_MAX) and self._row_chunk_ok() and \
+ not params.get("autosplit_measure"):
+ return self._forward_row_chunks(x, params, out_dtype)
+
if self.alt_residual_channel:
y = params["residual"].view(-1, self.hidden_size)
else:
@@ -1557,6 +2038,39 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
if self.latent_in is not None:
y = self.latent_in.forward(y, params)
+ # Foreign-quant grouped decode (Bolt latent MoE): one kernel runs all
+ # selected experts (see _forward_foreign_grouped). Strict eligibility
+ # inside; falls through to the paths below otherwise.
+ # KQ grouped decode (MiniCPM SwiGLU MoE): same idea via the KQ dots
+ # (see _forward_foreign_grouped_kq). Tried first (Bolt returns None
+ # without latent projs anyway).
+ if bsz == 1 and not params.get("activate_all_experts") and \
+ not params.get("reconstruct") and not params.get("autosplit_measure"):
+ grouped = self._forward_foreign_grouped_kq(
+ x, y, selected_experts, routing_weights, params, out_dtype, eshape)
+ if grouped is not None:
+ return grouped
+ grouped = self._forward_foreign_grouped(
+ x, y, selected_experts, routing_weights, params, out_dtype, eshape)
+ if grouped is not None:
+ return grouped
+
+ # Lean foreign prefill (Bolt latent MoE, rows > 1): same values as
+ # the dense per-expert torch path, minus the EXL3 tier scaffolding
+ # (see _forward_foreign_prefill). Strict eligibility inside; falls
+ # through otherwise. Skipped for DFlash verify batches (bit-exact
+ # union path owns those).
+ if bsz > 1 and not params.get("activate_all_experts") and \
+ not params.get("reconstruct") and not params.get("autosplit_measure") and \
+ not params.get("dflash_verify"):
+ pf = self._forward_foreign_prefill_grouped(
+ x, y, selected_experts, routing_weights, params, out_dtype, eshape)
+ if pf is None:
+ pf = self._forward_foreign_prefill(
+ x, y, selected_experts, routing_weights, params, out_dtype, eshape)
+ if pf is not None:
+ return pf
+
# Broadcast routing indices and weights
if self.routing_device is not None:
params["backend"].broadcast(selected_experts, src_device = self.routing_device)
@@ -1992,18 +2506,24 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
token_sorted = flat_token[order]
weight_sorted = flat_weight[order]
- # Count how many assignments per expert. With few enough total assignments no
- # expert can exceed the fused kernel's row capacity, so the readback (a CPU sync
- # per layer, ~33% idle at MTP verify shapes) is skipped and everything is fused
+ # Count how many assignments per expert. With few enough tokens no expert can exceed
+ # the fused kernel's row capacity (an expert gets at most one row per token), so the
+ # readback (a CPU sync per layer, ~33% idle at MTP verify shapes) is skipped and
+ # everything is fused
if _moe_sync_free_count():
expert_count = _scatter_expert_count(flat_expert_local, E + 1)
else:
expert_count = torch.bincount(flat_expert_local, minlength = E + 1)
- if self.fused_mode_buffers is not None and num_tokens * top_k <= self.fused_rows:
+ if self.fused_mode_buffers is not None and \
+ (num_tokens if SYNC_FREE_TOKENS else num_tokens * top_k) <= self.fused_rows:
expert_count_list = None
else:
expert_count_list = expert_count.tolist()
+ moeg = expert_count_list is not None and FUSED_DET and self._moeg_ok()
+ fused_cap = max(self.fused_rows, MOEG_ROWS) if moeg else self.fused_rows
+ self._fused_cap = fused_cap
+
# Tier plan: fused kernel for experts up to self.fused_rows rows, batched
# reconstruct groups above that up to the tile cap, per-expert reconstruct beyond
recon = None
@@ -2014,8 +2534,8 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
else:
fused_total = 0
if self.fused_mode_buffers is not None:
- min_rows = self.fused_rows
- fused_total = sum(c for c in expert_count_list[:num_ex] if 0 < c <= self.fused_rows)
+ min_rows = fused_cap
+ fused_total = sum(c for c in expert_count_list[:num_ex] if 0 < c <= fused_cap)
recon = self._batch_recon_layer(y)
if recon is not None:
lim = max(min_rows, TEMP_ROWS_GRAPH)
@@ -2034,6 +2554,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
# call. Its traffic (written once by the GEMMs, read once by the gather) matches
# what the atomic index_add_ path moved
scratch = tables = inv_order = None
+ n_grouped = n_slots = 0
if FUSED_DET and (fused_total or groups):
A = flat_expert_local.shape[0]
inv_order = torch.empty_like(order).scatter_(
@@ -2051,18 +2572,25 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
base = np.zeros(E1, dtype = np.int64)
kind = np.zeros(E1, dtype = np.int64)
starts_np = np.cumsum([0] + expert_count_list[:-1]).astype(np.int64)
+ gbase = np.zeros(E1, dtype = np.int64)
n_slots = 0
+ n_grouped = 0
if self.fused_mode_buffers is not None:
for e in range(num_ex):
c = expert_count_list[e]
- if 0 < c <= self.fused_rows:
- base[e] = n_slots; kind[e] = 1; n_slots += c
+ if 0 < c <= fused_cap:
+ if moeg and c >= MOEG_LO:
+ # Grouped tier: compact work rows, combined per token by the tier itself (kind 0 for the gather)
+ gbase[e] = n_grouped; n_grouped += c
+ else:
+ base[e] = n_slots; kind[e] = 1; n_slots += c
+ self._fused_slots = n_slots
for grp in groups:
cmax = max(expert_count_list[e] for e in grp)
for b, e in enumerate(grp):
base[e] = n_slots + b * cmax; kind[e] = 2
n_slots += len(grp) * cmax
- tables = torch.from_numpy(np.stack([base, starts_np, kind])).to(y.device, non_blocking = True)
+ tables = torch.from_numpy(np.stack([base, starts_np, kind, gbase])).to(y.device, non_blocking = True)
scratch = torch.empty((max(n_slots, 1), y.shape[1]), dtype = torch.float, device = y.device)
def run_fused(num_active, count_lo = 1, count_hi = self.fused_rows, m_tile = 16):
@@ -2104,19 +2632,57 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
count_lo, count_hi, m_tile
)
+ def run_grouped(count_lo, count_hi):
+ ext.exl3_moe_grouped(
+ y,
+ expert_count,
+ tables[1],
+ token_sorted,
+ weight_sorted,
+ self.activation_fn_idx,
+ self.multi_gate.K,
+ self.multi_up.K,
+ self.multi_down.K,
+ self.multi_gate.ptrs_trellis,
+ self.multi_gate.ptrs_suh,
+ self.multi_gate.ptrs_svh,
+ self.multi_up.ptrs_trellis,
+ self.multi_up.ptrs_suh,
+ self.multi_up.ptrs_svh,
+ self.multi_down.ptrs_trellis,
+ self.multi_down.ptrs_suh,
+ self.multi_down.ptrs_svh,
+ self.act_limit,
+ final_hidden_states,
+ flat_expert_local,
+ inv_order,
+ tables[3],
+ n_grouped,
+ count_lo, count_hi, 64,
+ self.fused_mode_buffers.temp_intermediate_g.shape[2]
+ )
+
# num_active -1 = unknown (all fused), kernel launches at max concurrency
if self.fused_mode_buffers is not None:
if expert_count_list is None:
run_fused(-1)
else:
- counts = [c for c in expert_count_list[:num_ex] if 0 < c <= self.fused_rows]
+ counts = [c for c in expert_count_list[:num_ex] if 0 < c <= fused_cap]
t1 = sum(1 for c in counts if MTILE_T1 < c <= MTILE_T2)
t2 = sum(1 for c in counts if c > MTILE_T2)
if self.mtile_ok and (t1 or t2):
# One launch per row tile over its expert range, largest first
t0 = len(counts) - t1 - t2
- if t2:
- run_fused(t2, MTILE_T2 + 1, self.fused_rows, 64)
+ if t2 and moeg and scratch is not None:
+ # Grouped GEMM tier for the experts above MOEG_LO rows, the persistent kernel keeps the rest
+ tg = sum(1 for c in counts if c >= MOEG_LO)
+ if tg:
+ run_grouped(MOEG_LO, max(counts))
+ tm = t2 - tg
+ if tm:
+ run_fused(tm, MTILE_T2 + 1, MOEG_LO - 1, 64)
+ elif t2:
+ run_fused(t2, MTILE_T2 + 1, fused_cap, 64)
if t1:
run_fused(t1, MTILE_T1 + 1, MTILE_T2, 32)
if t0:
@@ -2132,7 +2698,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
scratch, tables)
# One fixed-order gather over every slot
- if scratch is not None:
+ if scratch is not None and n_slots:
ext.exl3_moe_gather(final_hidden_states, scratch, flat_expert_local, inv_order,
tables[1, :num_ex], tables[0, :num_ex], tables[2, :num_ex], weight_sorted)
@@ -2143,6 +2709,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
start = 0
# expert_count_list None: everything already handled by the fused kernel above
+ rwh_w = self._rwh_true_weights(z) if (_RWH and "capture" in params and params.get("activate_all_experts")) else None
for expert_idx in range(num_ex if expert_count_list is not None else 0):
count = expert_count_list[expert_idx]
end = start + count
@@ -2155,6 +2722,10 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
f"({count} rows on expert {expert_idx}); use the fused/grouped/WMMA paths")
top_x = token_sorted[start:end]
w = weight_sorted[start:end].unsqueeze(1)
+ if rwh_w is not None:
+ w_e = rwh_w[top_x, expert_idx]
+ sel = (w_e > 0).nonzero().squeeze(1)
+ params["_cap_rw"] = (sel, w_e[sel])
current_state = y.index_select(0, top_x)
@@ -2204,6 +2775,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
current_state = mlp(expert_idx, current_state)
+ params.pop("_cap_rw", None)
current_state.mul_(w)
final_hidden_states.index_add_(0, top_x, current_state)
start = end
@@ -2294,6 +2866,41 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
return final_hidden_states
+ def _rwh_true_weights(self, z: torch.Tensor) -> torch.Tensor:
+ """[rows, E] float: the model's actual top-k routing weights (sigmoid scores renormalised over the picks, no
+ scaling), zero for unselected experts. Used to weight the per-expert calibration Hessians (EXL3_RWH)."""
+ cfg = self.routing_cfg
+ zz = z.view(-1, z.shape[-1])
+ logits = torch.matmul(zz, cfg.gate_tensor)[:, :self.num_experts].float()
+ scores = torch.sigmoid(logits)
+ top = torch.topk(scores, self.num_experts_per_tok, dim = -1)
+ wv = top.values / (top.values.sum(dim = -1, keepdim = True) + 1e-20)
+ out = torch.zeros_like(scores)
+ out.scatter_(1, top.indices, wv)
+ return out
+
+
+ def _row_chunk_ok(self) -> bool:
+ # bszN decode kernels exist (BC, CUDA) and no fused MoE kernel would take the rows (or only the 3INST one, which
+ # loses below _FUSED_3INST_MIN rows); ROCm has no BC object
+ return (self.bc is not None and (not self.support_fused or self.fused_3inst) and self.support_bc_bszn and not self.alt_residual_channel and
+ self.cpu_split_first is None and not self.cpu_offload and self.routing_device is None and self.tp_mode is None)
+
+
+ def _forward_row_chunks(self, x: torch.Tensor, params: dict, out_dtype: torch.dtype | None) -> torch.Tensor:
+ # Each slice gets its own params: no fused residual add (the caller adds y) and its rows of a pre-computed routing
+ y = x.reshape(-1, x.shape[-1])
+ routed = params.pop("dec_routed", None)
+ outs = []
+ for a in range(0, y.shape[0], MAX_BSZN):
+ sub = {k: v for k, v in params.items() if k != "mlp_residual_out"}
+ if routed is not None:
+ sub["dec_routed"] = (routed[0][a:a + MAX_BSZN], routed[1][a:a + MAX_BSZN])
+ o = self.forward(y[a:a + MAX_BSZN].unsqueeze(0), sub, out_dtype)
+ outs.append(o.reshape(-1, o.shape[-1]).clone()) # the bszN output buffer is reused by the next slice
+ return torch.cat(outs).view(x.shape[:-1] + (outs[0].shape[-1],))
+
+
def dec_norm_route(self, norm, xa: torch.Tensor, r: torch.Tensor, params: dict, rows: int = 1):
"""Batch-1 decode: MLP pre-norm (r += xa, y = norm(r)) fused with the router in one
exl3_dec_router_norm launch. Returns y (fp16), routing left in params["dec_routed"]; None
diff --git a/exllamav3/modules/foreign_linear.py b/exllamav3/modules/foreign_linear.py
new file mode 100644
index 0000000..c4ec2f2
--- /dev/null
+++ b/exllamav3/modules/foreign_linear.py
@@ -0,0 +1,301 @@
+"""Linear layer over third-party quantized weights, run as shipped (no requant).
+
+A ForeignLinear holds the raw checkpoint payload (ggml Q8_0 / IQ2_XXS blocks
+or ModelOpt NVFP4 nibbles + scales) on the device and dequantizes on the fly:
+rows <= 16 through the fused fq_gemm_* kernels, wider batches through
+fq_dequant_* + torch.matmul. Output matches dequant + matmul within fp16
+tolerance (the fused path only reorders the fp32 accumulation).
+
+Plugs into the existing dispatch: quant_type is "foreign" (never "exl3"), so
+BlockSparseMLP takes the dense per-expert torch path and calls
+forward(xc, params) per expert group; MLP / Mamba2 / Attention accept
+prebuilt modules the same way. inner is self with bias None so the
+quantized-path probes (l.inner.bias, l.inner.trellis, ...) stay dormant.
+
+BOLT_FQ_FUSED=0 forces the unfused dequant+matmul path (A/B).
+"""
+from __future__ import annotations
+
+import os
+from typing import Optional
+
+import torch
+
+from .module import Module
+from ..ext import exllamav3_ext as ext
+
+FUSED_ROWS_MAX = 16
+_FUSED = os.environ.get("BOLT_FQ_FUSED", "1") != "0"
+# Cooperative GEMV (fq_gemv.cu: shared-memory x staging, lanes split K):
+# replaces fq_gemm_* wherever present. Any half/float in+out (the old path
+# needed half in and always wrote half, so float-out layers like latent_out
+# and the mamba projections fell back to full dequant+matmul).
+# BOLT_FQ_GEMV=0 restores the fq_gemm_* path for A/B.
+_GEMV = os.environ.get("BOLT_FQ_GEMV", "1") != "0"
+# Row chunk of the unfused dequant+matmul path (transient fp16 bound).
+_UNFUSED_ROWS = int(os.environ.get("BOLT_FQ_UNFUSED_ROWS", "8192"))
+# NVFP4 E2M1 pair-table dot (fq_gemv.cuh: one shared float2 load per pair
+# instead of two replicated-e2m1 loads + nibble math). BOLT_FQ_PAIR=0
+# restores the direct dot for A/B.
+_PAIR = os.environ.get("BOLT_FQ_PAIR", "1") != "0"
+
+_FORMATS = ("q8_0", "iq2_xxs", "nvfp4", "q4_k", "q5_k", "q6_k", "iq4_xs")
+# GGUF K-quant formats: decode (rows < 16) via the q8_1-
+# activation row kernels; prefill (rows >= 16) via the unfused fp16 dequant
+# + cuBLAS GEMM path, one GEMM per call -- i.e. one GEMM per
+# expert token-group in the dense MoE prefill path. MCPM_FQ_KQ_GEMM=0 forces
+# the q8 row kernels for every width (A/B).
+_KQ_FORMATS = ("q4_k", "q5_k", "q6_k", "iq4_xs")
+_KQ_BLOCK_BYTES = {"q4_k": 144, "q5_k": 176, "q6_k": 210, "iq4_xs": 136}
+_KQ_GEMM_ROWS = 16
+_KQ_GEMM = os.environ.get("MCPM_FQ_KQ_GEMM", "1") != "0"
+
+# Reusable fp16 dequant scratch, one buffer per device: the KQ prefill GEMM
+# path dequantizes every weight N-chunk on every forward, so a persistent
+# buffer avoids an allocator round-trip per chunk. Views handed out alias
+# the buffer: consume (matmul) before the next _dequant_rows call (the only
+# callers do exactly that).
+_DQ_SCRATCH: dict = {}
+
+
+def _dq_fp16(dev: torch.device, rows: int, cols: int) -> torch.Tensor:
+ key = str(dev)
+ t = _DQ_SCRATCH.get(key)
+ if t is None or t.numel() < rows * cols:
+ t = torch.empty((rows * cols,), dtype=torch.float16, device=dev)
+ _DQ_SCRATCH[key] = t
+ return t[:rows * cols].view(rows, cols)
+
+
+class ForeignLinear(Module):
+
+ def __init__(
+ self,
+ config,
+ key: str,
+ in_features: int,
+ out_features: int,
+ format: str,
+ qmap: str | None = None,
+ out_dtype: torch.dtype | None = None,
+ post_scale: float = 1.0,
+ softcap: float = 0.0,
+ ):
+ super().__init__(config, key, qmap)
+ assert format in _FORMATS, f"unknown foreign format {format}"
+ self.format = format
+ self.in_features = in_features
+ self.in_features_unpadded = in_features
+ self.out_features = out_features
+ self.out_features_unpadded = out_features
+ self.full_in_features = in_features
+ self.full_out_features = out_features
+ self.first_in_feature = 0
+ self.first_out_feature = 0
+ self.trim_padded_out = False
+ self.allow_input_padding = False
+ self.transposed_load = False
+ self.out_dtype = out_dtype
+ self.pre_scale = 1.0
+ self.post_scale = post_scale
+ self.softcap = softcap
+ self.quant_type = "foreign"
+ # The BlockSparseMLP quantized-path probes (inner.bias / inner.trellis /
+ # inner.bc / ...) only run when is_quantized, which needs quant_type ==
+ # "exl3" on every expert; still, expose the attributes they would read.
+ self.inner = self
+ self.bias = None
+ self.bc = None
+ self.packed = None
+ self.scales = None
+ self.global_scale = None
+
+ def can_defer_load(self):
+ # Eager load: raw U8 payloads go straight to the device, no EXL3
+ # deferred arena.
+ return False
+
+ def optimizer_targets(self):
+ return [self.key]
+
+ def weights_numel(self):
+ return self.in_features * self.out_features
+
+ def get_tensors(self):
+ if self.packed is None:
+ return {}
+ d = {self.key + ".weight": self.packed}
+ if self.scales is not None:
+ d[self.key + ".weight_scale"] = self.scales
+ return d
+
+ def load(self, device: torch.device, **kwargs):
+ self.device = device
+ stc = self.config.stc
+ if self.format in ("q8_0", "iq2_xxs") or self.format in _KQ_FORMATS:
+ # Single raw payload (KQ GGUF bytes / Q8_0 / IQ2_XXS blocks).
+ self.packed = stc.get_tensor(self.key + ".weight", device, no_defer=True)
+ assert self.packed.dtype == torch.uint8, f"{self.key}: expected U8 payload, got {self.packed.dtype}"
+ else:
+ self.packed = stc.get_tensor(self.key + ".weight", device, no_defer=True)
+ scales = stc.get_tensor(self.key + ".weight_scale", device, no_defer=True)
+ # E4M3 scales arrive as fp8 (stc preserves stored dtypes); the
+ # kernels want the raw bytes.
+ self.scales = scales.view(torch.uint8) if scales.dtype != torch.uint8 else scales
+ g = stc.get_tensor(self.key + ".weight_scale_2", device, no_defer=True)
+ self.global_scale = float(g.float().item())
+ assert self.packed.dtype == torch.uint8 and self.scales.dtype == torch.uint8
+
+ def unload(self):
+ self.packed = None
+ self.scales = None
+ self.global_scale = None
+ self.device = None
+
+ def _dequant_weight(self) -> torch.Tensor:
+ """Full fp16 weight [N, K] (unfused path transient; freed by caller)."""
+ return self._dequant_rows(0, self.out_features)
+
+ def _dequant_rows(self, first: int, count: int) -> torch.Tensor:
+ """fp16 weight slice [count, K] for output rows [first, first+count)."""
+ N = self.out_features
+ assert 0 <= first and first + count <= N
+ dev = self.packed.device
+ if self.format in _KQ_FORMATS:
+ Kb = self.in_features // 256
+ bb = _KQ_BLOCK_BYTES[self.format]
+ assert self.packed.shape[1] == Kb * bb, \
+ f"{self.key}: packed width {self.packed.shape[1]} != K={self.in_features} ({bb}B)"
+ out = _dq_fp16(dev, count, self.in_features)
+ getattr(ext, f"fq_dequant_{self.format}")(
+ self.packed[first:first + count].contiguous(), out)
+ return out
+ if self.format == "q8_0":
+ Kb = self.in_features // 32
+ out = torch.empty((count, self.in_features), dtype=torch.float16, device=dev)
+ ext.fq_dequant_q8_0(self.packed.reshape(N, Kb, 34)[first:first + count].contiguous(), out)
+ elif self.format == "iq2_xxs":
+ Kb = self.in_features // 256
+ out = torch.empty((count, self.in_features), dtype=torch.float16, device=dev)
+ ext.fq_dequant_iq2_xxs(self.packed.reshape(N, Kb, 66)[first:first + count].contiguous(), out)
+ else:
+ K = self.in_features
+ out = torch.empty((count, K), dtype=torch.float16, device=dev)
+ ext.fq_dequant_nvfp4(self.packed.reshape(N, K // 2)[first:first + count].contiguous(),
+ self.scales.reshape(N, K // 16)[first:first + count].contiguous(),
+ self.global_scale, out)
+ return out
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ params: dict,
+ out_dtype: torch.dtype | None = None,
+ ) -> torch.Tensor:
+ shape = x.shape
+ K = self.in_features
+ assert shape[-1] == K, f"{self.key}: width {shape[-1]} != {K}"
+ flat = x.reshape(-1, K)
+ R = flat.shape[0]
+ dtype = out_dtype or self.out_dtype or torch.half
+ dev = self.packed.device
+ if flat.device != dev:
+ flat = flat.to(dev)
+ if not flat.is_contiguous():
+ flat = flat.contiguous()
+ out: Optional[torch.Tensor] = None
+ if self.format in _KQ_FORMATS:
+ # KQ path: quantize once to the cached q8 scratch, one
+ # row-per-block launch. Decode widths (R < 16) always run here;
+ # prefill widths (R >= 16) use the unfused fp16 GEMM below (one
+ # GEMM per call = one GEMM per expert token-group in MoE).
+ # Rows run in <=2048 chunks to bound the (R, N) output + q8 scratch transient
+ # (full-R prefill otherwise OOMs past ~12K).
+ assert flat.is_contiguous() and flat.dtype in (torch.half, torch.float)
+ N = self.out_features
+ bb = _KQ_BLOCK_BYTES[self.format]
+ assert self.packed.shape[1] == (K // 256) * bb, \
+ f"{self.key}: packed width {self.packed.shape[1]} != K={K} ({bb}B)"
+ if _KQ_GEMM and R >= _KQ_GEMM_ROWS:
+ xuse = flat.half() if flat.dtype != torch.half else flat
+ out = torch.empty((R, N), dtype=dtype, device=dev)
+ _RCH = 2048
+ for _s in range(0, R, _RCH):
+ _e = min(_s + _RCH, R)
+ _xs = xuse[_s:_e]
+ if N <= _UNFUSED_ROWS:
+ w = self._dequant_rows(0, N)
+ _m = torch.matmul(_xs, w.t())
+ out[_s:_e] = _m if _m.dtype == dtype else _m.to(dtype)
+ else:
+ for a in range(0, N, _UNFUSED_ROWS):
+ c = min(_UNFUSED_ROWS, N - a)
+ w = self._dequant_rows(a, c)
+ _m = torch.matmul(_xs, w.t())
+ _o = _m if _m.dtype == dtype else _m.to(dtype)
+ out[_s:_e, a:a + c] = _o
+ else:
+ out = torch.empty((R, N), dtype=dtype, device=dev)
+ dev_idx = dev.index if dev.index is not None else torch.cuda.current_device()
+ ext_fn = getattr(ext, f"fq_gemv_{self.format}_q8")
+ _CH = 2048
+ for _s in range(0, R, _CH):
+ _e = min(_s + _CH, R)
+ _fl = flat[_s:_e]
+ qb = ext.fq_q8_scratch(dev_idx, _e - _s, K)
+ ext.fq_quant_q8_1_rows(_fl.half() if _fl.dtype != torch.half else _fl, qb)
+ ext_fn(qb, self.packed, out[_s:_e])
+ elif (
+ _FUSED and R >= 1 and R <= FUSED_ROWS_MAX and flat.is_contiguous()
+ and flat.dtype in (torch.half, torch.float)
+ and hasattr(ext, "fq_gemv_q8_0")
+ and _GEMV
+ ):
+ N = self.out_features
+ out = torch.empty((R, N), dtype=dtype, device=dev)
+ if self.format == "q8_0":
+ ext.fq_gemv_q8_0(flat, self.packed.reshape(N, -1, 34), out)
+ elif self.format == "iq2_xxs":
+ ext.fq_gemv_iq2_xxs(flat, self.packed.reshape(N, -1, 66), out)
+ else:
+ ext.fq_gemv_nvfp4(flat, self.packed.reshape(N, K // 2),
+ self.scales.reshape(N, K // 16), self.global_scale, out, _PAIR)
+ elif (
+ _FUSED and R >= 1 and R <= FUSED_ROWS_MAX and flat.dtype == torch.half and flat.is_contiguous()
+ and hasattr(ext, "fq_gemm_q8_0")
+ ):
+ N = self.out_features
+ out = torch.empty((R, N), dtype=torch.float16, device=dev)
+ if self.format == "q8_0":
+ ext.fq_gemm_q8_0(flat, self.packed.reshape(N, -1, 34), out)
+ elif self.format == "iq2_xxs":
+ ext.fq_gemm_iq2_xxs(flat, self.packed.reshape(N, -1, 66), out)
+ else:
+ ext.fq_gemm_nvfp4(flat, self.packed.reshape(N, K // 2),
+ self.scales.reshape(N, K // 16), self.global_scale, out)
+ if out.dtype != dtype:
+ out = out.to(dtype)
+ else:
+ # Unfused: dequant in row chunks (bounds the transient fp16) +
+ # torch matmul. Single-chunk fast path: direct mm output (same
+ # values bitwise, skips the empty + slice-assign copy traffic).
+ N = self.out_features
+ xuse = flat.half() if flat.dtype != torch.half else flat
+ if N <= _UNFUSED_ROWS:
+ w = self._dequant_rows(0, N)
+ mmout = torch.matmul(xuse, w.t())
+ out = mmout if mmout.dtype == dtype else mmout.to(dtype)
+ del w
+ else:
+ out = torch.empty((R, N), dtype=dtype, device=dev)
+ for a in range(0, N, _UNFUSED_ROWS):
+ w = self._dequant_rows(a, min(_UNFUSED_ROWS, N - a))
+ mmout = torch.matmul(xuse, w.t())
+ out[:, a:a + w.shape[0]] = mmout if mmout.dtype == dtype else mmout.to(dtype)
+ del w
+ out = out.view(*shape[:-1], self.out_features)
+ if self.post_scale != 1.0:
+ out = out * self.post_scale
+ if self.softcap != 0.0:
+ ext.softcap(out, out, self.softcap)
+ return out
diff --git a/exllamav3/modules/fq_moe_prefill.py b/exllamav3/modules/fq_moe_prefill.py
new file mode 100644
index 0000000..d80073f
--- /dev/null
+++ b/exllamav3/modules/fq_moe_prefill.py
@@ -0,0 +1,191 @@
+"""Grouped MoE prefill for MiniCPM IQ4_XS experts.
+
+One Triton launch dequantizes every expert matrix of a layer to fp16 scratch
+(replacing 256 x 3 per-expert dequant + cuBLAS calls), then torch._grouped_mm
+runs gate / up / down over the expert-sorted rows with device-side offsets
+(no host sync). Same math as the per-expert path: fp16 weights, fp32 accum.
+"""
+import torch
+import triton
+import triton.language as tl
+
+_KV_IQ4NL = (-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113)
+_kv_tables = {}
+_scratch = {}
+
+
+def _kv(dev):
+ t = _kv_tables.get(dev)
+ if t is None:
+ t = _kv_tables[dev] = torch.tensor(_KV_IQ4NL, dtype=torch.float32, device=dev)
+ return t
+
+
+def _dq_iq4xs_grouped(ptrs, kv, out, n_blocks, BLK: tl.constexpr):
+ e = tl.program_id(1)
+ sb = tl.program_id(0) * BLK + tl.arange(0, BLK) # [BLK] super-block ids
+ m = sb < n_blocks
+ base = tl.load(ptrs + e).to(tl.pointer_type(tl.uint8))
+ j = tl.arange(0, 256) # element inside super-block
+ ib = j >> 5
+ jj = j & 31
+ bp = base + sb.to(tl.int64) * 136 # [BLK] block byte pointers
+ b0 = tl.load(bp, mask=m, other=0).to(tl.uint16)
+ b1 = tl.load(bp + 1, mask=m, other=0).to(tl.uint16)
+ d = (b0 | (b1 << 8)).to(tl.float16, bitcast=True).to(tl.float32) # [BLK]
+ h0 = tl.load(bp + 2, mask=m, other=0).to(tl.int32)
+ h1 = tl.load(bp + 3, mask=m, other=0).to(tl.int32)
+ sh = h0 | (h1 << 8) # [BLK]
+ sl = tl.load(bp[:, None] + 4 + (ib >> 1)[None, :], mask=m[:, None], other=0).to(tl.int32)
+ ls = ((sl >> (4 * (ib & 1))[None, :]) & 0xF) | (((sh[:, None] >> (2 * ib)[None, :]) & 3) << 4)
+ q = tl.load(bp[:, None] + 8 + (16 * ib + (jj & 15))[None, :], mask=m[:, None], other=0).to(tl.int32)
+ nib = tl.where((jj & 16)[None, :] != 0, q >> 4, q & 0xF)
+ dl = d[:, None] * (ls - 32).to(tl.float32)
+ v = dl * tl.load(kv + nib)
+ optr = out + (e * n_blocks + sb[:, None]).to(tl.int64) * 256 + j[None, :]
+ tl.store(optr, v.to(tl.float16), mask=m[:, None])
+
+
+def dequant_iq4xs_grouped(ptrs: torch.Tensor, out: torch.Tensor, n_blocks: int):
+ """ptrs: int64 [E] device pointers to [n_blocks*136] byte payloads;
+ out: fp16 contiguous [E * n_blocks * 256]."""
+ E = ptrs.shape[0]
+ BLK = 4
+ grid = (triton.cdiv(n_blocks, BLK), E)
+ _dq_iq4xs_grouped[grid](ptrs, _kv(ptrs.device), out, n_blocks, BLK=BLK, num_warps=4)
+
+
+def get_scratch(dev, name, numel):
+ t = _scratch.get((dev, name))
+ if t is None or t.numel() < numel:
+ _scratch.pop((dev, name), None)
+ t = _scratch[(dev, name)] = torch.empty(numel, dtype=torch.half, device=dev)
+ return t[:numel]
+
+
+# ---------------------------------------------------------------------------
+# Fused grouped GEMM: IQ4_XS weights decoded inside the K loop (no fp16 scratch)
+# ---------------------------------------------------------------------------
+
+def _iq4_sb(blk, kv, nmask, BN: tl.constexpr):
+ """Decode one IQ4_XS super-block per row of the tile: blk [BN] byte
+ pointers. Returns (wl, wh), each [128, BN] fp16 k-major: wl[c] is the low
+ nibble element of qs byte c (K index 32*(c//16)+c%16 inside the
+ super-block), wh[c] the high-nibble element (same index + 16). Per-element
+ op order matches fq_dq_iq4_xs_kernel."""
+ c = tl.arange(0, 128)
+ ib = tl.arange(0, 8)
+ b0 = tl.load(blk, mask=nmask, other=0).to(tl.uint16)
+ b1 = tl.load(blk + 1, mask=nmask, other=0).to(tl.uint16)
+ d = (b0 | (b1 << 8)).to(tl.float16, bitcast=True).to(tl.float32) # [BN]
+ h0 = tl.load(blk + 2, mask=nmask, other=0).to(tl.int32)
+ h1 = tl.load(blk + 3, mask=nmask, other=0).to(tl.int32)
+ sh = h0 | (h1 << 8) # [BN]
+ sl = tl.load(blk[:, None] + 4 + (ib >> 1)[None, :], mask=nmask[:, None], other=0).to(tl.int32) # [BN, 8]
+ ls = ((sl >> (4 * (ib & 1))[None, :]) & 0xF) | (((sh[:, None] >> (2 * ib)[None, :]) & 3) << 4)
+ dl = d[:, None] * (ls - 32).to(tl.float32) # [BN, 8]
+ dl = tl.reshape(tl.broadcast_to(dl[:, :, None], (BN, 8, 16)), (BN, 128))
+ q = tl.load(blk[:, None] + 8 + c[None, :], mask=nmask[:, None], other=0).to(tl.int32) # [BN, 128]
+ wl = (dl * tl.load(kv + (q & 0xF))).to(tl.float16)
+ wh = (dl * tl.load(kv + (q >> 4))).to(tl.float16)
+ return tl.trans(wl), tl.trans(wh)
+
+
+def _gmm_iq4(a_ptr, wptrs, kv, out_ptr, tile_e, tile_r0, offs_ptr, wrow_ptr,
+ N, K, stride_am, stride_om, E,
+ SWIGLU: tl.constexpr, SCALE_ROWS: tl.constexpr,
+ BM: tl.constexpr, BN: tl.constexpr):
+ """out[r, n] = sum_k A[r, k] * W_e[n, k] for the rows of tile t's expert.
+ SWIGLU: wptrs holds gate ptrs [0:E] and up ptrs [E:2E]; out = silu(g)*u
+ (g, u rounded to fp16 first, like the unfused path). SCALE_ROWS: multiply
+ the fp16 result by wrow[r] (routing weight, fp16 mul). K is walked one
+ 256-wide super-block at a time in a permuted (nibble-split) order that is
+ applied identically to A and W (sum order only): A arrives
+ pre-permuted (see perm_cols; the SWIGLU epilogue writes its output permuted)."""
+ pid_n = tl.program_id(0)
+ t = tl.program_id(1)
+ e = tl.load(tile_e + t)
+ if e >= E:
+ return
+ r0 = tl.load(tile_r0 + t)
+ r_end = tl.load(offs_ptr + e)
+ offs_m = r0 + tl.arange(0, BM)
+ mmask = offs_m < r_end
+ offs_n = pid_n * BN + tl.arange(0, BN)
+ nmask = offs_n < N
+ c = tl.arange(0, 128)
+ kb = K // 256
+ wb = tl.load(wptrs + e).to(tl.pointer_type(tl.uint8))
+ bp_n = wb + offs_n.to(tl.int64) * (kb * 136)
+ acc = tl.zeros((BM, BN), dtype=tl.float32)
+ if SWIGLU:
+ wb2 = tl.load(wptrs + E + e).to(tl.pointer_type(tl.uint8))
+ bp_n2 = wb2 + offs_n.to(tl.int64) * (kb * 136)
+ acc2 = tl.zeros((BM, BN), dtype=tl.float32)
+ a_row = a_ptr + offs_m.to(tl.int64)[:, None] * stride_am
+ for sb in range(0, kb):
+ al = tl.load(a_row + (sb * 256 + c)[None, :], mask=mmask[:, None], other=0.0)
+ ah = tl.load(a_row + (sb * 256 + 128 + c)[None, :], mask=mmask[:, None], other=0.0)
+ wl, wh = _iq4_sb(bp_n + sb * 136, kv, nmask, BN)
+ acc = tl.dot(al, wl, acc)
+ acc = tl.dot(ah, wh, acc)
+ if SWIGLU:
+ wl2, wh2 = _iq4_sb(bp_n2 + sb * 136, kv, nmask, BN)
+ acc2 = tl.dot(al, wl2, acc2)
+ acc2 = tl.dot(ah, wh2, acc2)
+ if SWIGLU:
+ g = acc.to(tl.float16).to(tl.float32)
+ u = acc2.to(tl.float16).to(tl.float32)
+ res = (g / (1.0 + tl.exp(-g)) * u).to(tl.float16)
+ else:
+ res = acc.to(tl.float16)
+ if SCALE_ROWS:
+ wr = tl.load(wrow_ptr + offs_m, mask=mmask, other=0.0).to(tl.float32)
+ res = (res.to(tl.float32) * wr[:, None]).to(tl.float16)
+ if SWIGLU:
+ # store the activation K-permuted (nibble-split) for the down GEMM's A loads
+ s_ = offs_n & 255
+ pos = tl.where((s_ & 16) != 0, 128 + (s_ >> 5) * 16 + (s_ & 15), (s_ >> 5) * 16 + (s_ & 15))
+ ocol = (offs_n - s_) + pos
+ else:
+ ocol = offs_n
+ o = out_ptr + offs_m.to(tl.int64)[:, None] * stride_om + ocol[None, :]
+ tl.store(o, res, mask=mmask[:, None] & nmask[None, :])
+
+
+def build_tiles(counts: torch.Tensor, M: int, BM: int):
+ """Sync-free tile map. counts: int64 [E] rows per expert (sorted layout).
+ Returns (tile_e int32 [T], tile_r0 int32 [T], offs int32 [E]) with
+ T = M // BM + E (static bound); unused tiles have tile_e == E."""
+ E = counts.shape[0]
+ dev = counts.device
+ T = M // BM + E
+ offs = counts.cumsum(0)
+ starts = offs - counts
+ tiles = (counts + BM - 1) // BM
+ cum = tiles.cumsum(0)
+ t = torch.arange(T, device=dev)
+ te = torch.searchsorted(cum, t, right=True) # first expert with cum > t; E if none
+ tec = te.clamp(max=E - 1)
+ local = t - (cum[tec] - tiles[tec])
+ r0 = starts[tec] + local * BM
+ return te.to(torch.int32), r0.to(torch.int32), offs.to(torch.int32)
+
+
+def gmm_iq4(a, wptrs, out, tile_e, tile_r0, offs, N, K, E, swiglu=False, wrow=None, BM=64, BN=64,
+ num_warps=4, num_stages=1):
+ T = tile_e.shape[0]
+ grid = (triton.cdiv(N, BN), T)
+ _gmm_iq4[grid](a, wptrs, _kv(a.device), out, tile_e, tile_r0, offs,
+ wrow if wrow is not None else offs, N, K, a.stride(0), out.stride(0), E,
+ SWIGLU=swiglu, SCALE_ROWS=wrow is not None, BM=BM, BN=BN,
+ num_warps=num_warps, num_stages=num_stages)
+
+
+def perm_cols(x: torch.Tensor) -> torch.Tensor:
+ """K-permute [M, K] (K % 256 == 0) into the nibble-split order _gmm_iq4 expects."""
+ M, K = x.shape
+ return x.view(M, K // 256, 8, 2, 16).permute(0, 1, 3, 2, 4).reshape(M, K)
diff --git a/exllamav3/modules/gated_delta_net.py b/exllamav3/modules/gated_delta_net.py
index 0335dda..feb09e4 100644
--- a/exllamav3/modules/gated_delta_net.py
+++ b/exllamav3/modules/gated_delta_net.py
@@ -184,7 +184,7 @@ class GDNState:
return 0
- def stash(self, async_: bool = False, pin_pool: dict = None):
+ def stash(self, async_: bool = False, pin_pool: dict = None, pinned: bool = False):
"""async_ (EXL3_NC2_ASYNC_STASH, via RecurrentCache.stash_async only): non-blocking D2H into pinned host tensors on the
current stream plus one event in stashed["_ev"]; the cache syncs it and moves the copies to pageable memory
(RecurrentCache._finish, worker thread) before any reader sees the entry."""
@@ -202,7 +202,7 @@ class GDNState:
stashed["_ev"] = ev
return stashed
for k, l in layers.items():
- stashed[k] = l.stash(self.slot)
+ stashed[k] = l.stash(self.slot, pinned = pinned) if pinned else l.stash(self.slot)
else:
cp_handle = new_checkpoint_handle()
self.cache.model.tp_dispatch_all(mp_cache_recurrent_stash, (id(self.cache), cp_handle, self.slot))
@@ -365,9 +365,18 @@ class GDNLayerState:
)
- def stash(self, slot, position: int = 0):
+ def stash(self, slot, position: int = 0, pinned: bool = False):
cdim = self.module.conv_kernel_size
b = _base_value.get((self.cache_id, slot), 0)
+ if pinned:
+ # CUDA prompt-end tail checkpoint (job._tail_stash): async copy into page-locked buffers from torch's
+ # caching host allocator (reused across stashes, bounded by the tail LRU) instead of a synchronous .cpu()
+ # into fresh pageable memory; stream order keeps the copy ahead of the next write and of unstash
+ src = (self.recurrent_state[slot, b:b + 1], self.conv_state[slot, :, :cdim])
+ out = tuple(torch.empty(s.shape, dtype = s.dtype, pin_memory = True) for s in src)
+ for d, s in zip(out, src):
+ d.copy_(s, non_blocking = True)
+ return out
return (
self.recurrent_state[slot, b:b + 1].cpu(),
self.conv_state[slot, :, :cdim].cpu()
@@ -422,6 +431,12 @@ class GatedDeltaNet(Module):
rms_norm_eps: float,
conv_kernel_size: int,
beta_scale: float = 1.0,
+ # Blocked GQA pairing (MiniCPM GGUF): the file stores v-heads even/odd
+ # grouped while q/k heads are sequential, and pairs v[j] with q[j % nk]
+ # (llama blocked style). Repeat pairing (v[2m]/v[2m+1] with q[m]) then
+ # mis-pairs 30/32 heads. When set, q/k are duplicated blocked AFTER
+ # the (depthwise, order-agnostic) conv and the rule runs plain 32/32.
+ blocked_gqa: bool = False,
key_a_log: str | None = None,
key_dt_bias: str | None = None,
key_conv1d: str | None = None,
@@ -472,6 +487,7 @@ class GatedDeltaNet(Module):
self.k_dim = self.k_head_dim * self.num_k_heads
self.v_dim = self.v_head_dim * self.num_v_heads
self.beta_scale = beta_scale
+ self.blocked_gqa = blocked_gqa or os.environ.get("EXL3_GDN_BLOCKED", "0") == "1"
self.out_dtype = out_dtype
@@ -1369,8 +1385,14 @@ class GatedDeltaNet(Module):
max_rows = 2 if os.environ.get("EXL3_PF_NO_TAIL", "0") == "1" else 1
if self.kda and os.environ.get("EXL3_NC2_CKPT4", "0") == "1":
max_rows = 4 # CK4 kernel build (vendor/fla/hip/kda_fused_h_hip.py): 8192-row chunks
- if len(rows) > max_rows or any(r % 64 or not cdim <= r < seqlen for r in rows):
+ if (not self.kda and os.environ.get("EXL3_GDN_HF", "0") == "1") or \
+ (self.kda and (int(os.environ.get("EXL3_TAIL_DENSE", "0")) > 0 or int(os.environ.get("EXL3_TAIL_SUB", "0")) > 0)):
+ max_rows = 8 # gdn_hf.hip / the CK8 kda_fused_h build side-write up to 8 rows (dense prompt-tail checkpoints, see Job.tail_ckpt_rows)
+ if any(r % 64 or not cdim <= r < seqlen for r in rows):
return None
+ # more rows than the kernel has slots: the deepest ones are written (the model-wide stash needs every layer to
+ # hold a row, so a row some layer drops is simply not stashed, see Job.stash_midchunk)
+ rows = rows[-max_rows:]
cks = [{
"row": r,
"chunk": r // 64,
@@ -1737,8 +1759,20 @@ class GatedDeltaNet(Module):
)
# Delta rule
+ _nk, _kd, _mq = self.num_k_heads, self.k_dim, mixed_qkv
+ if self.blocked_gqa and not self.kda:
+ # Blocked pairing for grouped-v files: duplicate q/k heads
+ # blocked ([q,q] not interleaved) AFTER the depthwise conv and
+ # run the rule plain (nk == nv, no repeat). Bitwise vs repeat
+ # on sequential weights; correct on grouped ones.
+ # mixed_qkv is [B, T, C] here (conv output transposed back).
+ _kd2 = 2 * self.k_dim
+ _q = _mq[..., :self.k_dim]
+ _k = _mq[..., self.k_dim:_kd2]
+ _mq = torch.cat([_q, _q, _k, _k, _mq[..., _kd2:]], dim=-1)
+ _nk, _kd = self.num_v_heads, self.v_dim
core_attn_out = gated_delta_rule_fn(
- mixed_qkv = mixed_qkv,
+ mixed_qkv = _mq,
beta = beta,
g = g,
recurrent_state = recurrent_state,
@@ -1746,9 +1780,9 @@ class GatedDeltaNet(Module):
recurrent_base = recurrent_base,
history = save_history,
save_state = save_state,
- num_k_heads = self.num_k_heads,
+ num_k_heads = _nk,
num_v_heads = self.num_v_heads,
- k_dim = self.k_dim,
+ k_dim = _kd,
v_dim = self.v_dim,
k_head_dim = self.k_head_dim,
v_head_dim = self.v_head_dim,
diff --git a/exllamav3/modules/linear.py b/exllamav3/modules/linear.py
index 1307e11..16d14ac 100644
--- a/exllamav3/modules/linear.py
+++ b/exllamav3/modules/linear.py
@@ -79,6 +79,10 @@ class Linear(Module):
no_defer_load: bool = False
):
super().__init__(config, key, qmap)
+ # Routed-weighted Hessians (EXL3_RWH): expert Linears also accumulate a per-expert H over their routed
+ # tokens only, rows scaled by the routing weight; qmap_q is where the quantizer looks the final H up
+ self.cap_rkey = None
+ self.qmap_q = None
self.alt_key = alt_key
self.in_features_unpadded = in_features
@@ -641,6 +645,26 @@ class Linear(Module):
params["_cap_pending"] = pend
pend.append((params["capture"][self.qmap], x))
+ rw = params.get("_cap_rw")
+ if rw is not None and self.cap_rkey is not None:
+ idx, wv = rw
+ hd = params["capture"].get(self.cap_rkey)
+ if hd is None:
+ hd = self.init_H_data(True)
+ hd["sw2"] = torch.zeros((), dtype = torch.float32, device = self.device)
+ hd["sw4"] = torch.zeros((), dtype = torch.float32, device = self.device)
+ params["capture"][self.cap_rkey] = hd
+ if hd["first_key"] == self.key:
+ xr = x.view(-1, x.shape[-1])[idx] * wv.to(x.dtype).unsqueeze(1)
+ hd["sw2"] += (wv.float() ** 2).sum()
+ hd["sw4"] += (wv.float() ** 4).sum()
+ hd["count"] += int(idx.numel())
+ pend = params.get("_cap_pending")
+ if pend is None:
+ pend = []
+ params["_cap_pending"] = pend
+ pend.append((hd, xr))
+
if _cap_t0 is not None:
CAP_STAT["wall"] += _time.perf_counter() - _cap_t0
CAP_STAT["calls"] += 1
diff --git a/exllamav3/modules/ngram_embedding.py b/exllamav3/modules/ngram_embedding.py
index 3ca32cb..0f5fd08 100644
--- a/exllamav3/modules/ngram_embedding.py
+++ b/exllamav3/modules/ngram_embedding.py
@@ -77,6 +77,7 @@ def _find_nth_prime_after(start: int, count: int) -> int:
PREFETCH_ENABLED = os.environ.get("EXL3_NGRAM_PREFETCH", "1") != "0" # debug/A-B switch
PREFETCH_MIN_TOKENS = 256 # positions (bsz * seq) below which prefetch() declines (decode-sized)
+WARM_TOKENS = int(os.environ.get("EXL3_NGRAM_WARM_TOKENS", "8192")) # look-ahead window of warm() in prompt positions; 0 = off
MAX_PIN_SETS = 2 # staging sets: one with the last forward's uploads in flight, one being staged
@@ -102,6 +103,24 @@ class _PinSet:
self.packed = torch.empty((n, row_words), dtype = row_dtype, pin_memory = True)
+RAM_MARGIN_BYTES = 48 << 30
+
+
+def decide_ngram_stream(requested, table_bytes: int, avail_bytes):
+ """Placement of the n-gram table: returns (stream_from_disk, reason).
+ Disk streaming is the default. RAM is used only when explicitly requested (requested is False): host memory
+ sampled while the rest of the pack is still loading says nothing about what remains afterwards, so no automatic
+ RAM choice is made. An explicit RAM request on a host without table + margin is honored but flagged."""
+ if requested is None:
+ return True, "default: disk streaming"
+ if requested:
+ return True, "requested: disk streaming"
+ if avail_bytes is not None and avail_bytes < table_bytes + RAM_MARGIN_BYTES:
+ return False, (f"requested: RAM, WARNING only {avail_bytes / 2**30:.1f} GiB available, "
+ f"table + {RAM_MARGIN_BYTES >> 30} GiB margin = {(table_bytes + RAM_MARGIN_BYTES) / 2**30:.1f} GiB")
+ return False, "requested: RAM"
+
+
class NGramEmbedding(Module):
def __init__(
@@ -151,6 +170,7 @@ class NGramEmbedding(Module):
self._pins = [] # pinned staging sets for the fast path (see _PinSet)
self._pending = [] # queued prefetches, oldest first: {"history", "pin", "future"}
self._executor = None
+ self._warm_pin = None # private staging set of warm(), touched only by the worker thread
self.prefetch_stats = {"hit": 0, "miss": 0, "retired": 0}
self._row_dtype = None # stored row dtype of the unquantized table
@@ -247,13 +267,12 @@ class NGramEmbedding(Module):
if stream_from_disk is None:
infer_params = getattr(self.config, "infer_params", None)
stream_from_disk = infer_params.ngram_stream_from_disk if infer_params is not None else None
- if stream_from_disk is None:
- # Auto: per-token row preads cost ~0.8 ms of GPU idle per decode token (tokplan1), so hold
- # the table in RAM when it fits with a wide margin; otherwise stream from disk
- from ..util.memory import host_memory_available
- avail = host_memory_available()
- tbl = self.num_rows * (words_per_row(self.K) * 2 if quantized else ROW_DIM * 2)
- stream_from_disk = avail is None or avail < tbl + (48 << 30)
+ from ..util.memory import host_memory_available
+ avail = host_memory_available()
+ tbl = self.num_rows * (words_per_row(self.K) * 2 if quantized else ROW_DIM * 2)
+ stream_from_disk, why = decide_ngram_stream(stream_from_disk, tbl, avail)
+ print(f"[ngram] placement: {'disk' if stream_from_disk else 'ram'} ({why}); table {tbl / 2**30:.1f} GiB, "
+ f"host MemAvailable {'?' if avail is None else f'{avail / 2**30:.1f}'} GiB", flush=True)
if stream_from_disk:
self.mode = "trellis_disk" if quantized else "fp16_disk"
self.handles = [stc.get_tensor_handle(k) for k in keys]
@@ -304,7 +323,7 @@ class NGramEmbedding(Module):
from ..util.memory import host_memory_available
av = host_memory_available()
print(f"[ngram] table mode {self.mode}: {self.num_rows} rows, host MemAvailable "
- f"{'?' if av is None else f'{av / 2**30:.1f}'} GiB at load (RAM mode needs table + 48 GiB; "
+ f"{'?' if av is None else f'{av / 2**30:.1f}'} GiB at load (RAM mode is opt-in, EXL3_NGRAM_STREAM=0; "
f"disk mode = every prefill chunk reads its rows from the file, a busy disk or a cold page cache stalls it)",
flush=True)
@@ -579,6 +598,36 @@ class NGramEmbedding(Module):
"future": self._executor.submit(self._stage, history, pin),
})
+ @torch.inference_mode()
+ def _warm_stage(self, history: torch.Tensor):
+ """Hash + gather into the private set and drop the rows: the point is the page cache."""
+ pin = self._warm_pin
+ if pin is None:
+ pin = self._warm_pin = _PinSet()
+ n = (history.shape[1] - self.context_len) * self.num_heads
+ trellis = self.mode.startswith("trellis")
+ pin.grow(n, words_per_row(self.K) if trellis else ROW_DIM, torch.int16 if trellis else self._row_dtype)
+ self._stage(history, pin)
+
+ def warm(self, history: torch.Tensor):
+ """
+ Read the table rows of a later part of the prompt into the page cache, on the prefetch
+ worker (queued behind the stage of the chunk being issued, so it never competes with it
+ for the disk). `history` is (1, context + seq) ids as for prefetch(). Disk modes only:
+ a cold gather is IOPS-bound (~0.4 s per 4096-token chunk) and otherwise stalls the GPU at
+ the head of every chunk; warmed, the same gather costs a few ms. Changes no result.
+ """
+ if not PREFETCH_ENABLED or self.mode is None or self.handles is None or history.dim() != 2:
+ return
+ if history.shape[1] - self.context_len < PREFETCH_MIN_TOKENS:
+ return
+ history = history.to("cpu", torch.int64).contiguous().clone()
+ for h in self.handles:
+ h._ensure_open()
+ if self._executor is None:
+ self._executor = ThreadPoolExecutor(max_workers = 1, thread_name_prefix = "ngram_prefetch")
+ self._executor.submit(self._warm_stage, history)
+
@override
def forward(
self,
diff --git a/exllamav3/modules/ple.py b/exllamav3/modules/ple.py
index 125b46a..f861347 100644
--- a/exllamav3/modules/ple.py
+++ b/exllamav3/modules/ple.py
@@ -7,7 +7,7 @@ import torch.nn.functional as F
from .module import Module
from .linear import Linear
from .rmsnorm import RMSNorm
-from .ngram_embedding import NGramEmbedding
+from .ngram_embedding import NGramEmbedding, WARM_TOKENS
from ..ext import exllamav3_ext as ext
from ..tokenizer.mm_embedding import FIRST_MM_EMBEDDING_INDEX
from ..model.config import Config
@@ -396,6 +396,24 @@ class PLELayer(Module):
"""
history, _, _ = self._state_history(self._prepare_ids(input_ids), params)
self.ple_embedding.prefetch(history)
+ ahead = params.get("pf_ahead")
+ if ahead is not None and WARM_TOKENS > 0 and self.ple_embedding.handles is not None:
+ self._warm_ahead(*ahead)
+
+ def _warm_ahead(self, seq, end: int):
+ """Warm the page cache for the rows of the next WARM_TOKENS prompt positions after this chunk
+ (seq.sequence_ids, chunk ends at `end`), in windows of at most one 4096-row chunk; every
+ position is warmed once per sequence (high-water mark on seq)."""
+ total = len(seq.sequence_ids) - 1
+ lo = max(end, getattr(seq, "_ngram_warm_to", 0))
+ hi = min(total, end + WARM_TOKENS)
+ ctx = self.ple_embedding.context_len
+ while lo < hi and lo >= ctx:
+ nxt = min(hi, lo + 4096)
+ ids = self._prepare_ids(seq.sequence_ids.torch_slice(lo - ctx, nxt))
+ self.ple_embedding.warm(ids)
+ lo = nxt
+ seq._ngram_warm_to = max(lo, getattr(seq, "_ngram_warm_to", 0))
@override
def forward(self, x: torch.Tensor, params: dict, out_dtype: torch.dtype | None = None):
diff --git a/exllamav3/modules/quant/exl3.py b/exllamav3/modules/quant/exl3.py
index 969ae37..623795a 100644
--- a/exllamav3/modules/quant/exl3.py
+++ b/exllamav3/modules/quant/exl3.py
@@ -18,7 +18,10 @@ DEC_GEMV_R_LOOP_MIN_K = int(os.environ.get("EXL3_DEC_GEMV_R_LOOP_MIN_K", "99"))
# (mlp.py). Rows stay bit-exact vs R batch-1 dec_gemv calls (the R=1 plain-decode math). R=1 untouched.
# Mutable at run time for one-load A/B: set VERIFY_FUSE["on"] (the harness also calls block_graph.purge()).
VERIFY_FUSE = {"on": os.environ.get("EXL3_VERIFY_FUSE", "0") != "0"}
-AUTO_RECONSTRUCT_THRESHOLD = 144
+# With the 32-row GEMM tile (EXL3_GEMM_SHAPE_5) the GEMM path beats reconstruct + hgemm up to ~192-256
+# rows on Ampere (Qwen3.8-27B TTFT 160 / 192 tokens 278 -> 238 / 320 -> 279 ms; at 256 reconstruct wins 344 vs 362 ms).
+# Without that patch 144 is right (16-row passes: threshold 512 is slower at every T > 144).
+AUTO_RECONSTRUCT_THRESHOLD = 192 if not torch.version.hip else 144
MAX_RECONSTRUCT_SLICE_N = 32768
RECONSTRUCT_SLICE_GRANULARITY_N = 128
@@ -355,7 +358,10 @@ class LinearEXL3:
self.suh = suh if suh is not None else self.unpack_bf(su)
self.svh = svh if svh is not None else self.unpack_bf(sv)
self.trellis = trellis
- self.K = trellis.shape[-1] / 16
+ # Integral K stays an int (the CUDA BC objects and kernels take int K); half-integer K stays a float.
+ # Same rule as upstream exllamav3 1.6.0 (MIT, modules/quant/exl3.py:68).
+ K = trellis.shape[-1] / 16
+ self.K = int(K) if float(K).is_integer() else K
self.in_features = in_features
self.out_features = out_features
self.bias = bias
@@ -372,6 +378,7 @@ class LinearEXL3:
self.dec_ok = dec_supported(self)
self.dec_ok_moe = dec_moe_supported(self)
self.bsz1_xh_args = (self.trellis.device, (1, self.in_features), self.out_dtype)
+ # The CUDA BC object takes an integer K; half-integer K tensors keep the Python path
self.bc = ext.BC_LinearEXL3(
self.trellis,
self.suh,
@@ -381,7 +388,7 @@ class LinearEXL3:
self.mcg,
self.mul1,
g_tensor_cache.get(*self.bsz1_xh_args)
- )
+ ) if isinstance(self.K, int) else None
def unload(self):
diff --git a/exllamav3/modules/sliding_attn.py b/exllamav3/modules/sliding_attn.py
index f90c0c8..bd67d28 100644
--- a/exllamav3/modules/sliding_attn.py
+++ b/exllamav3/modules/sliding_attn.py
@@ -241,6 +241,26 @@ class SWALayerState:
self.v_state[slot, a:b].copy_(v)
+def swa_graph_prep(cache, swa_mods, rsg, seqlen):
+ """Per-step host work of every sliding layer for the CUDA graph runner, done once outside the capture:
+ the left shift of a full ring (all layers share the decision; each layer shifts its own state) and the
+ in-state lengths (identical across layers). Returns the length list; sets rs.wshift like _decode_state_prep."""
+ S = swa_mods[0][0].kv_state_size
+ if any(rs.position - rs.window_beg + seqlen > S for rs in rsg):
+ for m, inst in swa_mods:
+ k_states, v_states = cache.get_recurrent_layer((m.layer_idx, inst)).get_state_tensors()
+ m._decode_state_prep(rsg, k_states, v_states, seqlen)
+ else:
+ for rs in rsg:
+ rs.wshift = 0
+ # after a shift the lengths come from the post-shift rs.position/window_beg of this step (window_beg moves in post_advance)
+ out = []
+ for rs in rsg:
+ cp = rs.position - rs.window_beg
+ out.append(cp - rs.wshift if rs.wshift else cp)
+ return out
+
+
class SlidingAttention(Module):
_seqlens_last = None
@@ -917,6 +937,18 @@ class SlidingAttention(Module):
return x
+ def _slot_block_table(self, slots):
+ bt = self.bt_cache.get(slots)
+ if bt is None:
+ pps = self.kv_state_size // PAGE_SIZE
+ bt = torch.tensor(
+ [[slot * pps + j for j in range(pps)] for slot in slots],
+ dtype = torch.int32, device = self.device
+ )
+ self.bt_cache[slots] = bt
+ return bt
+
+
def _decode_state_prep(self, rsg, k_states, v_states, seqlen):
"""Per-row page shift when the window run reaches the end of the state buffer, cached
per-slot block table, and the in-state sequence lengths for a decode step."""
@@ -935,14 +967,7 @@ class SlidingAttention(Module):
rs.wshift = 0
positions_l.append(cache_pos)
- slots = tuple(rs.slot for rs in rsg)
- bt = self.bt_cache.get(slots)
- if bt is None:
- bt = torch.tensor(
- [[slot * pps + j for j in range(pps)] for slot in slots],
- dtype = torch.int32, device = self.device
- )
- self.bt_cache[slots] = bt
+ bt = self._slot_block_table(tuple(rs.slot for rs in rsg))
# Every sliding layer of a decode step has the same in-state lengths: one upload per step
# instead of one per layer (read-only downstream)
key = (self.device, tuple(positions_l))
@@ -978,7 +1003,11 @@ class SlidingAttention(Module):
position = params.get("position", 0)
k_states, v_states = rsl.get_state_tensors()
- bt, cache_seqlens = self._decode_state_prep(rsg, k_states, v_states, seqlen)
+ swa_cs = params.get("swa_cs")
+ if swa_cs is not None:
+ bt, cache_seqlens = self._slot_block_table(tuple(rs.slot for rs in rsg)), swa_cs
+ else:
+ bt, cache_seqlens = self._decode_state_prep(rsg, k_states, v_states, seqlen)
return bca.step(x, cache_seqlens, bt, position, positions, position_ids, inv_freq)
@@ -1107,7 +1136,12 @@ class SlidingAttention(Module):
if seqlen <= 16 and not non_causal_spans:
# Decode: append into the state (shifting it left first on the rare step where the
# window run reaches the end of the buffer) and attend over the pages
- bt, cache_seqlens = self._decode_state_prep(rsg, k_states, v_states, seqlen)
+ swa_cs = params.get("swa_cs")
+ if swa_cs is not None:
+ # CUDA graph runner: shift + seqlens were prepared outside the capture (swa_graph_prep)
+ bt, cache_seqlens = self._slot_block_table(tuple(rs.slot for rs in rsg)), swa_cs
+ else:
+ bt, cache_seqlens = self._decode_state_prep(rsg, k_states, v_states, seqlen)
# DFlash verify (R rows): a single paged_attn_triton_decode call over all
# R rows at once tiles/splits the KV span from the batch's (single) cache_seqlens and
diff --git a/exllamav3/tokenizer/tokenizer.py b/exllamav3/tokenizer/tokenizer.py
index 14f293b..7ddcaba 100644
--- a/exllamav3/tokenizer/tokenizer.py
+++ b/exllamav3/tokenizer/tokenizer.py
@@ -89,10 +89,14 @@ class Tokenizer:
# Remove unspecial added tokens that exist in the base tokenizer already, but only if they decode correctly
# see https://github.com/huggingface/tokenizers/issues/1392
ok_tokens = []
+ spm_text = {}
for p, i in self.unspecial_piece_to_id.items():
try:
itp = self.tokenizer.decode([i], skip_special_tokens = False)
if itp == p: ok_tokens.append(p)
+ # SentencePiece whitespace runs stored as added tokens (Gemma 3: "▁▁▁▁" = four spaces): the content is the
+ # raw piece, the decoder's text differs only by the "▁" -> " " replacement, so decode to that text
+ elif "\u2581" in p and itp == p.replace("\u2581", " "): spm_text[i] = itp
except IndexError:
pass
for t in ok_tokens: del self.unspecial_piece_to_id[t]
@@ -100,6 +104,8 @@ class Tokenizer:
# Invert extended dictionaries
self.extended_id_to_piece = {v: k for k, v in self.extended_piece_to_id.items()}
self.unspecial_id_to_piece = {v: k for k, v in self.unspecial_piece_to_id.items()}
+ self.extended_id_to_piece.update(spm_text)
+ self.unspecial_id_to_piece.update(spm_text)
# Special added tokens the underlying tokenizer doesn't know (declared in
# tokenizer_config.json or added_tokens.json but missing from tokenizer.json's
diff --git a/exllamav3/util/jit_log.py b/exllamav3/util/jit_log.py
new file mode 100644
index 0000000..91b410e
--- /dev/null
+++ b/exllamav3/util/jit_log.py
@@ -0,0 +1,40 @@
+"""Optional log of Triton JIT compiles (EXL3_LOG_JIT=1): one line per kernel compiled in this process, with its
+compile-time constants and seconds. Kernels served from the on-disk cache are not logged. Use it to see what a start
+(or the first request after READY) still compiles."""
+from __future__ import annotations
+import os, sys, time
+
+_t0: dict = {}
+
+
+def install(log=None) -> bool:
+ if os.environ.get("EXL3_LOG_JIT", "0") != "1":
+ return False
+ try:
+ from triton import knobs
+ except Exception: # noqa: BLE001 older triton: no hooks
+ return False
+ out = log or (lambda s: print(s, file=sys.stderr, flush=True))
+ started = time.perf_counter()
+
+ def pre(*, key, repr, fn, compile, is_manual_warmup, already_compiled):
+ if not already_compiled:
+ _t0[key] = time.perf_counter()
+ return False
+
+ def post(*, key, repr, fn, compile, is_manual_warmup, already_compiled):
+ t = _t0.pop(key, None)
+ if t is None or already_compiled:
+ return
+ now = time.perf_counter()
+ name = str(repr).split("[", 1)[0]
+ consts = ""
+ try:
+ consts = " ".join(f"{k[-1] if isinstance(k, tuple) else k}={v}" for k, v in (compile.get("constants") or {}).items())
+ except Exception: # noqa: BLE001 diagnostics never break a compile
+ pass
+ out(f"[jit] t={now - started:7.1f}s took {now - t:5.2f}s {name} {str(repr)[len(name):].split(']', 1)[0]}] {consts[:300]}")
+
+ knobs.runtime.jit_cache_hook = pre
+ knobs.runtime.jit_post_compile_hook = post
+ return True
diff --git a/exllamav3/util/kernel_seed.py b/exllamav3/util/kernel_seed.py
new file mode 100644
index 0000000..d66d5fa
--- /dev/null
+++ b/exllamav3/util/kernel_seed.py
@@ -0,0 +1,238 @@
+"""Pre-compiled Triton kernels shipped with the code (exllamav3/kernel_seed/triton-<version>-<arch>.tar.xz).
+
+A fresh container has an empty Triton cache, and every kernel the servers use (and every constexpr / divisibility variant a request
+reaches) is compiled on first use: 25 s during start-up plus 30 s inside the first requests of a GLM start. The compiled objects
+are plain files keyed by a hash of the kernel source, its arguments and the Triton version, so they can be shipped.
+
+Portable keys. Triton 3.7 puts the absolute path of its own bundled device libraries (backends/amd/lib/ocml.bc, ockl.bc) into the
+HIP compile options and hashes it, so the same kernel gets a different cache key under every install prefix: a seed built in one
+virtual environment would never hit in another (the container installs under its own prefix). portable_keys() replaces that
+prefix by a placeholder inside HIPOptions.hash(); only the key changes, not what is compiled. The seed is built and used with it.
+
+install() unpacks the members whose key directory is missing from the live cache (never overwrites) and writes the group file Triton
+reads, with paths of the live cache. Only the code object and its metadata are shipped; Triton does not need the IR files to load a kernel.
+The autotune results (<kernel>.autotune.json) are shipped too: without them the first call of an autotuned kernel times every
+configuration (several seconds for the GLM linear-attention kernels) even when all configurations are compiled.
+A seed built for another Triton version or GPU architecture is not used, and on another architecture (or without a GPU) install()
+does nothing. EXL3_KERNEL_SEED=0 turns it off; EXL3_KERNEL_SEED=build uses the portable keys but installs nothing (the mode in which a
+seed is built from an empty cache).
+pack() builds a seed from a populated cache (tools/kernel_seed/build.py): it strips the debug sections of the code objects (they carry
+the build machine's source paths), replaces the library paths in the metadata by a placeholder, and refuses a seed that still holds a
+local path. install() writes the live paths back.
+"""
+from __future__ import annotations
+import hashlib, io, json, os, re, shutil, subprocess, sys, tarfile, tempfile, time
+from pathlib import Path
+
+SEED_DIR = Path(__file__).resolve().parent.parent / "kernel_seed"
+LIB_PLACEHOLDER = "@TRITON_AMD_LIB@" # stands for <triton>/backends/amd/lib in the cache key and in the shipped metadata
+_LOCAL_PATH = re.compile(rb"/(?:home|Users|root|tmp|mnt|var|opt|usr|srv)/|[A-Za-z]:\\") # a seed must hold none of these
+
+
+def _cache_dir() -> Path:
+ """The directory Triton itself reads (honours TRITON_CACHE_DIR, TRITON_HOME and HOME)."""
+ try:
+ from triton import knobs
+ if knobs.cache.dir:
+ return Path(knobs.cache.dir)
+ except Exception: # noqa: BLE001
+ pass
+ d = os.environ.get("TRITON_CACHE_DIR")
+ return Path(d) if d else Path(os.environ.get("HOME", "/tmp")) / ".triton" / "cache"
+
+
+def seed_name(triton_version: str, arch: str) -> str:
+ return f"triton-{triton_version}-{arch}.tar.xz"
+
+
+def find_seed(arch: str = "gfx1151") -> Path | None:
+ try:
+ import triton
+ except Exception: # noqa: BLE001
+ return None
+ p = SEED_DIR / seed_name(triton.__version__, arch)
+ return p if p.is_file() else None
+
+
+def device_arch() -> str | None:
+ """gcnArchName of the current GPU without the feature flags ("gfx1151"), None without a HIP GPU."""
+ try:
+ import torch
+ if not (torch.version.hip and torch.cuda.is_available()):
+ return None
+ name = torch.cuda.get_device_properties(torch.cuda.current_device()).gcnArchName
+ return name.split(":")[0] or None
+ except Exception: # noqa: BLE001
+ return None
+
+
+def _amd_libdir() -> str | None:
+ try:
+ from triton.backends.amd import compiler as amd
+ return str(Path(amd.__file__).parent / "lib")
+ except Exception: # noqa: BLE001
+ return None
+
+
+def portable_keys(arch: str = "gfx1151") -> bool:
+ """Make the cache key of a HIP kernel independent of the Triton install prefix. Returns True when the keys are portable.
+
+ The original HIPOptions.hash() is sha256 of "name-value" for every option joined with "_"; the options hold the absolute paths of
+ ocml.bc / ockl.bc under the Triton package. This hash is the same text with that package lib directory replaced by LIB_PLACEHOLDER.
+ It is installed only after it is checked to reproduce the original on a real options object (with the directory left in), so a
+ Triton whose options or hashing differ keeps its own hash and the seed is simply not used."""
+ try:
+ from triton.backends.amd import compiler as amd
+ except Exception: # noqa: BLE001
+ return False
+ cls, libdir = amd.HIPOptions, _amd_libdir()
+ if getattr(cls.hash, "_exl3_portable", False):
+ return True
+ if not libdir:
+ return False
+
+ def text(self) -> str:
+ return "_".join(f"{name}-{val}" for name, val in self.__dict__.items())
+
+ try:
+ probe = cls(arch = arch)
+ if libdir not in text(probe) or hashlib.sha256(text(probe).encode("utf-8")).hexdigest() != cls.hash(probe):
+ return False
+ except Exception: # noqa: BLE001
+ return False
+
+ def portable_hash(self):
+ return hashlib.sha256(text(self).replace(libdir, LIB_PLACEHOLDER).encode("utf-8")).hexdigest()
+
+ portable_hash._exl3_portable = True
+ cls.hash = portable_hash
+ return True
+
+
+def install(arch: str | None = None, cache: Path | None = None, log=None) -> int:
+ """Returns the number of kernels added to the cache. Does nothing without a HIP GPU, on an architecture without a seed,
+ with EXL3_KERNEL_SEED=0, or when there is no seed for this Triton version."""
+ mode = os.environ.get("EXL3_KERNEL_SEED", "1")
+ if mode == "0":
+ return 0
+ arch = arch or device_arch()
+ if not arch or not arch.startswith("gfx"):
+ return 0
+ seed = find_seed(arch)
+ if mode != "build" and seed is None:
+ return 0
+ if not portable_keys(arch):
+ print("kernel seed: not used (this Triton's HIP cache key could not be made portable)", file=sys.stderr, flush=True)
+ return 0
+ if mode == "build":
+ return 0
+ libdir = _amd_libdir() or ""
+ cache = Path(cache) if cache else _cache_dir()
+ t0 = time.perf_counter()
+ added = 0
+ try:
+ cache.mkdir(parents=True, exist_ok=True)
+ with tarfile.open(seed, "r:xz") as tf:
+ by_key: dict[str, list[tarfile.TarInfo]] = {}
+ for m in tf.getmembers():
+ if m.isfile() and m.name.count("/") == 1 and ".." not in m.name:
+ by_key.setdefault(m.name.split("/")[0], []).append(m)
+ for key, members in by_key.items():
+ kdir = cache / key
+ if kdir.exists():
+ continue
+ tmp = cache / f".seed-{os.getpid()}-{key}"
+ tmp.mkdir(parents=True, exist_ok=True)
+ names = []
+ for m in members:
+ data = tf.extractfile(m).read()
+ if m.name.endswith(".json"): # the library paths of this install, as Triton would have written them
+ data = data.replace(LIB_PLACEHOLDER.encode(), libdir.encode())
+ (tmp / Path(m.name).name).write_bytes(data)
+ names.append(Path(m.name).name)
+ meta = [n for n in names if n.endswith(".json") and not n.endswith(".autotune.json")]
+ for n in meta: # the group file Triton reads: kernel files with the live paths
+ group = {f: str(kdir / f) for f in names if f.startswith(n[:-5] + ".")}
+ (tmp / f"__grp__{n}").write_text(json.dumps({"child_paths": group}))
+ try:
+ os.rename(tmp, kdir)
+ added += 1
+ except OSError: # another process installed it first
+ for f in tmp.iterdir():
+ f.unlink()
+ tmp.rmdir()
+ except Exception as exc: # noqa: BLE001 a seed is an optimisation: never keep the server from starting
+ print(f"kernel seed: not used ({type(exc).__name__}: {exc})", file=sys.stderr, flush=True)
+ return added
+ (log or (lambda s: print(s, file=sys.stderr, flush=True)))(
+ f"kernel seed: {added} Triton kernels from {seed.name} added to {cache} in {time.perf_counter() - t0:.1f} s")
+ return added
+
+
+def _llvm_objcopy() -> str:
+ """llvm-objcopy of a ROCm toolchain (GNU objcopy does not know the AMDGPU ELF machine)."""
+ for cand in (os.environ.get("LLVM_OBJCOPY"), shutil.which("llvm-objcopy")):
+ if cand and os.path.exists(cand):
+ return cand
+ roots = [os.environ.get("ROCM_PATH"), os.environ.get("EXL3_ROCM_SDK"), "/opt/rocm"]
+ try:
+ import _rocm_sdk_devel
+ roots.append(os.path.dirname(_rocm_sdk_devel.__file__))
+ except Exception: # noqa: BLE001
+ pass
+ for root in filter(None, roots):
+ for rel in ("lib/llvm/bin/llvm-objcopy", "llvm/bin/llvm-objcopy"):
+ if os.path.exists(os.path.join(root, rel)):
+ return os.path.join(root, rel)
+ raise RuntimeError("llvm-objcopy not found: set LLVM_OBJCOPY (it strips the debug sections of the code objects)")
+
+
+def _scrub_hsaco(data: bytes, objcopy: str) -> bytes:
+ """The code object without its debug sections: they hold the source path of the machine that built it."""
+ with tempfile.TemporaryDirectory() as td:
+ src, dst = Path(td) / "k.hsaco", Path(td) / "k.stripped.hsaco"
+ src.write_bytes(data)
+ subprocess.run([objcopy, "--strip-debug", str(src), str(dst)], check = True, capture_output = True)
+ return dst.read_bytes()
+
+
+def _scrub_json(data: bytes) -> bytes:
+ """Metadata with the library paths replaced by the placeholder (install() writes the live ones back)."""
+ return re.sub(rb'"[^"]*/backends/amd/lib/(ocml|ockl)\.bc"', b'"' + LIB_PLACEHOLDER.encode() + rb'/\1.bc"', data)
+
+
+def pack(cache, out: Path) -> int:
+ """Write the seed tar from one or several populated Triton caches (a key present in more than one: the first wins): per key
+ directory the code object (debug sections stripped) and its metadata (library paths replaced). Raises when a member still
+ holds a local path."""
+ caches = [Path(c) for c in ([cache] if isinstance(cache, (str, Path)) else cache)]
+ out = Path(out)
+ objcopy = None
+ n = 0
+ kdirs: dict = {}
+ for c in caches:
+ for p in c.iterdir():
+ if p.is_dir() and not p.name.startswith("."):
+ kdirs.setdefault(p.name, p)
+ with tarfile.open(out, "w:xz", preset=9) as tf:
+ for kdir in (kdirs[k] for k in sorted(kdirs)):
+ files = sorted(f for f in kdir.iterdir() if f.is_file() and (f.suffix in (".hsaco", ".json")) and not f.name.startswith("__grp__"))
+ if not any(f.suffix == ".hsaco" or f.name.endswith(".autotune.json") for f in files):
+ continue
+ for f in files:
+ data = f.read_bytes()
+ if f.suffix == ".hsaco":
+ objcopy = objcopy or _llvm_objcopy()
+ data = _scrub_hsaco(data, objcopy)
+ elif not f.name.endswith(".autotune.json"):
+ data = _scrub_json(data)
+ bad = _LOCAL_PATH.search(data)
+ if bad:
+ raise RuntimeError(f"{kdir.name}/{f.name}: still holds a local path ({data[bad.start():bad.start() + 60]!r})")
+ info = tarfile.TarInfo(f"{kdir.name}/{f.name}")
+ info.size, info.mtime, info.mode = len(data), 0, 0o644
+ info.uid = info.gid = 0
+ info.uname = info.gname = ""
+ tf.addfile(info, io.BytesIO(data))
+ n += 1
+ return n
diff --git a/exllamav3/vendor/fla/__init__.py b/exllamav3/vendor/fla/__init__.py
index 9c1eaf6..f249446 100644
--- a/exllamav3/vendor/fla/__init__.py
+++ b/exllamav3/vendor/fla/__init__.py
@@ -113,6 +113,9 @@ def chunk_gated_delta_rule_pf(q, k, v, g, beta, scale=None, initial_state=None,
return chunk_gdn_hf(q, v, qn, kn, g, beta, scale, initial_state, output_final_state, ckpt=ckpt)
except Exception as e:
print(f" -- EXL3_GDN_HF failed, Triton/HIP chain for the rest of the process: {e!r}", flush=True)
+ if isinstance(ckpt, (list, tuple)) and len(ckpt) > 2:
+ # the fused chain below side-writes 2 rows (the HF kernel above takes 8): keep the two deepest, the others stay unwritten
+ ckpt = sorted(ckpt, key = lambda c: c["chunk"])[-2:]
g = chunk_local_cumsum(g, chunk_size = chunk_size, scale = RCP_LN2)
if os.environ.get("EXL3_GDN_FUSE", "0") == "1":
from .gdn_fused import chunk_gdn_fused
diff --git a/exllamav3/vendor/fla/hip/gdn_hf.hip b/exllamav3/vendor/fla/hip/gdn_hf.hip
index 96345c6..5221f96 100644
--- a/exllamav3/vendor/fla/hip/gdn_hf.hip
+++ b/exllamav3/vendor/fla/hip/gdn_hf.hip
@@ -64,6 +64,9 @@ extern "C" __global__ void gated_delta_chunk_gate_wmma(
int rows, int qkv_width, int key_heads, int value_heads, float query_scale, int output_bf16
#ifdef KYO_RAW
, float* __restrict__ ck0, int ck_row0, float* __restrict__ ck1, int ck_row1 // state entering row ck_row* (multiple of 16), or row -1
+ , float* __restrict__ ck2, int ck_row2, float* __restrict__ ck3, int ck_row3
+ , float* __restrict__ ck4, int ck_row4, float* __restrict__ ck5, int ck_row5
+ , float* __restrict__ ck6, int ck_row6, float* __restrict__ ck7, int ck_row7 // 8 slots: dense prompt-tail checkpoints
#endif
#ifdef NPU_TRUNK_ARENA
, int z_pitch, int z_col0
@@ -273,8 +276,10 @@ extern "C" __global__ void gated_delta_chunk_gate_wmma(
}
GC_BARRIER(); // chunk inputs consumed; out_s complete
#ifdef KYO_RAW
- if (t0 + 16 == ck_row0 || t0 + 16 == ck_row1) { // prefix-cache checkpoint: S after this chunk = state entering row t0 + 16
- float* ck = t0 + 16 == ck_row0 ? ck0 : ck1;
+ const int tn = t0 + 16;
+ float* ck = tn == ck_row0 ? ck0 : tn == ck_row1 ? ck1 : tn == ck_row2 ? ck2 : tn == ck_row3 ? ck3 :
+ tn == ck_row4 ? ck4 : tn == ck_row5 ? ck5 : tn == ck_row6 ? ck6 : tn == ck_row7 ? ck7 : nullptr;
+ if (ck != nullptr) { // prefix-cache checkpoint: S after this chunk = state entering row t0 + 16
#pragma unroll
for (int t = 0; t < 8; ++t)
#pragma unroll
diff --git a/exllamav3/vendor/fla/hip/gdn_hf_hip.py b/exllamav3/vendor/fla/hip/gdn_hf_hip.py
index 81441a0..fee3308 100644
--- a/exllamav3/vendor/fla/hip/gdn_hf_hip.py
+++ b/exllamav3/vendor/fla/hip/gdn_hf_hip.py
@@ -61,7 +61,7 @@ def gdn_hf_ok(q_raw, v, qn, kn, g, beta, initial_state):
def chunk_gdn_hf(q_raw, v, qn, kn, g, beta, scale, initial_state, output_final_state, ckpt=None):
- """Returns (o [1, T, HV, 128] bf16, final_state or None). ckpt: None, a dict or a list of <= 2 dicts {"s": fp32 [1, HV, K, V]
+ """Returns (o [1, T, HV, 128] bf16, final_state or None). ckpt: None, a dict or a list of <= 8 dicts {"s": fp32 [1, HV, K, V]
contiguous, "chunk": n} (gdn_fused_h_hip contract): the state after row 64 n is written to ck["s"] and ck["ok"] set."""
try:
fn = _load()
@@ -81,10 +81,10 @@ def chunk_gdn_hf(q_raw, v, qn, kn, g, beta, scale, initial_state, output_final_s
ctypes.c_float(scale), ctypes.c_int(1)]
cks = [] if ckpt is None else (list(ckpt) if isinstance(ckpt, (list, tuple)) else [ckpt])
cks = [c for c in cks if 0 < 64 * c["chunk"] <= T]
- assert len(cks) <= 2
+ assert len(cks) <= 8
for c in cks:
assert c["s"].dtype == torch.float32 and c["s"].is_contiguous() and c["s"].shape == (1, HV, K, K)
- for i in range(2):
+ for i in range(8):
c = cks[i] if i < len(cks) else None
args += [P(0 if c is None else c["s"].data_ptr()), ctypes.c_int(-1 if c is None else 64 * c["chunk"])]
params = (ctypes.c_void_p * len(args))(*[ctypes.cast(ctypes.byref(a), ctypes.c_void_p) for a in args])
diff --git a/exllamav3/vendor/fla/hip/kda_fused_h.hip b/exllamav3/vendor/fla/hip/kda_fused_h.hip
index 7b35a27..aca4924 100644
--- a/exllamav3/vendor/fla/hip/kda_fused_h.hip
+++ b/exllamav3/vendor/fla/hip/kda_fused_h.hip
@@ -159,6 +159,9 @@ __device__ uint32_t kda_prof[4096 * 9];
#ifndef CK4
#define CK4 0
#endif
+#ifndef CK8
+#define CK8 0 // 1: eight side-write slots (dense prompt-tail checkpoints); implies the CK4 slots
+#endif
extern "C" __global__ __launch_bounds__(PFW ? 288 : 256) void kda_fused_h_o(
const uint16_t* __restrict__ q, const uint16_t* __restrict__ k, const uint16_t* __restrict__ v,
@@ -166,8 +169,12 @@ extern "C" __global__ __launch_bounds__(PFW ? 288 : 256) void kda_fused_h_o(
const uint16_t* __restrict__ Aqk, uint16_t* __restrict__ o, const float* __restrict__ h0,
float* __restrict__ ht, float scale, int T, int H, int HV, float* __restrict__ hc, int ckpt_chunk,
float* __restrict__ hc2, int ckpt_chunk2
-#if CK4
+#if CK4 || CK8
, float* __restrict__ hc3, int ckpt_chunk3, float* __restrict__ hc4, int ckpt_chunk4
+#endif
+#if CK8
+ , float* __restrict__ hc5, int ckpt_chunk5, float* __restrict__ hc6, int ckpt_chunk6
+ , float* __restrict__ hc7, int ckpt_chunk7, float* __restrict__ hc8, int ckpt_chunk8
#endif
)
{
@@ -587,7 +594,7 @@ extern "C" __global__ __launch_bounds__(PFW ? 288 : 256) void kda_fused_h_o(
#pragma unroll
for (int r = 0; r < 8; ++r)
hc2[(int64_t) i_nh * KD * VD + (16 * kt + 2 * r + half) * VD + col] = h[kt][r];
-#if CK4
+#if CK4 || CK8
// third and fourth checkpoints (EXL3_NC2_CKPT4: 8192-row chunks), same store as above
if (hc3 && i_t + 1 == ckpt_chunk3)
#pragma unroll
@@ -601,6 +608,33 @@ extern "C" __global__ __launch_bounds__(PFW ? 288 : 256) void kda_fused_h_o(
#pragma unroll
for (int r = 0; r < 8; ++r)
hc4[(int64_t) i_nh * KD * VD + (16 * kt + 2 * r + half) * VD + col] = h[kt][r];
+#endif
+#if CK8
+ // slots five to eight (dense prompt-tail checkpoints), same store
+ if (hc5 && i_t + 1 == ckpt_chunk5)
+ #pragma unroll
+ for (int kt = 0; kt < 8; ++kt)
+ #pragma unroll
+ for (int r = 0; r < 8; ++r)
+ hc5[(int64_t) i_nh * KD * VD + (16 * kt + 2 * r + half) * VD + col] = h[kt][r];
+ if (hc6 && i_t + 1 == ckpt_chunk6)
+ #pragma unroll
+ for (int kt = 0; kt < 8; ++kt)
+ #pragma unroll
+ for (int r = 0; r < 8; ++r)
+ hc6[(int64_t) i_nh * KD * VD + (16 * kt + 2 * r + half) * VD + col] = h[kt][r];
+ if (hc7 && i_t + 1 == ckpt_chunk7)
+ #pragma unroll
+ for (int kt = 0; kt < 8; ++kt)
+ #pragma unroll
+ for (int r = 0; r < 8; ++r)
+ hc7[(int64_t) i_nh * KD * VD + (16 * kt + 2 * r + half) * VD + col] = h[kt][r];
+ if (hc8 && i_t + 1 == ckpt_chunk8)
+ #pragma unroll
+ for (int kt = 0; kt < 8; ++kt)
+ #pragma unroll
+ for (int r = 0; r < 8; ++r)
+ hc8[(int64_t) i_nh * KD * VD + (16 * kt + 2 * r + half) * VD + col] = h[kt][r];
#endif
}
diff --git a/exllamav3/vendor/fla/hip/kda_fused_h_hip.py b/exllamav3/vendor/fla/hip/kda_fused_h_hip.py
index 4b1c8e1..1c85cc2 100644
--- a/exllamav3/vendor/fla/hip/kda_fused_h_hip.py
+++ b/exllamav3/vendor/fla/hip/kda_fused_h_hip.py
@@ -2,7 +2,7 @@
# ROCm SDK hipcc on first use (cached by source hash) and launches it through torch's own libamdhip64 via
# hipModuleLaunchKernel on the current torch stream: no extension rebuild, no second HIP runtime.
-import ctypes, hashlib, os, shutil, subprocess
+import ctypes, hashlib, os, shutil, subprocess, threading
import torch
from exllamav3.util import hip_compiler
from exllamav3.util.hip_lib import load_hip_runtime
@@ -26,17 +26,40 @@ def _compile(defs, arch):
cache = os.path.join(os.path.expanduser("~/.cache/exllamav3"), f"kda_fused_h_{arch}_{tag}.hsaco")
if not os.path.isfile(cache):
os.makedirs(os.path.dirname(cache), exist_ok=True)
- tmp = cache + f".{os.getpid()}.tmp"
+ tmp = cache + f".{os.getpid()}.{threading.get_ident()}.tmp"
subprocess.run([_hipcc(), *flags, "-o", tmp, _SRC], check=True, capture_output=True)
os.replace(tmp, cache)
return cache
+_CK = ("CK4=1", "CK8=1")
+
+
+def _siblings(defs):
+ """The builds that differ from `defs` only in the checkpoint-slot count (2 slots: none, 4: CK4, 8: CK8)."""
+ base = " ".join(t for t in defs.split() if t not in _CK)
+ return [d for d in [base] + [f"{base} {t}".strip() for t in _CK] if d.split() != defs.split()]
+
+
+def _precompile_siblings(defs, arch):
+ # The number of checkpoint rows of a request picks the build. A prefill chunk and a short prompt tail use different
+ # ones, so the first re-sent prompt would run hipcc (about 2.5 s) inside its own time to first token. Build the
+ # others now, off the request path; a failure is not an error (the build then happens on first use as before).
+ def run():
+ for d in _siblings(defs):
+ try:
+ _compile(d, arch)
+ except Exception: # noqa: BLE001
+ return
+ threading.Thread(target=run, name="kda-fused-h-precompile", daemon=True).start()
+
+
def _load(defs=""):
# defs: extra -D defines (timing experiments only, e.g. "ABL=4"); one module per defines string
if defs in _state:
return _state[defs]
- cache = _compile(defs, torch.cuda.get_device_properties(0).gcnArchName.split(":")[0])
+ arch = torch.cuda.get_device_properties(0).gcnArchName.split(":")[0]
+ cache = _compile(defs, arch)
lib = load_hip_runtime()
torch.cuda.init()
mod, fn = ctypes.c_void_p(), ctypes.c_void_p()
@@ -48,6 +71,10 @@ def _load(defs=""):
_state["lib"] = lib
_state[defs] = fn
_state["mod", defs] = mod
+ base = " ".join(t for t in defs.split() if t not in _CK)
+ if ("pre", base) not in _state:
+ _state["pre", base] = True
+ _precompile_siblings(defs, arch)
return fn
@@ -75,13 +102,15 @@ def chunk_kda_fwd_h_fused_hip(q, k, v, gk, beta, Akk, Aqk, scale, initial_state=
# default off. Name kept per brief; the 2-WG split (lever a) was ruled NO-GO by
# construction (w/tril/vn couple all halves).
defs = "BRL=1 UNI=1"
- # ckpt: one dict or a list of up to 2 (EXL3_PF_NO_TAIL adds the prompt's last full page); up to 4 with the CK4 build
+ # ckpt: one dict or a list of up to 2 (EXL3_PF_NO_TAIL adds the prompt's last full page); up to 4 with the CK4 build, up to 8 with the CK8 build
# (EXL3_NC2_CKPT4: an 8192-row chunk carries 3 interior checkpoints + the last full page)
cks = [] if ckpt is None else (list(ckpt) if isinstance(ckpt, (list, tuple)) else [ckpt])
- nslot = 4 if len(cks) > 2 else 2
+ nslot = 8 if len(cks) > 4 else 4 if len(cks) > 2 else 2
assert len(cks) <= nslot
if nslot == 4:
defs = (defs + " CK4=1").strip()
+ elif nslot == 8:
+ defs = (defs + " CK8=1").strip()
fn = _load(defs)
if o is None:
o = torch.empty_like(v)
diff --git a/exllamav3/version.py b/exllamav3/version.py
index b4eda42..16c83d8 100644
--- a/exllamav3/version.py
+++ b/exllamav3/version.py
@@ -1 +1 @@
-__version__ = "1.5.10"
\ No newline at end of file
+__version__ = "1.7.0"
\ No newline at end of file
diff --git a/pyproject.toml b/pyproject.toml
index 3f21b14..f7f5608 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -106,6 +106,8 @@ include = ["exllamav3*"]
exllamav3 = [
"py.typed",
"util/hadamard_data/*",
+ "kernel_seed/*.tar.xz",
+ "model/dense_gemm_tune_seed.txt",
"conversion/standard_cal_data/*.utf8",
"exllamav3_ext/**/*",
"**/*.hip",
diff --git a/setup.py b/setup.py
index cb207af..d6aa072 100644
--- a/setup.py
+++ b/setup.py
@@ -32,6 +32,11 @@ else:
"-Xcudafe", "--diag_suppress=177",
"-Xcudafe", "--diag_suppress=20012",
]
+ # EXL3_PORT_DEC=1 at build time compiles the HIP decode kernels (quant/exl3_dec.cu) for CUDA too
+ # (see port.cuh); they are bound only when EXL3_PORT_DEC=1 at import as well.
+ if os.environ.get("EXL3_PORT_DEC", "0") == "1":
+ extra_cuda_cflags += ["-DEXL3_PORT_DEC"]
+ extra_cflags += ["-DEXL3_PORT_DEC"]
if windows:
# NOMINMAX: windows.h otherwise defines min/max function-like macros that break every
diff --git a/tests/foreign_quant_oracle/dequant_oracle.c b/tests/foreign_quant_oracle/dequant_oracle.c
new file mode 100644
index 0000000..2242ed7
--- /dev/null
+++ b/tests/foreign_quant_oracle/dequant_oracle.c
@@ -0,0 +1,215 @@
+/* Independent dequant oracle for the foreign_quant CPU tests.
+ *
+ * dequantize_row_q8_0 / dequantize_row_iq2_xxs below are verbatim ports of
+ * llama.cpp ggml/src/ggml-quants.c (MIT License, Copyright (c) the llama.cpp
+ * contributors, https://github.com/ggml-org/llama.cpp), with GGML_RESTRICT
+ * dropped and GGML_FP16_TO_FP32 spelled out as fp16_to_fp32 (exact IEEE-754
+ * conversion). Tables iq2xxs_grid / ksigns_iq2xs / kmask_iq2xs are verbatim
+ * from llama.cpp ggml/src/ggml-common.h.
+ *
+ * Usage: dequant_oracle (q8_0 | iq2_xxs | fp16) <raw-bytes-file>
+ * Prints one IEEE-754 bit pattern per decoded value ("%08x" per line).
+ */
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+
+#define QK_K 256
+#define QK8_0 32
+
+typedef struct { uint16_t d; int8_t qs[QK8_0]; } block_q8_0;
+typedef struct { uint16_t d; uint16_t qs[QK_K/8]; } block_iq2_xxs;
+
+static const uint8_t kmask_iq2xs[8] = { 1, 2, 4, 8, 16, 32, 64, 128 };
+
+static const uint8_t ksigns_iq2xs[128] = {
+ 0, 129, 130, 3, 132, 5, 6, 135, 136, 9, 10, 139, 12, 141, 142, 15,
+ 144, 17, 18, 147, 20, 149, 150, 23, 24, 153, 154, 27, 156, 29, 30, 159,
+ 160, 33, 34, 163, 36, 165, 166, 39, 40, 169, 170, 43, 172, 45, 46, 175,
+ 48, 177, 178, 51, 180, 53, 54, 183, 184, 57, 58, 187, 60, 189, 190, 63,
+ 192, 65, 66, 195, 68, 197, 198, 71, 72, 201, 202, 75, 204, 77, 78, 207,
+ 80, 209, 210, 83, 212, 85, 86, 215, 216, 89, 90, 219, 92, 221, 222, 95,
+ 96, 225, 226, 99, 228, 101, 102, 231, 232, 105, 106, 235, 108, 237, 238, 111,
+ 240, 113, 114, 243, 116, 245, 246, 119, 120, 249, 250, 123, 252, 125, 126, 255,
+};
+
+static const uint64_t iq2xxs_grid[256] = {
+ 0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08,
+ 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x08080808082b0808,
+ 0x08080808082b082b, 0x08080808082b2b08, 0x08080808082b2b2b, 0x0808080819080819,
+ 0x0808080819081908, 0x0808080819190808, 0x0808080819192b08, 0x08080808192b0819,
+ 0x08080808192b1908, 0x080808082b080808, 0x080808082b08082b, 0x080808082b082b2b,
+ 0x080808082b2b082b, 0x0808081908080819, 0x0808081908081908, 0x0808081908190808,
+ 0x0808081908191919, 0x0808081919080808, 0x080808192b081908, 0x080808192b192b08,
+ 0x0808082b08080808, 0x0808082b0808082b, 0x0808082b082b082b, 0x0808082b2b08082b,
+ 0x0808190808080819, 0x0808190808081908, 0x0808190808190808, 0x08081908082b0819,
+ 0x08081908082b1908, 0x0808190819080808, 0x080819081908082b, 0x0808190819082b08,
+ 0x08081908192b0808, 0x080819082b080819, 0x080819082b081908, 0x080819082b190808,
+ 0x080819082b2b1908, 0x0808191908080808, 0x080819190808082b, 0x0808191908082b08,
+ 0x08081919082b0808, 0x080819191908192b, 0x08081919192b2b19, 0x080819192b080808,
+ 0x080819192b190819, 0x0808192b08082b19, 0x0808192b08190808, 0x0808192b19080808,
+ 0x0808192b2b081908, 0x0808192b2b2b1908, 0x08082b0808080808, 0x08082b0808081919,
+ 0x08082b0808082b08, 0x08082b0808191908, 0x08082b08082b2b08, 0x08082b0819080819,
+ 0x08082b0819081908, 0x08082b0819190808, 0x08082b081919082b, 0x08082b082b082b08,
+ 0x08082b1908081908, 0x08082b1919080808, 0x08082b2b0808082b, 0x08082b2b08191908,
+ 0x0819080808080819, 0x0819080808081908, 0x0819080808190808, 0x08190808082b0819,
+ 0x0819080819080808, 0x08190808192b0808, 0x081908082b081908, 0x081908082b190808,
+ 0x081908082b191919, 0x0819081908080808, 0x0819081908082b08, 0x08190819082b0808,
+ 0x0819081919190808, 0x0819081919192b2b, 0x081908192b080808, 0x0819082b082b1908,
+ 0x0819082b19081919, 0x0819190808080808, 0x0819190808082b08, 0x08191908082b0808,
+ 0x08191908082b1919, 0x0819190819082b19, 0x081919082b080808, 0x0819191908192b08,
+ 0x08191919192b082b, 0x0819192b08080808, 0x0819192b0819192b, 0x08192b0808080819,
+ 0x08192b0808081908, 0x08192b0808190808, 0x08192b0819080808, 0x08192b082b080819,
+ 0x08192b1908080808, 0x08192b1908081919, 0x08192b192b2b0808, 0x08192b2b19190819,
+ 0x082b080808080808, 0x082b08080808082b, 0x082b080808082b2b, 0x082b080819081908,
+ 0x082b0808192b0819, 0x082b08082b080808, 0x082b08082b08082b, 0x082b0819082b2b19,
+ 0x082b081919082b08, 0x082b082b08080808, 0x082b082b0808082b, 0x082b190808080819,
+ 0x082b190808081908, 0x082b190808190808, 0x082b190819080808, 0x082b19081919192b,
+ 0x082b191908080808, 0x082b191919080819, 0x082b1919192b1908, 0x082b192b2b190808,
+ 0x082b2b0808082b08, 0x082b2b08082b0808, 0x082b2b082b191908, 0x082b2b2b19081908,
+ 0x1908080808080819, 0x1908080808081908, 0x1908080808190808, 0x1908080808192b08,
+ 0x19080808082b0819, 0x19080808082b1908, 0x1908080819080808, 0x1908080819082b08,
+ 0x190808081919192b, 0x19080808192b0808, 0x190808082b080819, 0x190808082b081908,
+ 0x190808082b190808, 0x1908081908080808, 0x19080819082b0808, 0x19080819192b0819,
+ 0x190808192b080808, 0x190808192b081919, 0x1908082b08080819, 0x1908082b08190808,
+ 0x1908082b19082b08, 0x1908082b1919192b, 0x1908082b192b2b08, 0x1908190808080808,
+ 0x1908190808082b08, 0x19081908082b0808, 0x190819082b080808, 0x190819082b192b19,
+ 0x190819190819082b, 0x19081919082b1908, 0x1908192b08080808, 0x19082b0808080819,
+ 0x19082b0808081908, 0x19082b0808190808, 0x19082b0819080808, 0x19082b0819081919,
+ 0x19082b1908080808, 0x19082b1919192b08, 0x19082b19192b0819, 0x19082b192b08082b,
+ 0x19082b2b19081919, 0x19082b2b2b190808, 0x1919080808080808, 0x1919080808082b08,
+ 0x1919080808190819, 0x1919080808192b19, 0x19190808082b0808, 0x191908082b080808,
+ 0x191908082b082b08, 0x1919081908081908, 0x191908191908082b, 0x191908192b2b1908,
+ 0x1919082b2b190819, 0x191919082b190808, 0x191919082b19082b, 0x1919191908082b2b,
+ 0x1919192b08080819, 0x1919192b19191908, 0x19192b0808080808, 0x19192b0808190819,
+ 0x19192b0808192b19, 0x19192b08192b1908, 0x19192b1919080808, 0x19192b2b08082b08,
+ 0x192b080808081908, 0x192b080808190808, 0x192b080819080808, 0x192b0808192b2b08,
+ 0x192b081908080808, 0x192b081919191919, 0x192b082b08192b08, 0x192b082b192b0808,
+ 0x192b190808080808, 0x192b190808081919, 0x192b191908190808, 0x192b19190819082b,
+ 0x192b19192b081908, 0x192b2b081908082b, 0x2b08080808080808, 0x2b0808080808082b,
+ 0x2b08080808082b2b, 0x2b08080819080819, 0x2b0808082b08082b, 0x2b08081908081908,
+ 0x2b08081908192b08, 0x2b08081919080808, 0x2b08082b08190819, 0x2b08190808080819,
+ 0x2b08190808081908, 0x2b08190808190808, 0x2b08190808191919, 0x2b08190819080808,
+ 0x2b081908192b0808, 0x2b08191908080808, 0x2b0819191908192b, 0x2b0819192b191908,
+ 0x2b08192b08082b19, 0x2b08192b19080808, 0x2b08192b192b0808, 0x2b082b080808082b,
+ 0x2b082b1908081908, 0x2b082b2b08190819, 0x2b19080808081908, 0x2b19080808190808,
+ 0x2b190808082b1908, 0x2b19080819080808, 0x2b1908082b2b0819, 0x2b1908190819192b,
+ 0x2b1908192b080808, 0x2b19082b19081919, 0x2b19190808080808, 0x2b191908082b082b,
+ 0x2b19190819081908, 0x2b19191919190819, 0x2b192b082b080819, 0x2b192b19082b0808,
+ 0x2b2b08080808082b, 0x2b2b080819190808, 0x2b2b08082b081919, 0x2b2b081908082b19,
+ 0x2b2b082b08080808, 0x2b2b190808192b08, 0x2b2b2b0819190808, 0x2b2b2b1908081908,
+};
+
+static float fp16_to_fp32(uint16_t h) {
+ uint32_t sign = ((uint32_t)(h & 0x8000)) << 16;
+ int exp = (h >> 10) & 0x1F;
+ uint32_t mant = h & 0x3FF;
+ uint32_t f;
+ if (exp == 0) {
+ if (mant == 0) {
+ f = sign;
+ } else {
+ exp = 1;
+ while (!(mant & 0x400)) { mant <<= 1; exp--; }
+ mant &= 0x3FF;
+ f = sign | ((uint32_t)(exp + 112) << 23) | (mant << 13);
+ }
+ } else if (exp == 31) {
+ f = sign | 0x7F800000 | (mant << 13);
+ } else {
+ f = sign | ((uint32_t)(exp + 112) << 23) | (mant << 13);
+ }
+ float out;
+ memcpy(&out, &f, sizeof(out));
+ return out;
+}
+
+static void dequantize_row_q8_0(const block_q8_0 * x, float * y, int64_t k) {
+ static const int qk = QK8_0;
+ assert(k % qk == 0);
+ const int nb = (int)(k / qk);
+ for (int i = 0; i < nb; i++) {
+ const float d = fp16_to_fp32(x[i].d);
+ for (int j = 0; j < qk; ++j) {
+ y[i*qk + j] = x[i].qs[j]*d;
+ }
+ }
+}
+
+static void dequantize_row_iq2_xxs(const block_iq2_xxs * x, float * y, int64_t k) {
+ assert(k % QK_K == 0);
+ const int64_t nb = k / QK_K;
+
+ uint32_t aux32[2];
+ const uint8_t * aux8 = (const uint8_t *)aux32;
+
+ for (int i = 0; i < nb; i++) {
+
+ const float d = fp16_to_fp32(x[i].d);
+
+ for (int ib32 = 0; ib32 < QK_K/32; ++ib32) {
+ memcpy(aux32, x[i].qs + 4*ib32, 2*sizeof(uint32_t));
+ const float db = d * (0.5f + (aux32[1] >> 28)) * 0.25f;
+ for (int l = 0; l < 4; ++l) {
+ const uint8_t * grid = (const uint8_t *)(iq2xxs_grid + aux8[l]);
+ const uint8_t signs = ksigns_iq2xs[(aux32[1] >> 7*l) & 127];
+ for (int j = 0; j < 8; ++j) {
+ y[j] = db * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f);
+ }
+ y += 8;
+ }
+ }
+ }
+}
+
+static void print_bits(const float * y, int64_t n) {
+ for (int64_t i = 0; i < n; i++) {
+ uint32_t b;
+ memcpy(&b, &y[i], sizeof(b));
+ printf("%08x\n", b);
+ }
+}
+
+int main(int argc, char ** argv) {
+ if (argc != 3) { fprintf(stderr, "usage: %s (q8_0|iq2_xxs|fp16) file\n", argv[0]); return 2; }
+ const char * mode = argv[1];
+ FILE * f = fopen(argv[2], "rb");
+ if (!f) { perror("fopen"); return 1; }
+ fseek(f, 0, SEEK_END);
+ long size = ftell(f);
+ fseek(f, 0, SEEK_SET);
+ uint8_t * buf = malloc(size ? size : 1);
+ if (fread(buf, 1, size, f) != (size_t)size) { perror("fread"); return 1; }
+ fclose(f);
+
+ if (!strcmp(mode, "q8_0")) {
+ assert(size % 34 == 0);
+ float * y = malloc(size / 34 * 32 * sizeof(float));
+ dequantize_row_q8_0((const block_q8_0 *)buf, y, size / 34 * 32);
+ print_bits(y, size / 34 * 32);
+ free(y);
+ } else if (!strcmp(mode, "iq2_xxs")) {
+ assert(size % 66 == 0);
+ float * y = malloc(size / 66 * 256 * sizeof(float));
+ dequantize_row_iq2_xxs((const block_iq2_xxs *)buf, y, size / 66 * 256);
+ print_bits(y, size / 66 * 256);
+ free(y);
+ } else if (!strcmp(mode, "fp16")) {
+ assert(size % 2 == 0);
+ for (long i = 0; i < size / 2; i++) {
+ uint16_t h;
+ memcpy(&h, buf + 2*i, 2);
+ float v = fp16_to_fp32(h);
+ uint32_t b;
+ memcpy(&b, &v, 4);
+ printf("%08x\n", b);
+ }
+ } else {
+ fprintf(stderr, "unknown mode %s\n", mode);
+ return 2;
+ }
+ free(buf);
+ return 0;
+}
diff --git a/tests/port/bench_cuda_graph.py b/tests/port/bench_cuda_graph.py
new file mode 100644
index 0000000..9ed7dc3
--- /dev/null
+++ b/tests/port/bench_cuda_graph.py
@@ -0,0 +1,96 @@
+# Whole-forward CUDA graph bench/check (Qwen3-MoE, B=1 plain decode). Needs a GPU; not run by CI.
+# usage: python -I bench_cuda_graph.py ENGINE_DIR MODEL_DIR OUT.json [NEW_TOKENS]
+# Arms in one process, same load: eager, graph, eager, graph (module flag flipped + purge between arms).
+# Per arm and prompt: decode tok/s (smoke_qwen.py method), token stream. Asserts graph stream == eager stream, and
+# compares the logits returned by model.forward on the first LOGIT_STEPS decode steps (separate untimed pass).
+import sys, os, time, json
+eng, mdir, out = sys.argv[1], sys.argv[2], sys.argv[3]; NEW = int(sys.argv[4]) if len(sys.argv) > 4 else 256
+LOGIT_STEPS = 16
+sys.path.insert(0, eng)
+import torch
+from exllamav3 import Config, Model, Cache, Tokenizer, Generator, Job
+from exllamav3.generator.sampler import ArgmaxSampler
+from exllamav3.model import cuda_graph as cg
+import exllamav3
+
+res = {"engine": exllamav3.__file__, "model": mdir, "env": {k: v for k, v in os.environ.items() if k.startswith("EXL3_")},
+ "arms": [], "new_tokens": NEW}
+cfg = Config.from_directory(mdir); model = Model.from_config(cfg)
+cache = Cache(model, max_num_tokens=8192, max_batch_size=1); model.load(); tok = Tokenizer.from_config(cfg)
+gen = Generator(model=model, cache=cache, tokenizer=tok)
+S = ArgmaxSampler()
+pl = os.environ["PROMPT_LONG"] # a long text file (summary prompt)
+base = open(pl).read()
+prompts = [
+ "<|im_start|>user\nWrite a short story about a lighthouse keeper who finds a message in a bottle.<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n",
+ "<|im_start|>user\nWrite a Python function that parses an ISO 8601 date string without using datetime, with tests.<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n",
+ "<|im_start|>user\nSummarise the following text in five bullet points:\n" + base + "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n",
+]
+
+def run(ids, new):
+ job = Job(input_ids=ids, max_new_tokens=new, sampler=S, stop_conditions=[])
+ torch.cuda.synchronize(); t0 = time.time(); tf = None; o = []
+ gen.enqueue(job)
+ while gen.num_remaining_jobs():
+ for r in gen.iterate():
+ if r.get("stage") == "streaming":
+ t = r.get("token_ids")
+ if t is not None and t.numel():
+ if tf is None: torch.cuda.synchronize(); tf = time.time()
+ o += t.flatten().tolist()
+ torch.cuda.synchronize(); te = time.time()
+ return o, tf - t0, te - tf
+
+# logits recorder around Model.forward (decode calls only; prefill does not go through forward)
+rec = None
+_orig_forward = model.forward
+def _fwd(input_ids, params=None):
+ y = _orig_forward(input_ids, params)
+ if rec is not None and len(rec) < LOGIT_STEPS:
+ rec.append(y.detach().float().cpu().clone())
+ return y
+model.forward = _fwd
+
+def arm(name, graph):
+ global rec
+ cg.purge(); cg.CUDA_GRAPH_ENABLED = graph
+ stats0 = None
+ a = {"arm": name, "graph": graph, "prompts": [], "logits": []}
+ run(tok.encode("Hello, warm-up."), 16)
+ for p in prompts:
+ ids = tok.encode(p)
+ run(ids, 8) # warm this prompt's block-table width (graph arm: warmups + capture)
+ o, tp, td = run(ids, NEW)
+ a["prompts"].append({"n_in": ids.shape[-1], "decode_tps": (len(o) - 1) / td, "decode_s": td, "ttft_s": tp, "ids": o})
+ print(json.dumps({"arm": name, "n_in": ids.shape[-1], "decode_tps": round((len(o) - 1) / td, 2)}), flush=True)
+ rec = []; run(ids, LOGIT_STEPS + 1); a["logits"].append(rec); rec = None
+ r = model.__dict__.get("_cuda_graph_runner")
+ if graph and r is not None:
+ a["graph_stats"] = {k: (dict(v) if isinstance(v, dict) or hasattr(v, "items") else v) for k, v in r.stats.items()}
+ print(json.dumps({"graph_stats": a["graph_stats"]}), flush=True)
+ res["arms"].append(a)
+ return a
+
+arms = [arm("eager1", False), arm("graph1", True), arm("eager2", False), arm("graph2", True)]
+cg.purge()
+
+ok = True
+res["checks"] = []
+for ea, ga in ((arms[0], arms[1]), (arms[2], arms[3]), (arms[0], arms[2]), (arms[1], arms[3])):
+ for i, (pe, pg) in enumerate(zip(ea["prompts"], ga["prompts"])):
+ a_, b_ = pe["ids"], pg["ids"]
+ div = next((j for j, (u, v) in enumerate(zip(a_, b_)) if u != v), None)
+ if div is None and len(a_) != len(b_): div = min(len(a_), len(b_))
+ md = max((float((x - y).abs().max()) if x.shape == y.shape else float("inf")) for x, y in zip(ea["logits"][i], ga["logits"][i])) \
+ if ea["logits"][i] else None
+ c = {"a": ea["arm"], "b": ga["arm"], "prompt": i, "first_divergence": div, "logits_max_abs_diff": md,
+ "n_logit_steps": len(ea["logits"][i])}
+ res["checks"].append(c); print(json.dumps(c), flush=True)
+ if div is not None or md not in (0.0,): ok = False
+for a in arms: a.pop("logits")
+for name, sel in (("eager", (0, 2)), ("graph", (1, 3))):
+ res[f"mean_tps_{name}"] = [sum(arms[k]["prompts"][i]["decode_tps"] for k in sel) / 2 for i in range(len(prompts))]
+res["identical"] = ok
+json.dump(res, open(out, "w"), indent=1)
+print(json.dumps({k: res[k] for k in ("mean_tps_eager", "mean_tps_graph", "identical")}), flush=True)
+assert ok, "graph != eager (see checks)"
diff --git a/tests/port/bench_cuda_graph_multi.py b/tests/port/bench_cuda_graph_multi.py
new file mode 100644
index 0000000..9e06eaf
--- /dev/null
+++ b/tests/port/bench_cuda_graph_multi.py
@@ -0,0 +1,115 @@
+# Multi-job whole-forward CUDA graph check/bench (EXL3_CUDA_GRAPH_MULTI), Qwen3.8-27B + DFlash2 drafter. Needs a GPU; not run by CI.
+# usage: python -I bench_cuda_graph_multi.py ENGINE_DIR [OUT.json] [NEW_TOKENS=128]
+# env: BENCH_MODEL (required: target model dir), BENCH_DRAFT (required: DFlash2 drafter dir), BENCH_NDRAFT (7),
+# BENCH_BS ("2,4"), BENCH_ROUNDS (2 = off/on/off/on)
+# One process, one load. Arm "off" = runner enabled, MULTI off (B>1 declines to eager); arm "on" = MULTI on, via
+# cuda_graph.set_multi() + purge() between arms. For B in BENCH_BS: B concurrent greedy jobs (distinct short prompts,
+# NEW tokens each, DFlash2 verify Q=1+NDRAFT).
+# (a) every job's token ids must be identical in all arms (+ runner stats incl. declines by reason),
+# (b) aggregate tok/s per arm, interleaved off/on/off/on, (c) logits of the first LOGIT_STEPS model.forward calls (the
+# batches are identical step by step when the streams are, so graph vs eager logits are comparable): max abs diff.
+# Prints JSON lines; exit code 1 if tokens or logits differ.
+import sys, os, time, json
+eng = sys.argv[1]; out = sys.argv[2] if len(sys.argv) > 2 else None; NEW = int(sys.argv[3]) if len(sys.argv) > 3 else 128
+sys.path.insert(0, eng)
+os.environ["EXL3_CUDA_GRAPH"] = "1"
+import torch
+from exllamav3 import Config, Model, Cache, Tokenizer, Generator, Job
+from exllamav3.generator.sampler import ArgmaxSampler
+from exllamav3.model import cuda_graph as cg
+import exllamav3
+
+MDIR = os.environ["BENCH_MODEL"]
+DFL = os.environ["BENCH_DRAFT"]
+ND = int(os.environ.get("BENCH_NDRAFT", "7"))
+BS = [int(b) for b in os.environ.get("BENCH_BS", "2,4").split(",")]
+ROUNDS = int(os.environ.get("BENCH_ROUNDS", "2"))
+LOGIT_STEPS = 24
+P = lambda d: print(json.dumps(d), flush = True)
+res = {"engine": exllamav3.__file__, "model": MDIR, "draft": DFL, "num_draft_tokens": ND, "new_tokens": NEW,
+ "env": {k: v for k, v in os.environ.items() if k.startswith("EXL3") or k.startswith("EXLLAMAV3")}, "arms": []}
+
+cfg = Config.from_directory(MDIR); model = Model.from_config(cfg)
+cache = Cache(model, max_num_tokens = 8192, max_batch_size = max(BS), max_history = max(3, ND))
+model.load(); tok = Tokenizer.from_config(cfg)
+dcfg = Config.from_directory(DFL); dm = Model.from_config(dcfg); dc = Cache(dm, max_num_tokens = 16 * 256); dm.load()
+dc.max_num_tokens = 8192 # ring cache as in a served drafter: the generator only compares sizes
+gen = Generator(model = model, cache = cache, tokenizer = tok, draft_model = dm, draft_cache = dc, num_draft_tokens = ND)
+S = ArgmaxSampler()
+Q = lambda s: "<|im_start|>user\n" + s + "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
+prompts = [Q(s) for s in (
+ "Write a short story about a lighthouse keeper who finds a message in a bottle.",
+ "Write a Python function that parses an ISO 8601 date string without using datetime, with tests.",
+ "Explain how a hash map handles collisions, with a small C example.",
+ "List ten facts about the planet Mars and one about each of its moons.")]
+assert len(prompts) >= max(BS)
+
+rec = None
+_orig_forward = model.forward
+def _fwd(input_ids, params = None):
+ y = _orig_forward(input_ids, params)
+ if rec is not None and len(rec) < LOGIT_STEPS:
+ rec.append(y.detach().float().cpu().clone())
+ return y
+model.forward = _fwd
+
+def run(b, new):
+ """b concurrent jobs; returns per-job token lists, wall seconds (enqueue to last token)"""
+ jobs = [Job(input_ids = tok.encode(prompts[i]), max_new_tokens = new, sampler = S, stop_conditions = [], identifier = i) for i in range(b)]
+ outs = [[] for _ in range(b)]
+ torch.cuda.synchronize(); t0 = time.time()
+ gen.enqueue(jobs)
+ while gen.num_remaining_jobs():
+ for r in gen.iterate():
+ if r.get("stage") == "streaming":
+ t = r.get("token_ids")
+ if t is not None and t.numel():
+ outs[r["identifier"]] += t.flatten().tolist()
+ torch.cuda.synchronize()
+ return outs, time.time() - t0
+
+def arm(name, multi, b):
+ global rec
+ cg.purge(); cg.set_multi(multi); cg.CUDA_GRAPH_ENABLED = True
+ r0 = model.__dict__.get("_cuda_graph_runner")
+ if r0 is not None:
+ r0.stats = {"captures": 0, "replays": 0, "warmups": 0, "declines": type(r0.stats["declines"])()}
+ run(b, 24) # per-shape warmups + capture + autotune (graph arm), tuner (off arm)
+ outs, dt = run(b, NEW) # timed: includes the prefill of B short prompts (same in both arms)
+ n = sum(len(o) for o in outs)
+ rec = []; run(b, LOGIT_STEPS + 1); logits = rec; rec = None
+ a = {"arm": name, "multi": multi, "B": b, "agg_tps": n / dt, "wall_s": dt, "n_tokens": n, "ids": outs, "logits": logits}
+ r = model.__dict__.get("_cuda_graph_runner")
+ a["runner_stats"] = {k: (dict(v) if hasattr(v, "items") else v) for k, v in r.stats.items()} if r is not None else None
+ P({k: v for k, v in a.items() if k not in ("ids", "logits")})
+ res["arms"].append(a)
+ return a
+
+ok = True
+res["checks"] = []
+for b in BS:
+ arms = []
+ for rd in range(ROUNDS): # interleaved: off, on, off, on
+ arms.append(arm(f"B{b}_off{rd}", False, b)); arms.append(arm(f"B{b}_on{rd}", True, b))
+ ref = arms[0]
+ for a in arms[1:]:
+ for j in range(b):
+ x, y = ref["ids"][j], a["ids"][j]
+ div = next((k for k, (u, v) in enumerate(zip(x, y)) if u != v), None)
+ if div is None and len(x) != len(y): div = min(len(x), len(y))
+ if div is not None: ok = False
+ P({"check": "tokens", "B": b, "a": ref["arm"], "b": a["arm"], "job": j, "n": len(x), "first_divergence": div})
+ md = max((float((u - v).abs().max()) if u.shape == v.shape else float("inf")) for u, v in zip(ref["logits"], a["logits"])) \
+ if ref["logits"] and len(ref["logits"]) == len(a["logits"]) else float("inf")
+ if md != 0.0: ok = False
+ P({"check": "logits", "B": b, "a": ref["arm"], "b": a["arm"], "n_steps": len(a["logits"]), "max_abs_diff": md})
+ res["checks"].append({"B": b, "a": ref["arm"], "b": a["arm"], "logits_max_abs_diff": md})
+ off = [a["agg_tps"] for a in arms if not a["multi"]]; on = [a["agg_tps"] for a in arms if a["multi"]]
+ P({"summary": True, "B": b, "mean_tps_off": sum(off) / len(off), "mean_tps_on": sum(on) / len(on),
+ "speedup": (sum(on) / len(on)) / (sum(off) / len(off))})
+cg.purge()
+for a in res["arms"]: a.pop("logits")
+res["identical"] = ok
+if out: json.dump(res, open(out, "w"), indent = 1)
+P({"identical": ok})
+sys.exit(0 if ok else 1)
diff --git a/tests/port/bench_cuda_graph_qwen.py b/tests/port/bench_cuda_graph_qwen.py
new file mode 100644
index 0000000..871ef67
--- /dev/null
+++ b/tests/port/bench_cuda_graph_qwen.py
@@ -0,0 +1,110 @@
+# Whole-forward CUDA graph bench/check for Qwen3.8-27B (GatedDeltaNet hybrid, mrope), B=1. Needs a GPU; not run by CI.
+# usage: [BENCH_DRAFT=DFLASH2_DIR [BENCH_NDRAFT=7]] EXL3_CUDA_GRAPH=1 python -I bench_cuda_graph_qwen.py ENGINE_DIR MODEL_DIR OUT.json [NEW_TOKENS]
+# plain : model=<Qwen3.8 EXL3 dir> (Q=1 decode graph)
+# dflash: + BENCH_DRAFT=<DFlash2 dir> (Q=1+NDRAFT verify graphs, recurrent_history/dflash_verify,
+# target hidden taps exported per replay; drafter + ring cache + Cache(max_batch_size=1, max_history) as smoke_qwen.py)
+# Arms in one process, same load: eager, graph, eager, graph (module flag flipped + purge between arms).
+# Per arm and prompt: decode tok/s (smoke_qwen.py method), token stream. Asserts graph stream == eager stream, and
+# compares the logits returned by model.forward on the first LOGIT_STEPS decode steps (separate untimed pass).
+import sys, os, time, json
+eng, mdir, out = sys.argv[1], sys.argv[2], sys.argv[3]; NEW = int(sys.argv[4]) if len(sys.argv) > 4 else 256
+LOGIT_STEPS = 16
+sys.path.insert(0, eng)
+import torch
+from exllamav3 import Config, Model, Cache, Tokenizer, Generator, Job
+from exllamav3.generator.sampler import ArgmaxSampler
+from exllamav3.model import cuda_graph as cg
+import exllamav3
+
+res = {"engine": exllamav3.__file__, "model": mdir, "env": {k: v for k, v in os.environ.items() if k.startswith("EXL3_")},
+ "arms": [], "new_tokens": NEW}
+cfg = Config.from_directory(mdir); model = Model.from_config(cfg)
+DFL = os.environ.get("BENCH_DRAFT"); ND = int(os.environ.get("BENCH_NDRAFT", "7"))
+res["draft"] = DFL; res["num_draft_tokens"] = ND if DFL else 0
+cache = Cache(model, max_num_tokens=8192, max_batch_size=1, **({"max_history": max(3, ND)} if DFL else {}))
+model.load(); tok = Tokenizer.from_config(cfg)
+kw = {}
+if DFL:
+ dcfg = Config.from_directory(DFL); dm = Model.from_config(dcfg); dc = Cache(dm, max_num_tokens=16 * 256); dm.load()
+ dc.max_num_tokens = 8192 # ring cache as in a served drafter: the generator only compares sizes
+ kw = dict(draft_model=dm, draft_cache=dc, num_draft_tokens=ND)
+gen = Generator(model=model, cache=cache, tokenizer=tok, **kw)
+S = ArgmaxSampler()
+pl = os.environ["PROMPT_LONG"] # a long text file (summary prompt)
+base = open(pl).read()
+prompts = [
+ "<|im_start|>user\nWrite a short story about a lighthouse keeper who finds a message in a bottle.<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n",
+ "<|im_start|>user\nWrite a Python function that parses an ISO 8601 date string without using datetime, with tests.<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n",
+ "<|im_start|>user\nSummarise the following text in five bullet points:\n" + base + "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n",
+]
+
+def run(ids, new):
+ job = Job(input_ids=ids, max_new_tokens=new, sampler=S, stop_conditions=[])
+ torch.cuda.synchronize(); t0 = time.time(); tf = None; o = []
+ gen.enqueue(job)
+ while gen.num_remaining_jobs():
+ for r in gen.iterate():
+ if r.get("stage") == "streaming":
+ t = r.get("token_ids")
+ if t is not None and t.numel():
+ if tf is None: torch.cuda.synchronize(); tf = time.time()
+ o += t.flatten().tolist()
+ torch.cuda.synchronize(); te = time.time()
+ return o, tf - t0, te - tf
+
+# logits recorder around Model.forward (decode calls only; prefill does not go through forward)
+rec = None
+_orig_forward = model.forward
+def _fwd(input_ids, params=None):
+ y = _orig_forward(input_ids, params)
+ if rec is not None and len(rec) < LOGIT_STEPS:
+ rec.append(y.detach().float().cpu().clone())
+ return y
+model.forward = _fwd
+
+def arm(name, graph):
+ global rec
+ cg.purge(); cg.CUDA_GRAPH_ENABLED = graph
+ stats0 = None
+ a = {"arm": name, "graph": graph, "prompts": [], "logits": []}
+ r0 = model.__dict__.get("_cuda_graph_runner")
+ if r0 is not None:
+ r0.stats = {"captures": 0, "replays": 0, "warmups": 0, "declines": type(r0.stats["declines"])()}
+ run(tok.encode("Hello, warm-up."), 16)
+ for p in prompts:
+ ids = tok.encode(p)
+ run(ids, 8) # warm this prompt's block-table width (graph arm: warmups + capture)
+ o, tp, td = run(ids, NEW)
+ a["prompts"].append({"n_in": ids.shape[-1], "decode_tps": (len(o) - 1) / td, "decode_s": td, "ttft_s": tp, "ids": o})
+ print(json.dumps({"arm": name, "n_in": ids.shape[-1], "decode_tps": round((len(o) - 1) / td, 2)}), flush=True)
+ rec = []; run(ids, LOGIT_STEPS + 1); a["logits"].append(rec); rec = None
+ r = model.__dict__.get("_cuda_graph_runner")
+ if graph and r is not None:
+ a["graph_stats"] = {k: (dict(v) if isinstance(v, dict) or hasattr(v, "items") else v) for k, v in r.stats.items()}
+ print(json.dumps({"graph_stats": a["graph_stats"]}), flush=True)
+ res["arms"].append(a)
+ return a
+
+arms = [arm("eager1", False), arm("graph1", True), arm("eager2", False), arm("graph2", True)]
+cg.purge()
+
+ok = True
+res["checks"] = []
+for ea, ga in ((arms[0], arms[1]), (arms[2], arms[3]), (arms[0], arms[2]), (arms[1], arms[3])):
+ for i, (pe, pg) in enumerate(zip(ea["prompts"], ga["prompts"])):
+ a_, b_ = pe["ids"], pg["ids"]
+ div = next((j for j, (u, v) in enumerate(zip(a_, b_)) if u != v), None)
+ if div is None and len(a_) != len(b_): div = min(len(a_), len(b_))
+ md = max((float((x - y).abs().max()) if x.shape == y.shape else float("inf")) for x, y in zip(ea["logits"][i], ga["logits"][i])) \
+ if ea["logits"][i] else None
+ c = {"a": ea["arm"], "b": ga["arm"], "prompt": i, "first_divergence": div, "logits_max_abs_diff": md,
+ "n_logit_steps": len(ea["logits"][i])}
+ res["checks"].append(c); print(json.dumps(c), flush=True)
+ if div is not None or md not in (0.0,): ok = False
+for a in arms: a.pop("logits")
+for name, sel in (("eager", (0, 2)), ("graph", (1, 3))):
+ res[f"mean_tps_{name}"] = [sum(arms[k]["prompts"][i]["decode_tps"] for k in sel) / 2 for i in range(len(prompts))]
+res["identical"] = ok
+json.dump(res, open(out, "w"), indent=1)
+print(json.dumps({k: res[k] for k in ("mean_tps_eager", "mean_tps_graph", "identical")}), flush=True)
+assert ok, "graph != eager (see checks)"
diff --git a/tests/port/bench_dec.py b/tests/port/bench_dec.py
new file mode 100644
index 0000000..0cdfa28
--- /dev/null
+++ b/tests/port/bench_dec.py
@@ -0,0 +1,79 @@
+# Kill test: Kyojin's HIP decode GEMV (exl3_dec_gemv, compiled for CUDA through port.cuh) vs the
+# upstream CUDA batch-1 path (BC_LinearEXL3 -> exl3_gemv) on the real linears of an EXL3 model.
+# Error of both against an fp32 reference (same trellis decode, fp32 Hadamards and matmul); time per call
+# from CUDA graphs (50 calls per replay, so no launch overhead).
+# usage: EXL3_PORT_DEC=1 python -I bench_dec.py ENGINE_DIR MODEL_DIR OUT.json [MIN_BLOCKS,...]
+import sys, os, json, time
+eng, mdir, out = sys.argv[1:4]
+MBS = [int(v) for v in sys.argv[4].split(",")] if len(sys.argv) > 4 else [32]
+sys.path.insert(0, eng)
+import torch
+from exllamav3 import Config, Model
+from exllamav3.ext import exllamav3_ext as ext
+from exllamav3.modules.quant.exl3 import LinearEXL3, dec_workspace
+assert hasattr(ext, "exl3_dec_gemv"), "build with EXL3_PORT_DEC=1 and import with EXL3_PORT_DEC=1"
+torch.manual_seed(0)
+cfg = Config.from_directory(mdir); model = Model.from_config(cfg); model.load()
+dev = torch.device("cuda:0")
+
+def had128():
+ h = torch.ones(1, 1, dtype = torch.float, device = dev)
+ while h.shape[0] < 128: h = torch.cat([torch.cat([h, h], 1), torch.cat([h, -h], 1)], 0)
+ return h / 128 ** 0.5
+H = had128()
+def had_rows(v): # v [1, n]: H128 on every 128-block
+ return (v.view(-1, 128) @ H).view(1, -1)
+
+# one linear per distinct (in, out, K) that the dec kernel takes (mul1 codebook, K*2 integral, shapes)
+lins = {}
+for m in (sm for top in model.modules for sm in top):
+ inner = getattr(m, "inner", None)
+ if not isinstance(inner, LinearEXL3): continue
+ if not inner.mul1 or inner.mcg or inner.suh is None or inner.svh is None: continue
+ if inner.in_features % 512 or inner.out_features % 128 or float(inner.K * 2) != int(inner.K * 2): continue
+ lins.setdefault((inner.in_features, inner.out_features, inner.K), (m.key, inner))
+print(len(lins), "shapes", flush = True)
+scratch, counters = dec_workspace(dev)
+
+def gtime(fn, reps = 50, n = 5):
+ s = torch.cuda.Stream(); s.wait_stream(torch.cuda.current_stream())
+ with torch.cuda.stream(s):
+ for _ in range(3): fn()
+ torch.cuda.current_stream().wait_stream(s); torch.cuda.synchronize()
+ g = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(g):
+ for _ in range(reps): fn()
+ g.replay(); torch.cuda.synchronize()
+ best = 1e9
+ for _ in range(n):
+ a = torch.cuda.Event(enable_timing = True); b = torch.cuda.Event(enable_timing = True)
+ a.record(); g.replay(); b.record(); b.synchronize()
+ best = min(best, a.elapsed_time(b) * 1000 / reps)
+ return best
+
+res = {"model": mdir, "env": {k: v for k, v in os.environ.items() if k.startswith("EXL3_")}, "rows": []}
+for (kin, kout, K), (key, inner) in sorted(lins.items(), key = lambda t: t[0]):
+ x = (torch.randn(1, kin, device = dev) * 0.5).half()
+ w = inner.get_inner_weight_tensor().float()
+ xr = had_rows(x.float() * inner.suh.float().view(1, -1)).half().float()
+ ref = had_rows(xr @ w) * inner.svh.float().view(1, -1)
+ y_up = inner.forward(x, {}).float()
+ y_dec = torch.empty(1, kout, dtype = torch.half, device = dev)
+ try:
+ ext.exl3_dec_gemv(x, inner.trellis, inner.suh, inner.svh, y_dec, scratch, counters, float(K))
+ except RuntimeError as e: # K not in this build's EXL3_PORT_DEC_KB2_MASK
+ print(json.dumps({"key": key, "K": K, "skip": str(e).splitlines()[0]}), flush = True); continue
+ y_dec = y_dec.float()
+ nr = ref.norm().item()
+ r = {"key": key, "in": kin, "out": kout, "K": K,
+ "relerr_up": (y_up - ref).norm().item() / nr, "relerr_dec": (y_dec - ref).norm().item() / nr,
+ "maxdiff_dec_up": (y_dec - y_up).abs().max().item(), "ref_absmax": ref.abs().max().item()}
+ yb = torch.empty(1, kout, dtype = torch.half, device = dev)
+ r["us_up"] = gtime(lambda: inner.forward(x, {}))
+ for mb in MBS:
+ os.environ["EXL3_DEC_MIN_BLOCKS"] = str(mb)
+ r[f"us_dec_mb{mb}"] = gtime(lambda: ext.exl3_dec_gemv(x, inner.trellis, inner.suh, inner.svh, yb, scratch, counters, float(K)))
+ wbytes = inner.trellis.numel() * inner.trellis.element_size()
+ r["GBs_up"] = wbytes / r["us_up"] / 1e3
+ res["rows"].append(r); print(json.dumps(r), flush = True)
+json.dump(res, open(out, "w"), indent = 1)
diff --git a/tests/port/test_attn16.py b/tests/port/test_attn16.py
new file mode 100644
index 0000000..6038ebc
--- /dev/null
+++ b/tests/port/test_attn16.py
@@ -0,0 +1,168 @@
+"""
+Paged decode attention: pre-1.6 Kyojin kernels (triton_paged, ATTN16 forced off) vs the ported upstream exllamav3 1.6.0
+(MIT) kernels (triton_paged_cu), CUDA only. fp16 and 6-bit quantized caches (built with ext.quant_cache_paged, as
+cache/quant.py does), q_len 1 / 8, 24 q heads / 4 kv heads, head_dim 256, page size 256, contexts 2K / 20K / 64K,
+no window and a 2048 left window (causal). Reports the max abs diff against an fp32 torch reference (dequantized
+K/V for the quantized cache) for both paths and microseconds per call (CUDA events, 20 calls after 3 warm-ups).
+
+ pytest -s tests/port/test_attn16.py or python tests/port/test_attn16.py
+Needs a GPU (not run by the port; the GPU is shared).
+"""
+import os, sys
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+import itertools
+import torch
+try:
+ import pytest
+except ImportError: # the CUDA venv has no pytest: __main__ runs the same grid without it
+ pytest = None
+
+if pytest is not None:
+ pytestmark = pytest.mark.skipif(not torch.cuda.is_available() or bool(torch.version.hip), reason = "CUDA only")
+
+from exllamav3.constants import PAGE_SIZE
+from exllamav3.modules.attention_fn import triton_paged as tp
+
+NQ, NKV, HD = 24, 4, 256
+BITS = 6
+dev = "cuda:0"
+_ext = None
+
+
+def ext():
+ global _ext
+ if _ext is None:
+ from exllamav3.ext import exllamav3_ext as e
+ _ext = e
+ return _ext
+
+
+def make_case(ctx, q_len, quant, seed = 0):
+ """ctx = total kv length including the q_len query rows, which are already in the cache."""
+ torch.manual_seed(seed)
+ pages = -(-ctx // PAGE_SIZE)
+ kc = torch.randn((pages, PAGE_SIZE, NKV, HD), dtype = torch.half, device = dev)
+ vc = torch.randn_like(kc)
+ bt = torch.randperm(pages, device = dev, dtype = torch.int32).view(1, pages)
+ sl = torch.full((1,), ctx - q_len, dtype = torch.int32, device = dev)
+ q = torch.randn((1, q_len, NQ, HD), dtype = torch.half, device = dev)
+ if not quant:
+ return dict(q = q, kc = kc, vc = vc, bt = bt, sl = sl, kref = kc, vref = vc, qc = None)
+ e = ext()
+ qk = torch.zeros((pages, PAGE_SIZE, NKV * HD // 32 * BITS), dtype = torch.int, device = dev)
+ qv = torch.zeros_like(qk)
+ sk = torch.zeros((pages, PAGE_SIZE, NKV * HD // 32), dtype = torch.half, device = dev)
+ sv = torch.zeros_like(sk)
+ # Logical token t of the sequence = flat row t of kc / vc, appended in chunks (the kernel's grid y = chunk length,
+ # max 65535), as CacheLayer_quant.update_kv appends new tokens
+ kf, vf = kc.view(1, pages * PAGE_SIZE, NKV, HD), vc.view(1, pages * PAGE_SIZE, NKV, HD)
+ for s0 in range(0, ctx, 16384):
+ n = min(16384, ctx - s0)
+ start = torch.full((1,), s0, dtype = torch.int, device = dev)
+ e.quant_cache_paged(kf[:, s0:s0 + n].contiguous(), qk, sk, vf[:, s0:s0 + n].contiguous(), qv, sv, start, bt,
+ PAGE_SIZE, n, 0.0, False)
+ kd = torch.empty_like(kc); vd = torch.empty_like(vc)
+ e.dequant_cache_paged(qk, sk, kd, qv, sv, vd, torch.full((1,), ctx, dtype = torch.int, device = dev), bt,
+ PAGE_SIZE, -1, 0.0)
+ return dict(q = q, kc = qk, vc = qv, bt = bt, sl = sl, kref = kd, vref = vd, qc = (sk, sv, BITS, BITS))
+
+
+def reference(c, ctx, q_len, window):
+ q = c["q"]
+ pages = c["bt"].shape[1]
+ idx = c["bt"][0].long()
+ K = c["kref"][idx].reshape(pages * PAGE_SIZE, NKV, HD)[:ctx]
+ V = c["vref"][idx].reshape(pages * PAGE_SIZE, NKV, HD)[:ctx]
+ lo = 0 if window is None else max(0, ctx - q_len - window) # keys below carry zero weight
+ K = K[lo:].float().permute(1, 0, 2) # [kvh, T, d]
+ V = V[lo:].float().permute(1, 0, 2)
+ T = K.shape[1]
+ g = NQ // NKV
+ qf = q[0].float().view(q_len, NKV, g, HD).permute(1, 0, 2, 3) # [kvh, q, g, d]
+ s = torch.einsum("hqgd,htd->hqgt", qf, K) * HD ** -0.5
+ qpos = (ctx - q_len + torch.arange(q_len, device = dev)).view(1, q_len, 1, 1)
+ kpos = (lo + torch.arange(T, device = dev)).view(1, 1, 1, T)
+ mask = kpos <= qpos
+ if window is not None:
+ mask &= kpos >= qpos - window
+ s = s.masked_fill(~mask, -float("inf"))
+ o = torch.einsum("hqgt,htd->hqgd", torch.softmax(s, -1), V)
+ return o.permute(1, 0, 2, 3).reshape(1, q_len, NQ, HD)
+
+
+def run_old(c, window, q_len):
+ saved = tp.ATTN16
+ tp.ATTN16 = False
+ try:
+ return tp.paged_attn_triton_decode(
+ c["q"], None, None, c["kc"], c["vc"], c["bt"], c["sl"], causal = True, window_size = window,
+ qc = c["qc"], pre_appended_len = q_len, n_kv_heads_override = NKV)
+ finally:
+ tp.ATTN16 = saved
+
+
+def run_new(c, window, q_len):
+ from exllamav3.modules.attention_fn.triton_paged_cu import paged_attn_triton_decode_cu
+ return paged_attn_triton_decode_cu(
+ c["q"], None, None, c["kc"], c["vc"], c["bt"], c["sl"], causal = True, window_size = window,
+ qc = c["qc"], pre_appended_len = q_len, n_kv_heads_override = NKV)
+
+
+def time_us(fn, n = 20, warm = 3):
+ for _ in range(warm):
+ fn()
+ torch.cuda.synchronize()
+ a, b = torch.cuda.Event(enable_timing = True), torch.cuda.Event(enable_timing = True)
+ a.record()
+ for _ in range(n):
+ fn()
+ b.record()
+ torch.cuda.synchronize()
+ return a.elapsed_time(b) * 1000 / n
+
+
+GRID = dict(quant = [False, True], q_len = [1, 8], window = [None, 2048], ctx = [2048, 20480, 65536])
+
+
+def _param(f):
+ if pytest is None:
+ return f
+ for k in reversed(list(GRID)):
+ f = pytest.mark.parametrize(k, GRID[k])(f)
+ return f
+
+
+@_param
+def test_attn16(quant, q_len, window, ctx):
+ c = make_case(ctx, q_len, quant, seed = ctx + q_len)
+ ref = reference(c, ctx, q_len, window)
+ o_old = run_old(c, window, q_len).float()
+ o_new = run_new(c, window, q_len).float()
+ if quant and not torch.isfinite(o_old).all(): # NaN triage (attn1: q6 64K NaN in BOTH paths): where does it start?
+ print(f"\n[attn16] nan triage ctx={ctx} q_len={q_len} win={window}: kref nonfinite {(~torch.isfinite(c['kref'])).sum().item()}, "
+ f"vref {(~torch.isfinite(c['vref'])).sum().item()}, sk {(~torch.isfinite(c['qc'][0])).sum().item()}, "
+ f"sv {(~torch.isfinite(c['qc'][1])).sum().item()}, ref {(~torch.isfinite(ref)).sum().item()}, "
+ f"old {(~torch.isfinite(o_old)).sum().item()}, new {(~torch.isfinite(o_new)).sum().item()}")
+ e_old = (o_old - ref).abs().max().item()
+ e_new = (o_new - ref).abs().max().item()
+ t_old = time_us(lambda: run_old(c, window, q_len))
+ t_new = time_us(lambda: run_new(c, window, q_len))
+ print(f"\n[attn16] {'q6 ' if quant else 'fp16'} q_len={q_len} win={window} ctx={ctx:6d}: "
+ f"maxabs old={e_old:.2e} new={e_new:.2e} old-vs-new={(o_old - o_new).abs().max().item():.2e} | "
+ f"us/call old={t_old:7.1f} new={t_new:7.1f} ({t_old / t_new:.2f}x)")
+ # fp16 outputs from fp16 inputs with unit-variance data: both paths sit at fp16 rounding noise
+ assert e_new < 5e-3 and e_old < 5e-3
+ assert e_new <= max(2 * e_old, 2e-3)
+
+
+if __name__ == "__main__":
+ if pytest is not None:
+ sys.exit(pytest.main([__file__, "-s", "-q", "-p", "no:cacheprovider"]))
+ fails = 0
+ for vals in itertools.product(*GRID.values()):
+ try:
+ test_attn16(**dict(zip(GRID, vals)))
+ except AssertionError as e:
+ fails += 1; print("[attn16] FAIL", dict(zip(GRID, vals)), e)
+ print(f"[attn16] {fails} failed of {len(list(itertools.product(*GRID.values())))}")
+ sys.exit(1 if fails else 0)
diff --git a/tests/test_failure_containment.py b/tests/test_failure_containment.py
index 6d843f3..1b88324 100644
--- a/tests/test_failure_containment.py
+++ b/tests/test_failure_containment.py
@@ -71,6 +71,8 @@ def make_generator(pending, active=(), max_batch_size=16):
generator.pagetable = StubPagetable()
generator.pending_jobs = list(pending)
generator.active_jobs = list(active)
+ generator.deferred_jobs = [] # read by flush_deferred() (EXL3_REPLY_FIRST) at the start of iterate()
+ generator.model = None # read by the fused-MoE barrier check at the end of iterate()
generator.max_batch_size = max_batch_size
return generator
diff --git a/tests/test_foreign_quant_cpu.py b/tests/test_foreign_quant_cpu.py
new file mode 100644
index 0000000..3317699
--- /dev/null
+++ b/tests/test_foreign_quant_cpu.py
@@ -0,0 +1,291 @@
+"""CPU-only tests for exllamav3.foreign_quant (ggml Q8_0 / IQ2_XXS, NVFP4).
+
+Modules are loaded by file path (stdlib+numpy only, no torch). Three
+independent oracles are used:
+
+* a C program (tests/foreign_quant_oracle/dequant_oracle.c) carrying the
+ verbatim llama.cpp dequant algorithm + tables (MIT) - bit-exact checks;
+* ml_dtypes fp8/fp4 codebooks (skipped if not installed);
+* real Bolt checkpoint tensors fetched with HTTP Range requests (no full
+ download; skipped if the network is unavailable).
+"""
+from __future__ import annotations
+
+import importlib.util
+import json
+import os
+import shutil
+import struct
+import subprocess
+import sys
+import urllib.request
+
+import numpy as np
+import pytest
+
+FQ_DIR = os.path.abspath(os.path.join(
+ os.path.dirname(__file__), "..", "exllamav3", "foreign_quant"))
+ORACLE_SRC = os.path.abspath(os.path.join(
+ os.path.dirname(__file__), "foreign_quant_oracle", "dequant_oracle.c"))
+HF_REPO = "nvidia/NVIDIA-Nemotron-3.5-Bolt-74B-A9B-24GB"
+HF_BASE = f"https://huggingface.co/{HF_REPO}/resolve/main/"
+
+
+def _load(name):
+ modname = f"foreign_quant_{name}_under_test"
+ if modname in sys.modules:
+ return sys.modules[modname]
+ path = os.path.join(FQ_DIR, name + ".py")
+ spec = importlib.util.spec_from_file_location(modname, path)
+ mod = importlib.util.module_from_spec(spec)
+ sys.modules[modname] = mod
+ spec.loader.exec_module(mod)
+ return mod
+
+
+q8_0 = _load("q8_0")
+iq2_xxs = _load("iq2_xxs")
+nvfp4 = _load("nvfp4")
+
+
+# --------------------------------------------------------------------------
+# C oracle (verbatim llama.cpp algorithm)
+# --------------------------------------------------------------------------
+
[email protected](scope="session")
+def oracle(tmp_path_factory):
+ if shutil.which("gcc") is None:
+ pytest.skip("gcc not available")
+ exe = str(tmp_path_factory.mktemp("oracle") / "dequant_oracle")
+ try:
+ subprocess.run(["gcc", "-O2", "-o", exe, ORACLE_SRC],
+ check=True, capture_output=True, timeout=120)
+ except Exception as e:
+ pytest.skip(f"oracle build failed: {e}")
+ return exe
+
+
+def _oracle_run(oracle_exe, mode, payload: bytes, tmp_path):
+ f = tmp_path / f"in_{mode}.bin"
+ f.write_bytes(bytes(payload))
+ r = subprocess.run([oracle_exe, mode, str(f)], check=True,
+ capture_output=True, timeout=120)
+ return np.array([int(x, 16) for x in r.stdout.decode().split()], dtype=np.uint32)
+
+
+def _bits(a: np.ndarray) -> np.ndarray:
+ return np.ascontiguousarray(a, dtype=np.float32).view(np.uint32)
+
+
+# --------------------------------------------------------------------------
+# Q8_0
+# --------------------------------------------------------------------------
+
+def test_q8_0_closed_form():
+ blk = bytes([0x00, 0x3C]) + bytes(range(32)) # d = 1.0, qs = 0..31
+ out = q8_0.dequant_q8_0_block(blk)
+ assert out.shape == (32,)
+ np.testing.assert_array_equal(out, np.arange(32, dtype=np.float32))
+
+
+def test_q8_0_negative_and_scale():
+ blk = struct.pack("<H", 0xBC00) + bytes([0x80, 0xFF, 0x7F] + [0] * 29)
+ out = q8_0.dequant_q8_0_block(blk) # d = -1.0
+ assert out[0] == np.float32(128.0) and out[1] == np.float32(1.0)
+ assert out[2] == np.float32(-127.0)
+
+
+def test_q8_0_vs_oracle(oracle, tmp_path):
+ rng = np.random.default_rng(0)
+ n = 5
+ payload = bytearray()
+ for _ in range(n):
+ payload += rng.integers(0, 256, size=2).astype(np.uint8).tobytes()
+ payload += rng.integers(0, 256, size=32).astype(np.uint8).tobytes()
+ ref = _oracle_run(oracle, "q8_0", bytes(payload), tmp_path)
+ got = q8_0.dequant_q8_0(np.frombuffer(bytes(payload), dtype=np.uint8).reshape(n, 34))
+ assert got.shape == (n, 32)
+ np.testing.assert_array_equal(_bits(got).ravel(), ref)
+
+
+def test_fp16_converter_vs_numpy(oracle, tmp_path):
+ edge = [0x0000, 0x8000, 0x0001, 0x03FF, 0x0400, 0x3C00, 0xBC00,
+ 0x7BFF, 0x7C00, 0xFC00, 0x7C01, 0x3555, 0xC000]
+ rng = np.random.default_rng(1)
+ vals = edge + [int(v) for v in rng.integers(0, 65536, size=200)]
+ payload = struct.pack(f"<{len(vals)}H", *vals)
+ ref = _oracle_run(oracle, "fp16", payload.encode() if isinstance(payload, str) else payload,
+ tmp_path)
+ got = np.array(vals, dtype=np.uint16).view("<f2").astype(np.float32)
+ np.testing.assert_array_equal(_bits(got), ref)
+
+
+# --------------------------------------------------------------------------
+# IQ2_XXS
+# --------------------------------------------------------------------------
+
+def test_iq2_xxs_grid_values():
+ assert set(int(v) for v in np.unique(iq2_xxs._GRID_BYTES)) == {8, 25, 43}
+
+
+def test_iq2_xxs_closed_form():
+ blk = bytes([0x00, 0x3C]) + bytes(64) # d = 1.0, all indices 0
+ out = iq2_xxs.dequant_iq2_xxs_block(blk)
+ assert out.shape == (256,)
+ # db = 1*(0.5+0)*0.25 = 0.125; grid[0] = all 8s; signs = ksigns[0] = 0.
+ np.testing.assert_array_equal(out, np.full(256, np.float32(1.0)))
+
+
+def test_iq2_xxs_vs_oracle(oracle, tmp_path):
+ rng = np.random.default_rng(2)
+ n = 4
+ payload = rng.integers(0, 256, size=(n, 66)).astype(np.uint8)
+ ref = _oracle_run(oracle, "iq2_xxs", payload.tobytes(), tmp_path)
+ got = iq2_xxs.dequant_iq2_xxs(payload)
+ assert got.shape == (n, 256)
+ np.testing.assert_array_equal(_bits(got).ravel(), ref)
+
+
+# --------------------------------------------------------------------------
+# NVFP4
+# --------------------------------------------------------------------------
+
+def test_nvfp4_e2m1_lut():
+ ml_dtypes = pytest.importorskip("ml_dtypes")
+ ref = np.arange(16, dtype=np.uint8).view(ml_dtypes.float4_e2m1fn).astype(np.float32)
+ np.testing.assert_array_equal(np.array(nvfp4.E2M1_LUT, dtype=np.float32), ref)
+
+
+def test_nvfp4_e4m3_all_codes():
+ ml_dtypes = pytest.importorskip("ml_dtypes")
+ codes = np.arange(256, dtype=np.uint8)
+ ref = codes.view(ml_dtypes.float8_e4m3fn).astype(np.float32)
+ got = nvfp4.e4m3_to_float32(codes)
+ # Exact for all finite codes (powers of two times (1+m/8)); NaNs compared
+ # by payload-insensitive equality.
+ np.testing.assert_allclose(got, ref, rtol=0, atol=0, equal_nan=True)
+
+
+def test_nvfp4_closed_form():
+ # One full group of 16: nibbles (1,1),(0,7),(0,0) x1 + 13 more zeros.
+ packed = np.array([[0x11, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]],
+ dtype=np.uint8)
+ scales = np.array([[0x38]], dtype=np.uint8) # 1.0
+ out = nvfp4.dequant_nvfp4(packed, scales, 2.0)
+ assert out.shape == (1, 16)
+ np.testing.assert_array_equal(out[0, :4], np.array([1.0, 1.0, 0.0, 12.0],
+ dtype=np.float32))
+ np.testing.assert_array_equal(out[0, 4:], np.zeros(12, dtype=np.float32))
+
+
+def test_nvfp4_shape_mismatch():
+ with pytest.raises(ValueError):
+ nvfp4.dequant_nvfp4(np.zeros((2, 8), np.uint8), np.zeros((2, 2), np.uint8), 1.0)
+
+
+# --------------------------------------------------------------------------
+# Real Bolt tensors via HTTP Range (no full download)
+# --------------------------------------------------------------------------
+
+def _http_range(url, start, n, timeout=120):
+ req = urllib.request.Request(url, headers={"Range": f"bytes={start}-{start + n - 1}"})
+ with urllib.request.urlopen(req, timeout=timeout) as r:
+ assert r.status in (200, 206), f"range request failed: {r.status}"
+ data = r.read(n)
+ assert len(data) == n, f"short read: {len(data)} != {n}"
+ return data
+
+
[email protected](scope="session")
+def hf_tensors():
+ try:
+ with urllib.request.urlopen(HF_BASE + "model.safetensors.index.json",
+ timeout=120) as r:
+ index = json.load(r)
+ except Exception as e:
+ pytest.skip(f"HF unreachable: {e}")
+ weight_map = index["weight_map"]
+ headers = {}
+
+ def shard_header(fname):
+ if fname not in headers:
+ raw = _http_range(HF_BASE + fname, 0, 8)
+ (hlen,) = struct.unpack("<Q", raw)
+ headers[fname] = (8 + hlen, json.loads(_http_range(HF_BASE + fname, 8, hlen)))
+ return headers[fname]
+
+ def fetch(name, rows):
+ fname = weight_map[name]
+ base, header = shard_header(fname)
+ meta = header[name]
+ shape, (start, end) = meta["shape"], meta["data_offsets"]
+ esize = {"F32": 4, "F16": 2, "BF16": 2, "U8": 1, "F8_E4M3": 1}[meta["dtype"]]
+ nrows = shape[0] if shape else 1
+ row_n = int(np.prod(shape[1:])) if len(shape) > 1 else 1
+ assert end - start == nrows * row_n * esize
+ lo = base + start + rows.start * row_n * esize
+ hi = base + start + rows.stop * row_n * esize
+ return _http_range(HF_BASE + fname, lo, hi - lo), meta
+
+ out = {}
+ try:
+ out["lm_head"], out["lm_head_meta"] = fetch("language_model.lm_head.weight",
+ range(0, 8))
+ out["fc1"], out["fc1_meta"] = fetch(
+ "language_model.backbone.layers.1.mixer.fc1_latent_proj.weight", range(0, 2))
+ out["exp0up"], out["exp0up_meta"] = fetch(
+ "language_model.backbone.layers.1.mixer.experts.0.up_proj.weight", range(0, 2))
+ w, wmeta = fetch("language_model.backbone.layers.0.mixer.in_proj.weight",
+ range(0, 2))
+ s, smeta = fetch("language_model.backbone.layers.0.mixer.in_proj.weight_scale",
+ range(0, 2))
+ g, gmeta = fetch("language_model.backbone.layers.0.mixer.in_proj.weight_scale_2",
+ range(0, 1))
+ out.update(in_w=w, in_wmeta=wmeta, in_s=s, in_smeta=smeta, in_g=g)
+ except Exception as e:
+ pytest.skip(f"HF range fetch failed: {e}")
+ return out
+
+
+def test_real_q8_0_lm_head(hf_tensors):
+ meta = hf_tensors["lm_head_meta"]
+ assert meta["dtype"] == "U8" and meta["shape"][1:] == [128, 34]
+ raw = np.frombuffer(hf_tensors["lm_head"], dtype=np.uint8).reshape(8, 128, 34)
+ out = q8_0.dequant_q8_0(raw)
+ assert out.shape == (8, 128, 32) and np.all(np.isfinite(out))
+ assert 1e-4 < float(out.std()) < 1.0 # d-first layout sanity
+
+
+def test_real_q8_0_latent_proj(hf_tensors, oracle, tmp_path):
+ meta = hf_tensors["fc1_meta"]
+ assert meta["dtype"] == "U8" and meta["shape"][1:] == [128, 34]
+ raw = np.frombuffer(hf_tensors["fc1"], dtype=np.uint8).reshape(2, 128, 34)
+ out = q8_0.dequant_q8_0(raw)
+ assert np.all(np.isfinite(out)) and 1e-4 < float(out.std()) < 1.0
+ ref = _oracle_run(oracle, "q8_0", hf_tensors["fc1"], tmp_path)
+ np.testing.assert_array_equal(_bits(out).ravel(), ref)
+
+
+def test_real_iq2_xxs_expert(hf_tensors, oracle, tmp_path):
+ meta = hf_tensors["exp0up_meta"]
+ assert meta["dtype"] == "U8" and meta["shape"][1:] == [4, 66]
+ raw = np.frombuffer(hf_tensors["exp0up"], dtype=np.uint8).reshape(2, 4, 66)
+ out = iq2_xxs.dequant_iq2_xxs(raw)
+ assert out.shape == (2, 4, 256) and np.all(np.isfinite(out))
+ assert 1e-4 < float(out.std()) < 5.0
+ ref = _oracle_run(oracle, "iq2_xxs", hf_tensors["exp0up"], tmp_path)
+ np.testing.assert_array_equal(_bits(out).ravel(), ref)
+
+
+def test_real_nvfp4_in_proj(hf_tensors):
+ assert hf_tensors["in_wmeta"]["shape"][1:] == [2048]
+ assert hf_tensors["in_smeta"]["shape"][1:] == [256]
+ packed = np.frombuffer(hf_tensors["in_w"], dtype=np.uint8).reshape(2, 2048)
+ scales = np.frombuffer(hf_tensors["in_s"], dtype=np.uint8).reshape(2, 256)
+ (g,) = struct.unpack("<f", hf_tensors["in_g"])
+ assert np.isfinite(g) and g > 0
+ svals = nvfp4.e4m3_to_float32(scales)
+ assert np.all(np.isfinite(svals)) and np.all(svals > 0) and np.all(svals <= 600)
+ out = nvfp4.dequant_nvfp4(packed, scales, g)
+ assert out.shape == (2, 4096) and np.all(np.isfinite(out))
+ assert 1e-4 < float(out.std()) < 5.0
diff --git a/tests/test_foreign_quant_cuda.py b/tests/test_foreign_quant_cuda.py
new file mode 100644
index 0000000..903f3c6
--- /dev/null
+++ b/tests/test_foreign_quant_cuda.py
@@ -0,0 +1,759 @@
+"""GPU tests for the foreign-quant kernels (Q8_0 / IQ2_XXS / NVFP4 -> fp16).
+
+Bit-exactness: ext dequant output (fp16) must equal the numpy reference
+(exllamav3/foreign_quant/*.py, float32) cast to fp16, compared as uint16 bits.
+Fused path: fq_gemm_* (M = 1..16) vs dequant + torch.matmul within fp16
+tolerance. Runs on synthetic payloads always, and on REAL Bolt tensors from
+BOLT_MODEL_DIR when it is set.
+
+Standalone script (the CUDA venv has no pytest):
+ python tests/test_foreign_quant_cuda.py
+Exit nonzero on the first failure.
+"""
+from __future__ import annotations
+
+import importlib.util
+import json
+import os
+import sys
+
+import numpy as np
+import torch
+
+ENGINE = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
+FQ_DIR = os.path.join(ENGINE, "exllamav3", "foreign_quant")
+MODEL_DIR = os.environ.get("BOLT_MODEL_DIR", "")
+sys.path.insert(0, ENGINE)
+
+if "pytest" in sys.modules and (not torch.cuda.is_available() or torch.version.hip is not None):
+ import pytest # the standalone run (CUDA venv) has no pytest
+ pytest.skip("NVIDIA CUDA required", allow_module_level = True)
+
+
+def _load(name):
+ path = os.path.join(FQ_DIR, name + ".py")
+ spec = importlib.util.spec_from_file_location(f"fq_{name}_ref", path)
+ mod = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mod)
+ return mod
+
+
+q8_0 = _load("q8_0")
+iq2_xxs = _load("iq2_xxs")
+nvfp4 = _load("nvfp4")
+
+from exllamav3.ext import exllamav3_ext as ext # noqa: E402
+
+PASS = []
+FAIL = []
+
+
+def check(name, cond, detail=""):
+ print(f" [{'PASS' if cond else 'FAIL'}] {name} {detail}")
+ (PASS if cond else FAIL).append(name)
+
+
+def bits16(a: torch.Tensor) -> np.ndarray:
+ return a.detach().to(torch.float16).cpu().contiguous().view(torch.uint16).numpy()
+
+
+def ref16(a: np.ndarray) -> np.ndarray:
+ return np.ascontiguousarray(a, dtype=np.float32).astype(np.float16).view(np.uint16)
+
+
+def finite_scales(rng, shape):
+ """Random fp16 scales with exponent != 31 (finite: no Inf/NaN)."""
+ u = rng.integers(0, 65536, size=shape).astype(np.uint16)
+ exp_full = (u & 0x7C00) == 0x7C00
+ u[exp_full] &= 0xFBFF # clear top exponent bit -> exp <= 30
+ return u
+
+
+# --------------------------------------------------------------------------
+# Synthetic bit-exact dequant
+# --------------------------------------------------------------------------
+
+def test_q8_0_synth():
+ rng = np.random.default_rng(0)
+ n, kb = 8, 5
+ payload = np.empty((n, kb, 34), np.uint8)
+ payload[:, :, :2] = finite_scales(rng, (n, kb)).view(np.uint8).reshape(n, kb, 2)
+ payload[:, :, 2:] = rng.integers(0, 256, size=(n, kb, 32)).astype(np.uint8)
+ ref = ref16(q8_0.dequant_q8_0(payload))
+ out = torch.empty((n, kb * 32), dtype=torch.float16, device="cuda")
+ ext.fq_dequant_q8_0(torch.from_numpy(payload).cuda(), out)
+ torch.cuda.synchronize()
+ check("q8_0 synth bit-exact", np.array_equal(bits16(out).ravel(), ref.ravel()),
+ f"shape={(n, kb * 32)}")
+
+
+def test_iq2_xxs_synth():
+ rng = np.random.default_rng(2)
+ n, kb = 4, 3
+ payload = rng.integers(0, 256, size=(n, kb, 66)).astype(np.uint8)
+ ref = ref16(iq2_xxs.dequant_iq2_xxs(payload))
+ out = torch.empty((n, kb * 256), dtype=torch.float16, device="cuda")
+ ext.fq_dequant_iq2_xxs(torch.from_numpy(payload).cuda(), out)
+ torch.cuda.synchronize()
+ check("iq2_xxs synth bit-exact", np.array_equal(bits16(out).ravel(), ref.ravel()),
+ f"shape={(n, kb * 256)}")
+
+
+def test_nvfp4_synth():
+ rng = np.random.default_rng(3)
+ n, k = 8, 64
+ packed = rng.integers(0, 256, size=(n, k // 2)).astype(np.uint8)
+ scales = rng.integers(0, 256, size=(n, k // 16)).astype(np.uint8)
+ scales[(scales == 0x7F) | (scales == 0xFF)] = 0x38 # no NaN scales here
+ g = np.float32(0.37)
+ ref = ref16(nvfp4.dequant_nvfp4(packed, scales, g))
+ out = torch.empty((n, k), dtype=torch.float16, device="cuda")
+ ext.fq_dequant_nvfp4(torch.from_numpy(packed).cuda(), torch.from_numpy(scales).cuda(),
+ float(g), out)
+ torch.cuda.synchronize()
+ check("nvfp4 synth bit-exact", np.array_equal(bits16(out).ravel(), ref.ravel()), f"shape={(n, k)}")
+
+
+def test_nvfp4_e4m3_finite_sweep():
+ # Every finite E4M3 code as a scale over a fixed nibble pattern.
+ codes = np.arange(256, dtype=np.uint8).reshape(16, 16)
+ codes[(codes == 0x7F) | (codes == 0xFF)] = 0x00
+ packed = np.full((16, 128), 0x11, np.uint8) # all nibbles = 1 -> 0.5
+ ref = ref16(nvfp4.dequant_nvfp4(packed, codes, 1.0))
+ out = torch.empty((16, 256), dtype=torch.float16, device="cuda")
+ ext.fq_dequant_nvfp4(torch.from_numpy(packed).cuda(), torch.from_numpy(codes).cuda(), 1.0, out)
+ torch.cuda.synchronize()
+ check("nvfp4 e4m3 finite-code sweep bit-exact", np.array_equal(bits16(out).ravel(), ref.ravel()))
+
+
+# --------------------------------------------------------------------------
+# Real Bolt tensors (skip gracefully while the download is incomplete)
+# --------------------------------------------------------------------------
+
+def _open_shard(fname):
+ from safetensors import safe_open
+ path = os.path.join(MODEL_DIR, fname)
+ if not os.path.isfile(path):
+ return None
+ return safe_open(path, framework="pt")
+
+
+def _load_real():
+ """Returns dict of (tensor, meta) or None if any needed shard is missing."""
+ index_p = os.path.join(MODEL_DIR, "model.safetensors.index.json")
+ if not os.path.isfile(index_p):
+ return None
+ with open(index_p) as f:
+ wmap = json.load(f)["weight_map"]
+ need = {
+ "lm_head": "language_model.lm_head.weight",
+ "fc1": "language_model.backbone.layers.1.mixer.fc1_latent_proj.weight",
+ "exp_up": "language_model.backbone.layers.1.mixer.experts.0.up_proj.weight",
+ "exp_down": "language_model.backbone.layers.1.mixer.experts.0.down_proj.weight",
+ "in_w": "language_model.backbone.layers.0.mixer.in_proj.weight",
+ "in_s": "language_model.backbone.layers.0.mixer.in_proj.weight_scale",
+ "in_g": "language_model.backbone.layers.0.mixer.in_proj.weight_scale_2",
+ }
+ handles = {}
+ out = {}
+ try:
+ for k, name in need.items():
+ fn = wmap[name]
+ if fn not in handles:
+ h = _open_shard(fn)
+ if h is None:
+ return None
+ handles[fn] = h
+ t = handles[fn].get_tensor(name)
+ if "scale_2" in name:
+ out[k] = (t, None)
+ else:
+ out[k] = (t[:4].contiguous(), t.shape)
+ except Exception as e:
+ print(f" [SKIP] real tensors: {e}")
+ return None
+ return out
+
+
+def test_real():
+ real = _load_real()
+ if real is None:
+ print(" [SKIP] real tensors (shards not downloaded yet)")
+ return
+ dev = "cuda"
+ # Q8_0 lm_head rows: [4, 128, 34] -> [4, 4096]
+ t, _ = real["lm_head"]
+ raw = t.contiguous().numpy().reshape(-1, 128, 34)[:, :4, :]
+ ref = ref16(q8_0.dequant_q8_0(raw))
+ out = torch.empty((raw.shape[0], 128), dtype=torch.float16, device=dev)
+ ext.fq_dequant_q8_0(torch.from_numpy(raw).reshape(-1, 4, 34).cuda(), out)
+ torch.cuda.synchronize()
+ check("q8_0 real lm_head bit-exact", np.array_equal(bits16(out).ravel(), ref.ravel()))
+ # Q8_0 latent proj
+ t, _ = real["fc1"]
+ raw = t.contiguous().numpy().reshape(-1, 128, 34)[:, :4, :]
+ ref = ref16(q8_0.dequant_q8_0(raw))
+ out = torch.empty((raw.shape[0], 128), dtype=torch.float16, device=dev)
+ ext.fq_dequant_q8_0(torch.from_numpy(raw).reshape(-1, 4, 34).cuda(), out)
+ torch.cuda.synchronize()
+ check("q8_0 real fc1_latent_proj bit-exact", np.array_equal(bits16(out).ravel(), ref.ravel()))
+ # IQ2_XXS expert up/down
+ for k, per in (("exp_up", 1024), ("exp_down", 1024)):
+ t, _ = real[k]
+ raw = t.contiguous().numpy().reshape(-1, 4 if k == "exp_up" else 8, 66)[:, :2, :]
+ ref = ref16(iq2_xxs.dequant_iq2_xxs(raw))
+ out = torch.empty((raw.shape[0], 512), dtype=torch.float16, device=dev)
+ ext.fq_dequant_iq2_xxs(torch.from_numpy(raw).reshape(-1, 2, 66).cuda(), out)
+ torch.cuda.synchronize()
+ check(f"iq2_xxs real {k} bit-exact", np.array_equal(bits16(out).ravel(), ref.ravel()))
+ # NVFP4 in_proj
+ w, _ = real["in_w"]
+ s, _ = real["in_s"]
+ (g, _) = real["in_g"]
+ w_np = w.contiguous().view(torch.uint8).numpy().reshape(-1, 2048)[:, :64]
+ s_np = s.contiguous().view(torch.uint8).numpy().reshape(-1, 256)[:, :8]
+ gv = float(g.float().item())
+ ref = ref16(nvfp4.dequant_nvfp4(w_np, s_np, np.float32(gv)))
+ out = torch.empty((w_np.shape[0], 128), dtype=torch.float16, device=dev)
+ ext.fq_dequant_nvfp4(torch.from_numpy(w_np).cuda(), torch.from_numpy(s_np).cuda(), gv, out)
+ torch.cuda.synchronize()
+ check("nvfp4 real in_proj bit-exact", np.array_equal(bits16(out).ravel(), ref.ravel()))
+
+
+# --------------------------------------------------------------------------
+# Fused dequant-GEMM vs dequant + torch.matmul (fp16 tolerance)
+# --------------------------------------------------------------------------
+
+def _gemm_check(name, fmt, packed_np, scales_np, g, N, K, Mlist=(1, 2, 5, 16)):
+ dev = "cuda"
+ rng = np.random.default_rng(7)
+ if fmt == "q8_0":
+ w_ref = q8_0.dequant_q8_0(packed_np).reshape(N, K)
+ W = torch.from_numpy(packed_np).cuda()
+ def run(x, o):
+ ext.fq_gemm_q8_0(x, W, o)
+ elif fmt == "iq2_xxs":
+ w_ref = iq2_xxs.dequant_iq2_xxs(packed_np).reshape(N, K)
+ W = torch.from_numpy(packed_np).cuda()
+ def run(x, o):
+ ext.fq_gemm_iq2_xxs(x, W, o)
+ else:
+ w_ref = nvfp4.dequant_nvfp4(packed_np, scales_np, np.float32(g)).reshape(N, K)
+ W = torch.from_numpy(packed_np).cuda()
+ S = torch.from_numpy(scales_np).cuda()
+ def run(x, o):
+ ext.fq_gemm_nvfp4(x, W, S, float(g), o)
+ Wt = torch.from_numpy(w_ref).half().cuda()
+ worst_abs, worst_rel = 0.0, 0.0
+ for M in Mlist:
+ x = torch.from_numpy(rng.standard_normal((M, K)).astype(np.float32)).half().cuda() * 0.5
+ ref = torch.matmul(x.float(), Wt.t().float()).half()
+ out = torch.empty((M, N), dtype=torch.float16, device=dev)
+ run(x, out)
+ torch.cuda.synchronize()
+ d = (out.float() - ref.float()).abs()
+ worst_abs = max(worst_abs, d.max().item())
+ denom = ref.float().abs().clamp_min(1.0)
+ worst_rel = max(worst_rel, (d / denom).max().item())
+ # fp16 tolerance: one-ulp-level agreement (at 2048, 1 ulp = 2.0 absolute).
+ ok = worst_abs <= 1e-2 or worst_rel <= 5e-3
+ check(f"fq_gemm_{fmt} M={Mlist} within fp16 tol", ok,
+ f"max_abs_diff={worst_abs:.2e} worst_rel={worst_rel:.2e}")
+
+
+def test_gemm_synth():
+ rng = np.random.default_rng(11)
+ N, K = 256, 512
+ p = np.empty((N, K // 32, 34), np.uint8)
+ p[:, :, :2] = finite_scales(rng, (N, K // 32)).view(np.uint8).reshape(N, K // 32, 2)
+ p[:, :, 2:] = rng.integers(-64, 65, size=(N, K // 32, 32)).astype(np.int8).view(np.uint8)
+ _gemm_check("q8", "q8_0", p, None, 0.0, N, K)
+ p2 = rng.integers(0, 256, size=(N, K // 256, 66)).astype(np.uint8)
+ _gemm_check("iq2", "iq2_xxs", p2, None, 0.0, N, K)
+ pk = rng.integers(0, 256, size=(N, K // 2)).astype(np.uint8)
+ sc = rng.integers(0, 256, size=(N, K // 16)).astype(np.uint8)
+ sc[(sc == 0x7F) | (sc == 0xFF)] = 0x38
+ _gemm_check("nvfp4", "nvfp4", pk, sc, 0.5, N, K)
+
+
+def test_gemm_real_shapes():
+ # Bolt-native shapes: latent proj (Q8_0 4096->1024), expert up (IQ2 1024->2048).
+ rng = np.random.default_rng(13)
+ p = np.empty((1024, 128, 34), np.uint8)
+ p[:, :, :2] = finite_scales(rng, (1024, 128)).view(np.uint8).reshape(1024, 128, 2)
+ p[:, :, 2:] = rng.integers(-64, 65, size=(1024, 128, 32)).astype(np.int8).view(np.uint8)
+ _gemm_check("q8-latent", "q8_0", p, None, 0.0, 1024, 4096, Mlist=(1, 9, 16))
+ p2 = rng.integers(0, 256, size=(2048, 4, 66)).astype(np.uint8)
+ _gemm_check("iq2-expert", "iq2_xxs", p2, None, 0.0, 2048, 1024, Mlist=(1, 9, 16))
+
+
+def _gemv_check(name, fmt, packed_np, scales_np, g, N, K, Mlist=(1, 3)):
+ # Same contract as _gemm_check, but through the cooperative GEMV kernels
+ # (fq_gemv.cu): half and float in/out, out written directly in the
+ # requested dtype (no extra .to() copy).
+ dev = "cuda"
+ rng = np.random.default_rng(7)
+ if fmt == "q8_0":
+ w_ref = q8_0.dequant_q8_0(packed_np).reshape(N, K)
+ W = torch.from_numpy(packed_np).cuda()
+ def run(x, o):
+ ext.fq_gemv_q8_0(x, W, o)
+ elif fmt == "iq2_xxs":
+ w_ref = iq2_xxs.dequant_iq2_xxs(packed_np).reshape(N, K)
+ W = torch.from_numpy(packed_np).cuda()
+ def run(x, o):
+ ext.fq_gemv_iq2_xxs(x, W, o)
+ else:
+ w_ref = nvfp4.dequant_nvfp4(packed_np, scales_np, np.float32(g)).reshape(N, K)
+ W = torch.from_numpy(packed_np).cuda()
+ S = torch.from_numpy(scales_np).cuda()
+ def run(x, o):
+ # fp-tolerance contract is the fp32 dot's: pin the q8 path off
+ # (the q8 path has its own rms-normalized gate in test_q8nv).
+ os.environ["BOLT_FQ_Q8NV"] = "0"
+ try:
+ ext.fq_gemv_nvfp4(x, W, S, float(g), o)
+ finally:
+ os.environ.pop("BOLT_FQ_Q8NV", None)
+ Wt = torch.from_numpy(w_ref).half().cuda()
+ worst_abs, worst_rel = 0.0, 0.0
+ for M in Mlist:
+ x = torch.from_numpy(rng.standard_normal((M, K)).astype(np.float32)).half().cuda() * 0.5
+ ref = torch.matmul(x.float(), Wt.t().float())
+ for dt, xf in ((torch.float16, x), (torch.float32, x.float())):
+ out = torch.empty((M, N), dtype=dt, device=dev)
+ run(xf, out)
+ torch.cuda.synchronize()
+ d = (out.float() - ref).abs()
+ worst_abs = max(worst_abs, d.max().item())
+ denom = ref.abs().clamp_min(1.0)
+ worst_rel = max(worst_rel, (d / denom).max().item())
+ ok = worst_abs <= 1e-2 or worst_rel <= 5e-3
+ check(f"fq_gemv_{fmt} M={Mlist} h/f in+out within fp16 tol", ok,
+ f"max_abs_diff={worst_abs:.2e} worst_rel={worst_rel:.2e}")
+
+
+def test_gemv_synth():
+ rng = np.random.default_rng(11)
+ N, K = 256, 512
+ p = np.empty((N, K // 32, 34), np.uint8)
+ p[:, :, :2] = finite_scales(rng, (N, K // 32)).view(np.uint8).reshape(N, K // 32, 2)
+ p[:, :, 2:] = rng.integers(-64, 65, size=(N, K // 32, 32)).astype(np.int8).view(np.uint8)
+ _gemv_check("q8", "q8_0", p, None, 0.0, N, K)
+ p2 = rng.integers(0, 256, size=(N, K // 256, 66)).astype(np.uint8)
+ _gemv_check("iq2", "iq2_xxs", p2, None, 0.0, N, K)
+ pk = rng.integers(0, 256, size=(N, K // 2)).astype(np.uint8)
+ sc = rng.integers(0, 256, size=(N, K // 16)).astype(np.uint8)
+ sc[(sc == 0x7F) | (sc == 0xFF)] = 0x38
+ _gemv_check("nvfp4", "nvfp4", pk, sc, 0.5, N, K)
+
+
+def test_gemv_real_shapes():
+ # Bolt decode shapes incl. the wide ends (lm_head Q8_0, mamba NVFP4).
+ rng = np.random.default_rng(13)
+ p = np.empty((1024, 128, 34), np.uint8)
+ p[:, :, :2] = finite_scales(rng, (1024, 128)).view(np.uint8).reshape(1024, 128, 2)
+ p[:, :, 2:] = rng.integers(-64, 65, size=(1024, 128, 32)).astype(np.int8).view(np.uint8)
+ _gemv_check("q8-latent", "q8_0", p, None, 0.0, 1024, 4096)
+ p2 = rng.integers(0, 256, size=(2560, 4, 66)).astype(np.uint8)
+ _gemv_check("iq2-expert-up", "iq2_xxs", p2, None, 0.0, 2560, 1024)
+ pk = rng.integers(0, 256, size=(18560, 2048)).astype(np.uint8)
+ sc = rng.integers(0, 256, size=(18560, 256)).astype(np.uint8)
+ sc[(sc == 0x7F) | (sc == 0xFF)] = 0x38
+ _gemv_check("nvfp4-mamba-in", "nvfp4", pk, sc, 1.0, 18560, 4096, Mlist=(1,))
+
+
+def test_gemv_e4m3_sweep():
+ # Every E4M3 scale code through the GEMV LUT vs the dequant path.
+ dev = "cuda"
+ rng = np.random.default_rng(17)
+ N, K = 64, 256
+ pk = rng.integers(0, 256, size=(N, K // 2)).astype(np.uint8)
+ sc = np.arange(256, dtype=np.uint8)[None, :].repeat(N, axis=0)[:, :K // 16]
+ w_ref = nvfp4.dequant_nvfp4(pk, sc, np.float32(1.0)).reshape(N, K)
+ W = torch.from_numpy(pk).cuda()
+ S = torch.from_numpy(sc).cuda()
+ Wt = torch.from_numpy(w_ref).half().cuda()
+ x = torch.from_numpy(rng.standard_normal((1, K)).astype(np.float32)).half().cuda() * 0.3
+ ref = torch.matmul(x.float(), Wt.t().float())
+ out = torch.empty((1, N), dtype=torch.float16, device=dev)
+ ext.fq_gemv_nvfp4(x, W, S, 1.0, out)
+ torch.cuda.synchronize()
+ finite = torch.isfinite(ref)
+ d = (out.float() - ref).abs() / ref.abs().clamp_min(1.0)
+ d = torch.where(finite, d, torch.zeros_like(d))
+ check("fq_gemv_nvfp4 all-256 E4M3 codes", d.max().item() <= 5e-3,
+ f"worst_rel={d.max().item():.2e}")
+
+
+def test_moe_grouped():
+ # Grouped IQ2_XXS MoE (fq_moe.cu: up + down + fold launches) vs the
+ # manual per-expert fq_gemv + torch relu2-square + weighted fold.
+ # ones payload: codes zero -> w=1.0 exactly, keeps full Bolt sizes
+ # finite; random small checks summation-order agreement.
+ dev = torch.device("cuda", 0)
+ torch.manual_seed(2)
+ for tag, E, S, K, I, random in (
+ ("ones", 16, 9, 1024, 2048, False),
+ ("ones-bigE", 240, 9, 1024, 2560, False),
+ ("random-small", 8, 4, 256, 256, True),
+ ):
+ ups, downs = [], []
+ for is_up, (N, KK) in (True, (I, K)), (False, (K, I)):
+ for _ in range(E):
+ if random:
+ p = torch.randint(0, 256, (N, KK // 256, 64),
+ dtype=torch.uint8, device=dev)
+ o = torch.empty((N, KK // 256, 66), dtype=torch.uint8, device=dev)
+ o[..., 0:2] = torch.tensor([0x00, 0x3C], dtype=torch.uint8, device=dev)
+ o[..., 2:].copy_(p)
+ else:
+ o = torch.zeros((N, KK // 256, 66), dtype=torch.uint8, device=dev)
+ o[..., 0:2] = torch.tensor([0x00, 0x3C], dtype=torch.uint8, device=dev)
+ (ups if is_up else downs).append(o)
+ up_ptrs = torch.tensor([u.data_ptr() for u in ups], dtype=torch.int64, device=dev)
+ down_ptrs = torch.tensor([d.data_ptr() for d in downs], dtype=torch.int64, device=dev)
+ h = (torch.randn(1, K, device=dev) * (0.01 if random else 0.1)).half()
+ sel = torch.tensor(sorted(torch.randperm(E)[:S].tolist()), dtype=torch.long, device=dev)
+ wts = (torch.rand(S, device=dev).half() + 0.1)
+ ref = torch.zeros(1, K, dtype=torch.float32, device=dev)
+ for s in range(S):
+ e = int(sel[s])
+ u = torch.empty(1, I, dtype=torch.float16, device=dev)
+ ext.fq_gemv_iq2_xxs(h, ups[e], u)
+ a = torch.square(torch.relu(u))
+ p = torch.empty(1, K, dtype=torch.float32, device=dev)
+ ext.fq_gemv_iq2_xxs(a, downs[e], p)
+ ref += p * float(wts[s])
+ assert torch.isfinite(ref).all(), f"moe grouped {tag}: reference overflowed"
+ partial = torch.empty(S, K, dtype=torch.float32, device=dev)
+ out = torch.empty(1, K, dtype=torch.float32, device=dev)
+ ext.fq_moe_iq2xxs_grouped(h, sel, wts, up_ptrs, down_ptrs,
+ (K // 256) * 66, (I // 256) * 66, partial, out)
+ torch.cuda.synchronize()
+ d = (out - ref).abs()
+ rel = (d / (ref.abs() + 1.0)).max().item()
+ check(f"fq_moe_grouped {tag} E={E} S={S} K={K} I={I}",
+ rel <= 5e-3 and rel == rel, f"maxrel1={rel:.2e}")
+
+
+def test_mlp_shared():
+ # Fused shared-expert up+relu2 (fq_mlp.cu) vs the torch path it
+ # replaces (fq_gemv up + square(relu)): bit-identical expected (same
+ # dot grid, same epilogue arithmetic), full MLP checked within tol.
+ # ones payload keeps full Bolt sizes finite (K=4096, I=5376).
+ dev = torch.device("cuda", 0)
+ torch.manual_seed(3)
+ for tag, K, I, random in (("ones", 4096, 5376, False),
+ ("random-small", 256, 256, True)):
+ if random:
+ p = torch.randint(0, 256, (I, K // 256, 64), dtype=torch.uint8, device=dev)
+ up = torch.empty((I, K // 256, 66), dtype=torch.uint8, device=dev)
+ up[..., 0:2] = torch.tensor([0x00, 0x3C], dtype=torch.uint8, device=dev)
+ up[..., 2:].copy_(p)
+ pd = torch.randint(0, 256, (K, I // 256, 64), dtype=torch.uint8, device=dev)
+ down = torch.empty((K, I // 256, 66), dtype=torch.uint8, device=dev)
+ down[..., 0:2] = torch.tensor([0x00, 0x3C], dtype=torch.uint8, device=dev)
+ down[..., 2:].copy_(pd)
+ else:
+ up = torch.zeros((I, K // 256, 66), dtype=torch.uint8, device=dev)
+ up[..., 0:2] = torch.tensor([0x00, 0x3C], dtype=torch.uint8, device=dev)
+ down = torch.zeros((K, I // 256, 66), dtype=torch.uint8, device=dev)
+ down[..., 0:2] = torch.tensor([0x00, 0x3C], dtype=torch.uint8, device=dev)
+ x = (torch.randn(1, K, device=dev) * (0.01 if random else 0.1)).half()
+ u = torch.empty(1, I, dtype=torch.float16, device=dev)
+ ext.fq_gemv_iq2_xxs(x, up, u)
+ a = torch.square(torch.relu(u))
+ h = torch.empty(1, I, dtype=torch.float16, device=dev)
+ ext.fq_mlp_shared_iq2xxs(x, up, h)
+ torch.cuda.synchronize()
+ dh = (h.float() - a.float()).abs().max().item()
+ check(f"fq_mlp_shared {tag} up+relu2 K={K} I={I}", dh == 0.0, f"maxabs={dh:.2e}")
+ assert torch.isfinite(a).all(), f"mlp shared {tag}: reference overflowed"
+ po = torch.empty(1, K, dtype=torch.float32, device=dev)
+ ext.fq_gemv_iq2_xxs(a, down, po)
+ pf = torch.empty(1, K, dtype=torch.float32, device=dev)
+ ext.fq_gemv_iq2_xxs(h, down, pf)
+ torch.cuda.synchronize()
+ dd = (pf - po).abs().max().item()
+ check(f"fq_mlp_shared {tag} full-mlp K={K} I={I}", dd == 0.0, f"maxabs={dd:.2e}")
+
+
+def test_q8act():
+ # q8_1-activation IQ2_XXS path (Bolt phase 2, BOLT_FQ_Q8ACT=1): integer
+ # dp4a dots over once-per-row q8_1 activations, same arithmetic as
+ # llama.cpp's mmvq vec dots. Gate: quantize matches the ggml
+ # quantize_q8_1 arithmetic (d=amax/127, round-half-away) bit-exactly;
+ # q8 dots agree with the fp dots (top-1 + small rel diff) at Bolt
+ # shared shapes with small scales (real Bolt expert scales are ~1e-2;
+ # d=1.0 random payloads overflow fp16, same as the MoE tests note).
+ import struct
+ dev = torch.device("cuda", 0)
+ torch.manual_seed(11)
+ for K in (256, 1024, 4096):
+ x = (torch.randn(1, K, device=dev) * 0.3).half()
+ qb = torch.empty(1, (K // 32) * 36, dtype=torch.uint8, device=dev)
+ ext.fq_quant_q8_1_rows(x, qb)
+ torch.cuda.synchronize()
+ qbn = qb.cpu().numpy()
+ xf = x.cpu().float().numpy()[0]
+ worst_q, worst_d = 0, 0.0
+ for b in range(K // 32):
+ blk = qbn[0, b * 36:(b + 1) * 36]
+ d = struct.unpack("<e", bytes(blk[0:2]))[0]
+ ref = xf[b * 32:(b + 1) * 32].astype(np.float64)
+ amax = np.abs(ref).max()
+ dref = amax / 127.0
+ # round-half-away (ggml), not numpy banker's: allow off-by-one
+ q = blk[4:].astype(np.int8).astype(np.int32)
+ qe = np.zeros(32, dtype=np.int32) if amax == 0 else np.clip(
+ np.floor(ref / dref + 0.5), -127, 127).astype(np.int32)
+ worst_q = max(worst_q, int(np.abs(q - qe).max()))
+ worst_d = max(worst_d, abs(d - dref))
+ check(f"fq_q8act quant K={K}", worst_q <= 1 and worst_d <= 2e-3,
+ f"maxqdiff={worst_q} maxdd={worst_d:.2e}")
+ for tag, N, K in (("shared_up", 5376, 4096), ("shared_down", 4096, 5376),
+ ("expert_up", 2560, 1024), ("expert_down", 1024, 2560)):
+ p = torch.randint(0, 256, (N, K // 256, 64), dtype=torch.uint8, device=dev)
+ sc = (torch.rand(N, K // 256, device=dev) * 0.02).half()
+ scb = sc.cpu().numpy().view(np.uint8).reshape(N, K // 256, 2)
+ pk = torch.empty((N, K // 256, 66), dtype=torch.uint8, device=dev)
+ pk[..., 0:2].copy_(torch.from_numpy(scb).to(dev))
+ pk[..., 2:].copy_(p)
+ x = (torch.randn(2, K, device=dev) * 0.1).half()
+ oo = torch.empty(2, N, dtype=torch.float, device=dev)
+ os.environ["BOLT_FQ_Q8ACT"] = "1"
+ ext.fq_gemv_iq2_xxs(x, pk, oo)
+ torch.cuda.synchronize()
+ new = oo.clone().float()
+ os.environ.pop("BOLT_FQ_Q8ACT", None)
+ ext.fq_gemv_iq2_xxs(x, pk, oo)
+ torch.cuda.synchronize()
+ old = oo.clone().float()
+ assert torch.isfinite(old).all() and torch.isfinite(new).all(), \
+ f"q8act {tag}: overflow (scales too big?)"
+ d = (new - old).abs()
+ rel = (d / (old.abs() + 1.0))
+ agree = (new.argmax(1) == old.argmax(1)).sum().item()
+ check(f"fq_q8act gemv {tag}", agree == 2 and rel.max().item() <= 0.3
+ and rel.mean().item() <= 3e-2,
+ f"top1={agree}/2 maxrel={rel.max().item():.2e} meanrel={rel.mean().item():.2e}")
+
+
+def test_q8nv():
+ # q8_1-activation NVFP4 + Q8_0 paths (Bolt phase 2, BOLT_FQ_Q8NV=1 /
+ # BOLT_FQ_Q8Q8=1): integer dp4a dots over once-per-row q8_1 activations,
+ # same factorization as llama.cpp's vec_dot_nvfp4_q8_1 / vec_dot_q8_0_q8_1
+ # (doubled-e2m1 int8 table + halved ue4m3 scale; direct int8 for Q8).
+ # Gate: exact-arithmetic payloads (lossless activation quant) match the
+ # closed form to fp16-scale noise; random payloads agree with the fp
+ # dots at the activation-quant noise floor (rms-normalized).
+ dev = torch.device("cuda", 0)
+ torch.manual_seed(0)
+ os.environ["BOLT_FQ_Q8NV"] = "1"
+ os.environ["BOLT_FQ_Q8Q8"] = "1"
+ try:
+ for N, K in ((256, 1024), (4096, 8192)):
+ p = torch.full((N, K // 2), 0x55, dtype=torch.uint8, device=dev)
+ s = torch.full((N, K // 16), 0x38, dtype=torch.uint8, device=dev)
+ x = torch.full((1, K), 0.5, dtype=torch.half, device=dev)
+ oo = torch.empty(1, N, dtype=torch.float, device=dev)
+ ext.fq_gemv_nvfp4(x, p, s, 0.5, oo, True)
+ torch.cuda.synchronize()
+ rel = ((oo.float() - 0.75 * K).abs() / (0.75 * K)).max().item()
+ check(f"fq_q8nv exact {N}x{K}", rel < 1e-3, f"maxrel={rel:.2e}")
+ for tag, N, K in (("mamba_in", 18560, 4096), ("mamba_out", 4096, 8192)):
+ p = torch.randint(0, 256, (N, K // 2), dtype=torch.uint8, device=dev)
+ se = torch.randint(5, 9, (N, K // 16), device=dev, dtype=torch.uint8)
+ sm = torch.randint(0, 8, (N, K // 16), device=dev, dtype=torch.uint8)
+ s = (se << 3) | sm
+ x = (torch.randn(2, K, device=dev) * 0.1).half()
+ oo = torch.empty(2, N, dtype=torch.float, device=dev)
+ ext.fq_gemv_nvfp4(x, p, s, 1.0, oo, True)
+ torch.cuda.synchronize()
+ new = oo.clone()
+ os.environ["BOLT_FQ_Q8NV"] = "0"
+ ext.fq_gemv_nvfp4(x, p, s, 1.0, oo, True)
+ torch.cuda.synchronize()
+ old = oo.clone()
+ os.environ["BOLT_FQ_Q8NV"] = "1"
+ d = (new - old).abs()
+ rms = old.pow(2).mean().sqrt().item()
+ agree = (new.argmax(1) == old.argmax(1)).sum().item()
+ check(f"fq_q8nv {tag}", agree == 2 and (d.max().item() / rms) <= 0.1,
+ f"top1={agree}/2 max/rms={(d.max().item() / rms):.2e}")
+ for tag, N, K in (("latent", 1024, 4096), ("lm_head", 4096, 4096)):
+ o = torch.empty((N, K // 32, 34), dtype=torch.uint8, device=dev)
+ o[..., 0:2] = torch.tensor([0x00, 0x3C], dtype=torch.uint8, device=dev)
+ o[..., 2:].copy_(torch.randint(0, 256, (N, K // 32, 32),
+ dtype=torch.uint8, device=dev))
+ x = (torch.randn(2, K, device=dev) * 0.3).half()
+ oo = torch.empty(2, N, dtype=torch.float, device=dev)
+ ext.fq_gemv_q8_0(x, o, oo)
+ torch.cuda.synchronize()
+ new = oo.clone()
+ os.environ["BOLT_FQ_Q8Q8"] = "0"
+ ext.fq_gemv_q8_0(x, o, oo)
+ torch.cuda.synchronize()
+ old = oo.clone()
+ os.environ["BOLT_FQ_Q8Q8"] = "1"
+ d = (new - old).abs()
+ rms = old.pow(2).mean().sqrt().item()
+ agree = (new.argmax(1) == old.argmax(1)).sum().item()
+ check(f"fq_q8q8 {tag}", agree == 2 and (d.max().item() / rms) <= 0.1,
+ f"top1={agree}/2 max/rms={(d.max().item() / rms):.2e}")
+ finally:
+ os.environ.pop("BOLT_FQ_Q8NV", None)
+ os.environ.pop("BOLT_FQ_Q8Q8", None)
+
+
+def test_q8moe():
+ # q8_1-activation grouped MoE (Bolt phase 2, BOLT_FQ_Q8MOE=1): same
+ # (slot, tile) grid as fq_moe.cu, integer-dp4a lane dots over
+ # once-per-step q8_1 activations. Gate: ones payload (all experts
+ # identical, full-scale, no cancellation) + small-scale random
+ # payload, vs the fp grouped path (rms-normalized: random payloads
+ # cancel in the fold, so absolute-tolerance metrics mislead).
+ dev = torch.device("cuda", 0)
+ torch.manual_seed(2)
+ E, S, K, I = 8, 3, 1024, 2560
+ for tag, ones in (("ones", True), ("small", False)):
+ ups, downs = [], []
+ for _ in range(E):
+ for lst, N, KK in ((ups, I, K), (downs, K, I)):
+ o = torch.empty((N, KK // 256, 66), dtype=torch.uint8, device=dev)
+ if ones:
+ o[..., 0:2] = torch.tensor([0x00, 0x3C], dtype=torch.uint8, device=dev)
+ o[..., 2:].fill_(1)
+ else:
+ sc = (torch.rand(N, KK // 256, device=dev) * 0.02).half()
+ scb = sc.cpu().numpy().view(np.uint8).reshape(N, KK // 256, 2)
+ o[..., 0:2].copy_(torch.from_numpy(scb).to(dev))
+ o[..., 2:].copy_(torch.randint(0, 256, (N, KK // 256, 64),
+ dtype=torch.uint8, device=dev))
+ lst.append(o)
+ up_ptrs = torch.tensor([u.data_ptr() for u in ups], dtype=torch.int64, device=dev)
+ down_ptrs = torch.tensor([d.data_ptr() for d in downs], dtype=torch.int64, device=dev)
+ h = (torch.randn(1, K, device=dev) * 0.1).half()
+ sel = torch.tensor([0, 2, 5], dtype=torch.long, device=dev)
+ wts = (torch.rand(S, device=dev).half() + 0.1)
+ partial = torch.empty(S, K, dtype=torch.float32, device=dev)
+ out = torch.empty(1, K, dtype=torch.float32, device=dev)
+ up_s, down_s = (K // 256) * 66, (I // 256) * 66
+ os.environ["BOLT_FQ_Q8MOE"] = "1"
+ ext.fq_moe_iq2xxs_grouped(h, sel, wts, up_ptrs, down_ptrs, up_s, down_s, partial, out)
+ torch.cuda.synchronize()
+ new = out.clone()
+ os.environ.pop("BOLT_FQ_Q8MOE", None)
+ ext.fq_moe_iq2xxs_grouped(h, sel, wts, up_ptrs, down_ptrs, up_s, down_s, partial, out)
+ torch.cuda.synchronize()
+ old = out.clone()
+ okf = bool(torch.isfinite(old).all() and torch.isfinite(new).all())
+ d = (new - old).abs()
+ rms = old.pow(2).mean().sqrt().item()
+ check(f"fq_q8moe {tag}", okf and (d.max().item() / rms) <= 0.15,
+ f"finite={okf} max/rms={(d.max().item() / rms):.2e}")
+
+
+def test_q8v2():
+ # v2 IQ2_XXS q8 dot (Bolt phase 2 step 13, BOLT_FQ_Q8V2=1): same
+ # integer arithmetic as the v1 dot (const-grid like llama's
+ # iq2xxs_grid, inline ksigns unpack, direct u16 header loads; no
+ # header staging, no signs32 table, one barrier). Gate: BITWISE vs
+ # v1 on shared/expert shapes (ones payload: exact, no fp16
+ # rounding in the reference path) + grouped-MoE bitwise vs v1.
+ dev = torch.device("cuda", 0)
+ torch.manual_seed(3)
+ os.environ["BOLT_FQ_Q8ACT"] = "1"
+ try:
+ for tag, N, K in (("shared_up", 5376, 4096), ("shared_down", 4096, 5376),
+ ("expert_up", 2560, 1024), ("expert_down", 1024, 2560)):
+ p = torch.empty((N, K // 256, 66), dtype=torch.uint8, device=dev)
+ p[..., 0:2] = torch.tensor([0x00, 0x3C], dtype=torch.uint8, device=dev)
+ p[..., 2:].fill_(1)
+ x = (torch.randn(1, K, device=dev) * 0.3).half()
+ oo = torch.empty(1, N, dtype=torch.float, device=dev)
+ os.environ["BOLT_FQ_Q8V2"] = "1"
+ ext.fq_gemv_iq2_xxs(x, p, oo)
+ torch.cuda.synchronize()
+ new = oo.clone()
+ os.environ["BOLT_FQ_Q8V2"] = "0"
+ ext.fq_gemv_iq2_xxs(x, p, oo)
+ torch.cuda.synchronize()
+ old = oo.clone()
+ nbad = int((new != old).sum())
+ check(f"fq_q8v2 gemv {tag}", nbad == 0, f"nbad={nbad}/{N}")
+ # grouped MoE + fused shared MLP take the same v2 dot: bitwise.
+ E, S, K, I = 8, 3, 1024, 2560
+ ups, downs = [], []
+ for _ in range(E):
+ for lst, N, KK in ((ups, I, K), (downs, K, I)):
+ o = torch.empty((N, KK // 256, 66), dtype=torch.uint8, device=dev)
+ o[..., 0:2] = torch.tensor([0x00, 0x3C], dtype=torch.uint8, device=dev)
+ o[..., 2:].fill_(1)
+ lst.append(o)
+ up_ptrs = torch.tensor([u.data_ptr() for u in ups], dtype=torch.int64, device=dev)
+ down_ptrs = torch.tensor([d.data_ptr() for d in downs], dtype=torch.int64, device=dev)
+ h = (torch.randn(1, K, device=dev) * 0.1).half()
+ sel = torch.tensor([0, 2, 5], dtype=torch.long, device=dev)
+ wts = (torch.rand(S, device=dev).half() + 0.1)
+ partial = torch.empty(S, K, dtype=torch.float32, device=dev)
+ out = torch.empty(1, K, dtype=torch.float32, device=dev)
+ up_s, down_s = (K // 256) * 66, (I // 256) * 66
+ os.environ["BOLT_FQ_Q8MOE"] = "1"
+ os.environ["BOLT_FQ_Q8V2"] = "1"
+ ext.fq_moe_iq2xxs_grouped(h, sel, wts, up_ptrs, down_ptrs, up_s, down_s, partial, out)
+ torch.cuda.synchronize()
+ new = out.clone()
+ os.environ["BOLT_FQ_Q8V2"] = "0"
+ ext.fq_moe_iq2xxs_grouped(h, sel, wts, up_ptrs, down_ptrs, up_s, down_s, partial, out)
+ torch.cuda.synchronize()
+ old = out.clone()
+ nbad = int((new != old).sum())
+ check("fq_q8v2 grouped", nbad == 0, f"nbad={nbad}/{K}")
+ os.environ.pop("BOLT_FQ_Q8MOE", None)
+ finally:
+ os.environ.pop("BOLT_FQ_Q8ACT", None)
+ os.environ.pop("BOLT_FQ_Q8V2", None)
+
+
+def main():
+ assert torch.cuda.is_available(), "CUDA required"
+ for f in ("fq_dequant_q8_0", "fq_dequant_iq2_xxs", "fq_dequant_nvfp4",
+ "fq_gemm_q8_0", "fq_gemm_iq2_xxs", "fq_gemm_nvfp4",
+ "fq_gemv_q8_0", "fq_gemv_iq2_xxs", "fq_gemv_nvfp4",
+ "fq_moe_iq2xxs_grouped", "fq_mlp_shared_iq2xxs",
+ "fq_quant_q8_1_rows", "fq_gemv_iq2_xxs_q8",
+ "fq_gemv_nvfp4_q8", "fq_gemv_q8_0_q8"):
+ assert hasattr(ext, f), f"ext missing {f} (rebuild?)"
+ print(f"ext: {ext.__file__} cuda={torch.cuda.get_device_name(0)}")
+ t0 = torch.cuda.Event(enable_timing=True)
+ t1 = torch.cuda.Event(enable_timing=True)
+ t0.record()
+ test_q8_0_synth()
+ test_iq2_xxs_synth()
+ test_nvfp4_synth()
+ test_nvfp4_e4m3_finite_sweep()
+ test_real()
+ test_gemm_synth()
+ test_gemm_real_shapes()
+ test_gemv_synth()
+ test_gemv_real_shapes()
+ test_gemv_e4m3_sweep()
+ test_moe_grouped()
+ test_mlp_shared()
+ test_q8act()
+ test_q8nv()
+ test_q8moe()
+ test_q8v2()
+ t1.record()
+ torch.cuda.synchronize()
+ print(f"done in {t0.elapsed_time(t1) / 1000:.1f}s: {len(PASS)} pass, {len(FAIL)} fail")
+ if FAIL:
+ print("FAILURES:", FAIL)
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/test_kernel_seed.py b/tests/test_kernel_seed.py
new file mode 100644
index 0000000..92ac5d0
--- /dev/null
+++ b/tests/test_kernel_seed.py
@@ -0,0 +1,173 @@
+"""Kernel seed: portable HIP cache keys, install() and pack() (CPU only; needs a Triton wheel with the AMD backend)."""
+import json, os, subprocess, sys, tempfile
+from pathlib import Path
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
+from exllamav3.util import kernel_seed
+
+REPO = str(Path(__file__).resolve().parents[1])
+
+CHILD = r'''
+import hashlib, json, sys
+sys.path.insert(0, sys.argv[1])
+import triton, triton.language as tl
+from triton.backends.compiler import GPUTarget
+from triton.compiler import ASTSource, make_backend
+from triton.compiler.compiler import get_cache_key
+sys.path.insert(0, sys.argv[2])
+from exllamav3.util import kernel_seed
+
+def k(x_ptr, n, BLOCK: tl.constexpr):
+ i = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)
+ tl.store(x_ptr + i, tl.load(x_ptr + i, mask=i < n) + 1, mask=i < n)
+
+def key():
+ backend = make_backend(GPUTarget("hip", "gfx1151", 32))
+ src = ASTSource(k, {"x_ptr": "*fp32", "n": "i32"}, {"BLOCK": 128})
+ return hashlib.sha256(get_cache_key(src, backend, backend.parse_options({"num_warps": 4}), {}).encode()).hexdigest()
+
+raw = key()
+ok = kernel_seed.portable_keys("gfx1151")
+print(json.dumps({"raw": raw, "ok": ok, "portable": key()}))
+'''
+
+
+def _skip(msg):
+ try:
+ import pytest
+ pytest.skip(msg)
+ except ImportError:
+ print("skip:", msg)
+
+
+def _have_amd_triton() -> bool:
+ try:
+ from triton.backends.amd import compiler # noqa: F401
+ return True
+ except Exception:
+ return False
+
+
+def _farm(src: Path, dst: Path):
+ """dst/triton: symlinks to the real package, except the directories on the way to backends/amd/compiler.py, which are real
+ (the file is copied): the same Triton under another install prefix."""
+ def rec(s: Path, d: Path, rel=()):
+ d.mkdir(parents=True, exist_ok=True)
+ for e in s.iterdir():
+ r = rel + (e.name,)
+ if r == ("backends", "amd", "compiler.py"):
+ (d / e.name).write_bytes(e.read_bytes())
+ elif r in (("backends",), ("backends", "amd")):
+ rec(e, d / e.name, r)
+ else:
+ (d / e.name).symlink_to(e)
+ rec(src, dst / "triton")
+
+
+def test_cache_key_is_the_same_under_another_install_prefix():
+ if not _have_amd_triton():
+ return _skip("no Triton with the AMD backend")
+ import triton
+ real = Path(triton.__file__).parent
+ outs = []
+ with tempfile.TemporaryDirectory() as td:
+ sites = [None, Path(td) / "one" / "site", Path(td) / "second" / "other" / "site"]
+ for site in sites[1:]:
+ site.mkdir(parents=True)
+ _farm(real, site)
+ child = Path(td) / "child.py"
+ child.write_text(CHILD)
+ env = {k: v for k, v in os.environ.items() if k != "PYTHONPATH"}
+ for site in sites:
+ r = subprocess.run([sys.executable, str(child), str(site or "/nonexistent"), REPO], capture_output=True, text=True, env=env)
+ assert r.returncode == 0, r.stderr[-2000:]
+ outs.append(json.loads(r.stdout.strip().splitlines()[-1]))
+ assert all(o["ok"] for o in outs)
+ assert len({o["raw"] for o in outs}) == 3 # Triton's own key depends on the prefix ...
+ assert len({o["portable"] for o in outs}) == 1 # ... the seed's does not
+
+
+def test_scrub_json_and_local_path_check():
+ meta = json.dumps({"extern_libs": [["ocml", "/opt/x/.venv/lib/python3.12/site-packages/triton/backends/amd/lib/ocml.bc"],
+ ["ockl", "/home/u/v/triton/backends/amd/lib/ockl.bc"]], "name": "k"}).encode()
+ out = kernel_seed._scrub_json(meta)
+ assert json.loads(out)["extern_libs"] == [["ocml", kernel_seed.LIB_PLACEHOLDER + "/ocml.bc"], ["ockl", kernel_seed.LIB_PLACEHOLDER + "/ockl.bc"]]
+ assert not kernel_seed._LOCAL_PATH.search(out)
+ assert kernel_seed._LOCAL_PATH.search(b"x /home/someone/repo/file.py y")
+ assert kernel_seed._LOCAL_PATH.search(b"C:\\Users\\me")
+ assert not kernel_seed._LOCAL_PATH.search(b"amdgcn-amd-amdhsa--gfx1151 exllamav3/modules/attention.py")
+
+
+def test_pack_refuses_a_member_with_a_local_path():
+ with tempfile.TemporaryDirectory() as td:
+ cache, kdir = Path(td) / "cache", Path(td) / "cache" / "KEY"
+ kdir.mkdir(parents=True)
+ (kdir / "k.autotune.json").write_text(json.dumps({"key": [1], "path": "/home/someone/x"}))
+ try:
+ kernel_seed.pack(cache, Path(td) / "out.tar.xz")
+ except RuntimeError as exc:
+ assert "local path" in str(exc)
+ else:
+ raise AssertionError("pack() accepted a local path")
+
+
+def test_pack_merges_caches_first_wins():
+ import tarfile
+ with tempfile.TemporaryDirectory() as td:
+ a, b = Path(td) / "a", Path(td) / "b"
+ for root, keys in ((a, ("K1", "K2")), (b, ("K2", "K3"))):
+ for k in keys:
+ (root / k).mkdir(parents=True)
+ (root / k / "f.autotune.json").write_text(json.dumps({"from": root.name}))
+ out = Path(td) / "o.tar.xz"
+ assert kernel_seed.pack([a, b], out) == 3
+ with tarfile.open(out) as tf:
+ got = {m.name: json.load(tf.extractfile(m))["from"] for m in tf.getmembers()}
+ assert got == {"K1/f.autotune.json": "a", "K2/f.autotune.json": "a", "K3/f.autotune.json": "b"}
+
+
+def test_install_other_architecture_and_off_switch_do_nothing():
+ with tempfile.TemporaryDirectory() as td:
+ for arch in ("gfx1100", "sm_89"):
+ assert kernel_seed.install(arch, cache = Path(td) / "c") == 0
+ os.environ["EXL3_KERNEL_SEED"] = "0"
+ try:
+ assert kernel_seed.install("gfx1151", cache = Path(td) / "c") == 0
+ finally:
+ del os.environ["EXL3_KERNEL_SEED"]
+ assert not (Path(td) / "c").exists()
+
+
+def test_shipped_seed_has_no_local_path_and_installs_with_this_prefix():
+ if not _have_amd_triton():
+ return _skip("no Triton with the AMD backend")
+ seed = kernel_seed.find_seed("gfx1151")
+ if seed is None:
+ return _skip("no seed for this Triton version")
+ import tarfile
+ libdir = kernel_seed._amd_libdir()
+ with tarfile.open(seed, "r:xz") as tf:
+ members = [m for m in tf.getmembers() if m.isfile()]
+ assert members
+ for m in members:
+ data = tf.extractfile(m).read()
+ assert not kernel_seed._LOCAL_PATH.search(data), m.name
+ keys = {m.name.split("/")[0] for m in members}
+ with tempfile.TemporaryDirectory() as td:
+ cache = Path(td) / "cache"
+ assert kernel_seed.install("gfx1151", cache = cache, log = lambda s: None) == len(keys)
+ assert kernel_seed.install("gfx1151", cache = cache, log = lambda s: None) == 0 # never overwrites
+ for j in cache.glob("*/*.json"):
+ if j.name.startswith("__grp__") or j.name.endswith(".autotune.json"):
+ continue
+ text = j.read_text()
+ assert kernel_seed.LIB_PLACEHOLDER not in text
+ for lib in json.loads(text)["extern_libs"]:
+ assert lib[1].startswith(libdir)
+ assert kernel_seed.portable_keys("gfx1151")
+
+
+if __name__ == "__main__":
+ for n, f in list(globals().items()):
+ if n.startswith("test_"):
+ f(); print("ok", n)
diff --git a/tests/test_moe_foreign.py b/tests/test_moe_foreign.py
new file mode 100644
index 0000000..7bff120
--- /dev/null
+++ b/tests/test_moe_foreign.py
@@ -0,0 +1,135 @@
+"""MoE-path test: IQ2_XXS routed experts through BlockSparseMLP dispatch.
+
+Builds a tiny 2-expert gateless-relu2 BlockSparseMLP whose ups/downs are
+ForeignLinear (raw IQ2_XXS payloads), drives forward() with pre-routed
+picks (params["dec_routed"], no router needed), and checks against a manual
+numpy-dequant + torch reference. Runs fused (fq_gemm_*) and unfused
+(dequant + matmul) and requires both to match.
+
+Standalone script (CUDA venv has no pytest):
+ python tests/test_moe_foreign.py
+"""
+from __future__ import annotations
+
+import importlib.util
+import os
+import sys
+
+import numpy as np
+import torch
+
+ENGINE = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
+sys.path.insert(0, ENGINE)
+
+
+def _load_pkg(name, path):
+ spec = importlib.util.spec_from_file_location(name, path)
+ mod = importlib.util.module_from_spec(spec)
+ sys.modules[name] = mod
+ spec.loader.exec_module(mod)
+ return mod
+
+
+iq2_xxs = _load_pkg("fq_iq2_ref", os.path.join(ENGINE, "exllamav3", "foreign_quant", "iq2_xxs.py"))
+
+from exllamav3.modules.foreign_linear import ForeignLinear # noqa: E402
+import exllamav3.modules.foreign_linear as fl_mod # noqa: E402
+from exllamav3.modules.block_sparse_mlp import BlockSparseMLP # noqa: E402
+
+PASS, FAIL = [], []
+
+
+def check(name, cond, detail=""):
+ print(f" [{'PASS' if cond else 'FAIL'}] {name} {detail}")
+ (PASS if cond else FAIL).append(name)
+
+
+def make_expert_pack(rng, out_f, in_f):
+ assert in_f % 256 == 0
+ p = rng.integers(0, 256, size=(out_f, in_f // 256, 66)).astype(np.uint8)
+ # Small fixed scale (real Bolt expert scales are ~1e-2; random fp16
+ # scales up to 6e4 overflow fp16 matmuls to inf -> inf-inf NaN diffs;
+ # and 0.005-scale weights amplify 1-ulp GEMM diffs through relu2 to 4%
+ # at the composed output, while 0.002 keeps the composed check tight).
+ p[:, :, 0] = np.float16(0.002).tobytes()[0]
+ p[:, :, 1] = np.float16(0.002).tobytes()[1]
+ return p
+
+
+def main():
+ # Dispatch-equivalence contract is the fp dots': pin all q8 paths off
+ # (their numeric contract lives in test_foreign_quant_cuda's q8 gates).
+ os.environ["BOLT_FQ_Q8ACT"] = "0"
+ os.environ["BOLT_FQ_Q8MOE"] = "0"
+ assert torch.cuda.is_available(), "CUDA required"
+ dev = torch.device("cuda")
+ rng = np.random.default_rng(21)
+ H, I, E, TOP = 256, 256, 2, 2
+
+ packs_up = [make_expert_pack(rng, I, H) for _ in range(E)]
+ packs_dn = [make_expert_pack(rng, H, I) for _ in range(E)]
+ # Reference fp16 weights.
+ ref_up = [torch.from_numpy(iq2_xxs.dequant_iq2_xxs(p).reshape(I, H)).half().cuda()
+ for p in packs_up]
+ ref_dn = [torch.from_numpy(iq2_xxs.dequant_iq2_xxs(p).reshape(H, I)).half().cuda()
+ for p in packs_dn]
+
+ ups, downs = [], []
+ for e in range(E):
+ u = ForeignLinear(None, f"moe.exp{e}.up", H, I, "iq2_xxs")
+ u.packed = torch.from_numpy(packs_up[e]).cuda()
+ u.device = dev
+ d = ForeignLinear(None, f"moe.exp{e}.down", I, H, "iq2_xxs",
+ out_dtype=torch.float)
+ d.packed = torch.from_numpy(packs_dn[e]).cuda()
+ d.device = dev
+ ups.append(u)
+ downs.append(d)
+
+ moe = BlockSparseMLP(
+ None, "moe", hidden_size=H, intermediate_size=I,
+ num_experts=E, num_experts_per_tok=TOP,
+ activation_fn="relu2", gates=[], ups=ups, downs=downs,
+ )
+ for m in ups + downs:
+ moe.register_submodule(m)
+ moe.device = dev
+
+ xr = rng.standard_normal((3, H)).astype(np.float32) * 0.5
+ sel = torch.tensor([[0, 1], [1, 0], [1, 1]], dtype=torch.long, device=dev)
+ wts = torch.tensor([[0.6, 0.4], [0.3, 0.7], [0.5, 0.5]], dtype=torch.float16, device=dev)
+
+ def reference(x):
+ outs = []
+ for r in range(x.shape[0]):
+ acc = torch.zeros(H, dtype=torch.float32, device=dev)
+ for k in range(TOP):
+ e = int(sel[r, k])
+ u = torch.matmul(x[r:r + 1].half(), ref_up[e].t())
+ a = torch.square(torch.relu(u))
+ o = torch.matmul(a.half(), ref_dn[e].t())
+ acc += float(wts[r, k]) * o.float().ravel()
+ outs.append(acc)
+ return torch.stack(outs)
+
+ def tol(name, got, ref):
+ d = (got.float() - ref.float()).abs()
+ worst = d.max().item()
+ wrel = (d / ref.float().abs().clamp_min(1.0)).max().item()
+ check(name, worst <= 1e-2 or wrel <= 5e-3, f"max_abs={worst:.2e} wrel={wrel:.2e}")
+
+ x = torch.from_numpy(xr).half().cuda()
+ fl_mod._FUSED = False
+ y_unfused = moe.forward(x, {"dec_routed": (sel, wts)})
+ tol("moe dispatch unfused vs manual", y_unfused, reference(x))
+ assert y_unfused.shape == (3, H), y_unfused.shape
+ fl_mod._FUSED = True
+ y_fused = moe.forward(x, {"dec_routed": (sel, wts)})
+ tol("moe dispatch fused vs unfused", y_fused, y_unfused)
+
+ print(f"done: {len(PASS)} pass, {len(FAIL)} fail")
+ return 1 if FAIL else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/test_multimodal_rewind_prefill.py b/tests/test_multimodal_rewind_prefill.py
index 7fab339..3b274ad 100644
--- a/tests/test_multimodal_rewind_prefill.py
+++ b/tests/test_multimodal_rewind_prefill.py
@@ -73,6 +73,8 @@ def make_job(prompt_length, sequence_length, replay_start, *, image=True, image_
cache=None,
draft_model=None,
mtp_draft=mtp,
+ tail_ckpt_max=0, # prompt-tail checkpoints off: Job._tail_ok() reads it before the normal path
+ wide_prefill_chunks=lambda: (False, False), # Job.prefill asks whether the model takes wide prefill chunks (SWA-only fused MoE)
)
if atomic:
# Gemma 4: chunks ending inside an image span are extended to cover the whole span
diff --git a/tests/test_nemotron_puzzle_cpu.py b/tests/test_nemotron_puzzle_cpu.py
new file mode 100644
index 0000000..66e9477
--- /dev/null
+++ b/tests/test_nemotron_puzzle_cpu.py
@@ -0,0 +1,235 @@
+"""CPU-only tests for the Nemotron-H Puzzle config adapter.
+
+Loads ``exllamav3/architecture/nemotronh_puzzle.py`` directly by file path so
+the test runs without torch (the adapter module is stdlib-only by design).
+Validates against the real Bolt checkpoint config when available
+(``$BOLT_CONFIG_JSON``) plus a hermetic synthetic fixture that always runs.
+"""
+from __future__ import annotations
+
+import importlib.util
+import json
+import os
+import sys
+
+import pytest
+
+ADAPTER_PATH = os.path.abspath(os.path.join(
+ os.path.dirname(__file__), "..", "exllamav3", "architecture", "nemotronh_puzzle.py"))
+REAL_CONFIG = os.environ.get(
+ "BOLT_CONFIG_JSON", "")
+
+
+def _load_adapter():
+ name = "nemotronh_puzzle_adapter_under_test"
+ spec = importlib.util.spec_from_file_location(name, ADAPTER_PATH)
+ mod = importlib.util.module_from_spec(spec)
+ sys.modules[name] = mod # dataclasses need the module registered pre-exec
+ spec.loader.exec_module(mod)
+ return mod
+
+
+ap = _load_adapter()
+
+
+def _needs_real_config():
+ return pytest.mark.skipif(
+ not os.path.isfile(REAL_CONFIG),
+ reason=f"Bolt config not found: {REAL_CONFIG}")
+
+
+def _real_llm():
+ with open(REAL_CONFIG, encoding="utf8") as f:
+ return json.load(f)["llm_config"]
+
+
+# --------------------------------------------------------------------------
+# Real Bolt config
+# --------------------------------------------------------------------------
+
+@_needs_real_config()
+def test_bolt_block_layout():
+ spec = ap.load_puzzle_spec(REAL_CONFIG)
+ assert spec.from_omni_wrapper is True
+ assert spec.num_hidden_layers == 88
+ assert len(spec.blocks) == 88
+ assert spec.block_counts == {"mamba": 40, "moe": 40, "attention": 8}
+ assert spec.attention_indices == (7, 16, 25, 36, 47, 58, 69, 78)
+
+
+@_needs_real_config()
+def test_bolt_per_layer_experts_match_block_configs():
+ llm = _real_llm()
+ spec = ap.load_puzzle_spec(REAL_CONFIG)
+ assert len(llm["block_configs"]) == len(llm["layers_block_type"]) == 88
+ for i, (node, bcfg, btype) in enumerate(
+ zip(spec.blocks, llm["block_configs"], llm["layers_block_type"])):
+ assert node.index == i
+ assert node.block_type == btype == bcfg["block_type"]
+ if btype == "moe":
+ assert node.n_routed_experts == bcfg["n_routed_experts"] > 0
+ assert node.moe_intermediate_size == bcfg["moe_intermediate_size"] > 0
+ assert node.num_experts_per_tok == bcfg["num_experts_per_tok"] == 9
+ else:
+ assert node.n_routed_experts == 0
+ assert node.moe_intermediate_size == 0
+ # Heterogeneous Puzzle MoE: 12 distinct (n_experts, intermediate) specs.
+ assert len(spec.distinct_moe_specs()) == 12
+ assert spec.block_at(1).n_routed_experts == 240
+ assert spec.block_at(1).moe_intermediate_size == 2048
+
+
+@_needs_real_config()
+def test_bolt_globals():
+ spec = ap.load_puzzle_spec(REAL_CONFIG)
+ assert spec.hidden_size == 4096
+ assert spec.vocab_size == 131072
+ assert spec.moe_latent_size == 1024
+ assert spec.moe_shared_expert_intermediate_size == 5376
+ assert spec.num_attention_heads == 32
+ assert spec.num_key_value_heads == 2
+ assert spec.head_dim == 128
+ assert spec.mamba_num_heads == 128
+ assert spec.mamba_head_dim == 64
+ assert spec.ssm_state_size == 128
+
+
+@_needs_real_config()
+def test_bolt_graph_tensor_keys():
+ spec = ap.load_puzzle_spec(REAL_CONFIG)
+ graph = ap.build_puzzle_graph(spec)
+ assert graph.num_layers == 88
+ assert graph.find("backbone.layers.7").block_type == "attention"
+
+ mamba_keys = set(ap.iter_block_tensor_keys(graph.find("backbone.layers.0")))
+ assert mamba_keys == {
+ "backbone.layers.0.norm.weight",
+ "backbone.layers.0.mixer.in_proj.weight",
+ "backbone.layers.0.mixer.out_proj.weight",
+ "backbone.layers.0.mixer.conv1d.weight",
+ "backbone.layers.0.mixer.conv1d.bias",
+ "backbone.layers.0.mixer.A_log",
+ "backbone.layers.0.mixer.D",
+ "backbone.layers.0.mixer.dt_bias",
+ "backbone.layers.0.mixer.norm.weight",
+ }
+ attn_keys = set(ap.iter_block_tensor_keys(graph.find("backbone.layers.7")))
+ assert attn_keys == {
+ "backbone.layers.7.norm.weight",
+ "backbone.layers.7.mixer.q_proj.weight",
+ "backbone.layers.7.mixer.k_proj.weight",
+ "backbone.layers.7.mixer.v_proj.weight",
+ "backbone.layers.7.mixer.o_proj.weight",
+ }
+ moe_keys = set(ap.iter_block_tensor_keys(graph.find("backbone.layers.1")))
+ assert len(moe_keys) == 1 + 6 + 2 * 240 # norm + shared/router + experts
+ assert "backbone.layers.1.mixer.gate.weight" in moe_keys
+ assert "backbone.layers.1.mixer.gate.e_score_correction_bias" in moe_keys
+ assert "backbone.layers.1.mixer.fc1_latent_proj.weight" in moe_keys
+ assert "backbone.layers.1.mixer.shared_experts.down_proj.weight" in moe_keys
+ assert "backbone.layers.1.mixer.experts.0.up_proj.weight" in moe_keys
+ assert "backbone.layers.1.mixer.experts.239.down_proj.weight" in moe_keys
+
+
+def test_key_mapping():
+ assert ap.strip_llm_prefix("language_model.backbone.layers.0.mixer.D") == \
+ "backbone.layers.0.mixer.D"
+ assert ap.strip_llm_prefix("language_model.lm_head.weight") == "lm_head.weight"
+ assert ap.map_checkpoint_key("language_model.lm_head.weight") == "lm_head.weight"
+ assert ap.map_checkpoint_key("vision_model.radio_model.blocks.0.attn.qkv") is None
+ assert ap.map_checkpoint_key("mlp1.1.weight") is None
+ assert ap.map_checkpoint_key("backbone.layers.0.mixer.D") == \
+ "backbone.layers.0.mixer.D" # bare puzzle checkpoint
+ with pytest.raises(ValueError):
+ ap.strip_llm_prefix("vision_model.x")
+
+
+def test_strip_prefix_from_maps():
+ file_map = {
+ "language_model.lm_head.weight": "shard1",
+ "language_model.backbone.layers.0.mixer.D": "shard2",
+ "vision_model.blocks.0.weight": "shard9",
+ "mlp1.1.weight": "shard9",
+ }
+ headers = {
+ "shard1": {"language_model.lm_head.weight": {"shape": [1]},
+ "_header_offset": 100},
+ "shard2": {"language_model.backbone.layers.0.mixer.D": {"shape": [2]},
+ "__metadata__": {}},
+ "shard9": {"vision_model.blocks.0.weight": {"shape": [3]},
+ "mlp1.1.weight": {"shape": [4]},
+ "_header_offset": 200},
+ }
+ new_map, new_headers = ap.strip_llm_prefix_from_maps(file_map, headers)
+ assert new_map == {
+ "lm_head.weight": "shard1",
+ "backbone.layers.0.mixer.D": "shard2",
+ }
+ assert new_headers["shard1"] == {
+ "lm_head.weight": {"shape": [1]}, "_header_offset": 100}
+ assert new_headers["shard2"] == {
+ "backbone.layers.0.mixer.D": {"shape": [2]}}
+ assert new_headers["shard9"] == {"_header_offset": 200}
+
+
+# --------------------------------------------------------------------------
+# Hermetic synthetic fixture (always runs)
+# --------------------------------------------------------------------------
+
+def _synthetic_llm(n_layers=6):
+ pattern = ["mamba", "moe", "mamba", "attention", "moe", "mamba"]
+ block_configs = []
+ for t in pattern[:n_layers]:
+ if t == "moe":
+ block_configs.append({"block_type": t, "moe_intermediate_size": 1536,
+ "n_routed_experts": 240, "num_experts_per_tok": 9})
+ else:
+ block_configs.append({"block_type": t})
+ return {
+ "model_type": "nemotron_h_puzzle",
+ "architectures": ["NemotronHPuzzleForCausalLM"],
+ "hidden_size": 4096, "vocab_size": 131072,
+ "num_attention_heads": 32, "num_key_value_heads": 2,
+ "layers_block_type": pattern[:n_layers],
+ "block_configs": block_configs,
+ "moe_latent_size": 1024, "moe_shared_expert_intermediate_size": 5376,
+ }
+
+
+def test_synthetic_bare_and_wrapped(tmp_path):
+ llm = _synthetic_llm()
+ bare = tmp_path / "bare.json"
+ bare.write_text(json.dumps(llm), encoding="utf8")
+ spec = ap.load_puzzle_spec(str(bare))
+ assert spec.from_omni_wrapper is False
+ assert spec.num_hidden_layers == 6
+ assert spec.block_counts == {"mamba": 3, "moe": 2, "attention": 1}
+ assert spec.attention_indices == (3,)
+ assert spec.block_at(1).n_routed_experts == 240
+
+ wrapped = {"architectures": ["NemotronH_Omni_Reasoning_V3"],
+ "model_type": "nemotron_h_omni", "llm_config": llm}
+ wrap = tmp_path / "wrap.json"
+ wrap.write_text(json.dumps(wrapped), encoding="utf8")
+ wspec = ap.load_puzzle_spec(str(wrap))
+ assert wspec.from_omni_wrapper is True
+ assert wspec.block_counts == spec.block_counts
+ graph = ap.build_puzzle_graph(wspec)
+ assert graph.num_layers == 6
+ assert "puzzle" in ap.summarize(wspec).lower() or "Puzzle" in ap.summarize(wspec)
+
+
+def test_rejects_bad_configs():
+ good = _synthetic_llm()
+ bad_len = dict(good, block_configs=good["block_configs"][:-1])
+ with pytest.raises(ValueError):
+ ap.parse_puzzle_spec(bad_len)
+ bad_type = json.loads(json.dumps(good))
+ bad_type["block_configs"][0] = {"block_type": "dense"}
+ with pytest.raises(ValueError):
+ ap.parse_puzzle_spec(bad_type)
+ bad_model = dict(good, model_type="llama")
+ with pytest.raises(ValueError):
+ ap.parse_puzzle_spec(bad_model)
+ with pytest.raises(ValueError):
+ ap.load_llm_config_dict({"architectures": ["Nope"], "model_type": "nope"})
diff --git a/tests/test_ngram_placement_cpu.py b/tests/test_ngram_placement_cpu.py
new file mode 100644
index 0000000..c60c088
--- /dev/null
+++ b/tests/test_ngram_placement_cpu.py
@@ -0,0 +1,36 @@
+import os, re, ast
+
+# The placement rule is a pure function; load it from source so the test needs neither a GPU nor the compiled extension
+_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+_src = open(os.path.join(_ROOT, "exllamav3/modules/ngram_embedding.py")).read()
+_tree = ast.parse(_src)
+_ns = {}
+for _n in _tree.body:
+ if (isinstance(_n, ast.FunctionDef) and _n.name == "decide_ngram_stream") or \
+ (isinstance(_n, ast.Assign) and getattr(_n.targets[0], "id", "") == "RAM_MARGIN_BYTES"):
+ exec(compile(ast.Module([_n], []), "ngram_embedding", "exec"), _ns)
+decide_ngram_stream = _ns["decide_ngram_stream"]
+
+GiB = 1 << 30
+
+
+def test_unset_is_disk_even_with_lots_of_ram():
+ assert decide_ngram_stream(None, 76 * GiB, 107 * GiB)[0] is True
+ assert decide_ngram_stream(None, 76 * GiB, None)[0] is True
+
+
+def test_explicit_disk():
+ assert decide_ngram_stream(True, 10 * GiB, 500 * GiB)[0] is True
+
+
+def test_explicit_ram_honored_with_warning_when_tight():
+ stream, why = decide_ngram_stream(False, 76 * GiB, 80 * GiB)
+ assert stream is False and "WARNING" in why
+ stream, why = decide_ngram_stream(False, 76 * GiB, 200 * GiB)
+ assert stream is False and "WARNING" not in why
+
+
+def test_config_unset_stays_none():
+ # unset must reach the placement rule as None (which decides disk), never as an RAM request
+ src = open(os.path.join(_ROOT, "exllamav3/model/config.py")).read()
+ assert re.search(r"ngram_stream_from_disk = None if _ns is None", src)
diff --git a/tests/test_pf_split_plan.py b/tests/test_pf_split_plan.py
new file mode 100644
index 0000000..dc95ac2
--- /dev/null
+++ b/tests/test_pf_split_plan.py
@@ -0,0 +1,119 @@
+"""Job.split_plan / Job.exact_gate / Job._stash_exact: EXL3_PF_SPLIT exactness tags (CPU only)."""
+import os, sys, types
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
+from exllamav3.generator.job import Job
+from exllamav3.generator.pagetable import PAGE_SIZE
+
+ENVS = ("EXL3_PF_SPLIT", "EXL3_PF_SPLIT_MIN", "EXL3_PF_SPLIT_HEAD", "EXL3_PF_SPLIT_STEP", "EXL3_PF_SPLIT_Q",
+ "EXL3_PREFILL_BIG_CHUNK", "EXL3_PREFILL_BIG_CHUNK_MAXPOS", "EXL3_PF_TAIL_MERGE")
+
+
+def clean_env():
+ for k in ENVS:
+ os.environ.pop(k, None)
+ os.environ["EXL3_PF_TAIL_MERGE"] = "1024"
+
+
+def plan(total, split = "256", **env):
+ clean_env()
+ os.environ["EXL3_PF_SPLIT"] = split
+ for k, v in env.items():
+ os.environ[k] = str(v)
+ me = types.SimpleNamespace(generator = types.SimpleNamespace(max_chunk_size = 4096))
+ return Job.split_plan(me, total)
+
+
+def test_off_and_short():
+ assert plan(11010, split = "") is None
+ assert plan(3000) is None # below EXL3_PF_SPLIT_MIN
+ assert plan(4000) is None
+
+
+def test_one_cut():
+ # 11010 rows: 4096-row chunks while more than 4096 + 1024 remain -> merged last chunk starts at 8192
+ assert plan(11010) == (8192, 10752)
+ assert plan(28674) == (24576, 28416)
+ # the cut depends on the prompt length only: 256 rows before the end, rounded down to a page
+ assert plan(11008 + 255) == (8192, 10752)
+ assert plan(11008 + 256) == (8192, 11008)
+
+
+def test_two_cuts_and_spacing():
+ assert plan(11010, split = "1536,256") == (8192, 9472, 10752)
+ # cuts closer than EXL3_PF_SPLIT_STEP collapse into the first
+ assert plan(11010, split = "512,256", EXL3_PF_SPLIT_STEP = 1024) == (8192, 10496)
+
+
+def test_head_room():
+ # a cut with fewer than EXL3_PF_SPLIT_HEAD rows in the first pass is dropped
+ assert plan(8192 + 1100, split = "256") is None or plan(8192 + 1100)[1] >= 8192 + 1024
+
+
+def test_kda_big_tail_plan():
+ # KDA big-tail planner: 8192-row chunks, the last chunk is what remains (<= 8192)
+ assert plan_mode(20000, "kda") == (16384, 19712)
+ assert plan_mode(8192 + 100, "kda") is None # 100 rows after the first 8192 chunk: no room for a first pass
+ assert plan_mode(8000, "kda") == (0, 7680)
+ assert plan_mode(3000, "kda") is None # below EXL3_PF_SPLIT_MIN
+ assert plan_mode(20000, "kda", EXL3_PREFILL_BIG_CHUNK = 2048) is None # big == chunk is the plain planner, not big-tail
+ assert plan_mode(20000, "gdn", EXL3_PREFILL_BIG_CHUNK = 8192) is None # GDN planner needs the plain chunking
+
+
+def plan_mode(total, mode, split = "256", **env):
+ clean_env()
+ os.environ["EXL3_PF_SPLIT"] = split
+ os.environ.setdefault("EXL3_PREFILL_BIG_CHUNK", "8192")
+ for k, v in env.items():
+ os.environ[k] = str(v)
+ me = types.SimpleNamespace(generator = types.SimpleNamespace(max_chunk_size = 2048 if mode == "kda" else 4096))
+ return Job.split_plan(me, total, mode)
+
+
+def test_coarse_grid():
+ assert plan(11010, EXL3_PF_SPLIT_Q = 1024) == (8192, 10240)
+
+
+def test_adaptive_chunking_disabled():
+ assert plan(11010, EXL3_PREFILL_BIG_CHUNK = 8192) is None
+
+
+class Pg:
+ def __init__(self, wgen): self.wgen = wgen
+
+
+def gate_for(total, rc, pages, plan_, hashes):
+ pt = types.SimpleNamespace(referenced_pages = {h: p for h, p in zip(hashes, pages)}, unreferenced_pages = {})
+ seq = types.SimpleNamespace(sequence_ids = list(range(total + 1)), page_hashes = hashes)
+ me = types.SimpleNamespace(generator = types.SimpleNamespace(recurrent_cache = rc), pagetable = pt, sequences = [seq],
+ split_mode = lambda alloc = False: "gdn", split_plan = lambda t, mode = None: plan_)
+ return Job.exact_gate(me, seq)
+
+
+def test_gate_tags():
+ rc = types.SimpleNamespace(exact_meta = {}, metrics = {})
+ hashes = [f"h{i}" for i in range(60)]
+ pages = [Pg(i + 1) for i in range(60)]
+ state, other = object(), object()
+ p = (8192, 10752)
+ pw = tuple(pg.wgen for pg in pages[8192 // PAGE_SIZE: 10752 // PAGE_SIZE])
+ rc.exact_meta[hashes[10752 // PAGE_SIZE - 1]] = {"eid": id(state), "sig": p, "pw": pw}
+ ph, pi = hashes[10752 // PAGE_SIZE - 1], 10752 // PAGE_SIZE - 1
+ g = gate_for(11010, rc, pages, p, hashes)
+ assert g(state, ph, pi) is True # tagged, same plan, pages untouched
+ assert g.tagged == [pi] # allocate_pages prefers it over deeper states
+ assert gate_for(11010, rc, pages, (8192, 10240), hashes)(state, ph, pi) is False # other cut in this prompt's plan
+ assert gate_for(11010, rc, pages, None, hashes)(state, ph, pi) is False # this prompt has no plan
+ assert gate_for(11010, rc, pages, p, hashes)(other, ph, pi) is False # the state under the hash is not the tagged one
+ pages[40].wgen = 999 # a page under the cut was rewritten
+ assert gate_for(11010, rc, pages, p, hashes)(state, ph, pi) is False
+ # an untagged state exactly at a cut of this plan is refused, any other passes
+ assert gate_for(11010, rc, pages, p, hashes)(other, hashes[41], 41) is False
+ assert gate_for(11010, rc, pages, p, hashes)(other, hashes[20], 20) is True
+ assert rc.metrics["exact_rejected"] >= 4
+
+
+if __name__ == "__main__":
+ for name, fn in list(globals().items()):
+ if name.startswith("test_"):
+ fn()
+ print("ok", name)
diff --git a/tests/test_row_groups_cpu.py b/tests/test_row_groups_cpu.py
new file mode 100644
index 0000000..c50963a
--- /dev/null
+++ b/tests/test_row_groups_cpu.py
@@ -0,0 +1,192 @@
+"""CPU checks for the job groups of a row-invariant multi-job decode step (generator/row_groups.py).
+
+The arithmetic is proven on the GPU (tools/qwen/batch_inv.py); this file pins the pure logic: how jobs are packed
+into forwards, and that the grouped forward feeds every group its own slice of the batch and puts the pieces back in
+batch order.
+"""
+import types
+
+import pytest
+import torch
+
+from exllamav3.generator import row_groups as RG
+from exllamav3.generator.generator import Generator
+from exllamav3.util.row_inv import ROW_INV_MAX_ROWS
+
+
+def test_cap_default_and_override(monkeypatch):
+ monkeypatch.delenv("EXL3_ROW_INV_GROUP_ROWS", raising=False)
+ assert RG.group_rows_cap() == ROW_INV_MAX_ROWS == 8
+ monkeypatch.setenv("EXL3_ROW_INV_GROUP_ROWS", "1")
+ assert RG.group_rows_cap() == 1
+ monkeypatch.setenv("EXL3_ROW_INV_GROUP_ROWS", "0")
+ assert RG.group_rows_cap() == 1
+ monkeypatch.setenv("EXL3_ROW_INV_GROUP_ROWS", "")
+ assert RG.group_rows_cap() == 8
+
+
[email protected]("value,expect", [(None, False), ("", False), ("0", False), ("1", True)])
+def test_grouped_step_is_opt_in(value, expect):
+ import os
+ import subprocess
+ import sys
+ env = {k: v for k, v in os.environ.items() if k != "EXL3_ROW_INV_GROUPS"}
+ if value is not None:
+ env["EXL3_ROW_INV_GROUPS"] = value
+ out = subprocess.run([sys.executable, "-c", "from exllamav3.generator.row_groups import GROUPS; print(GROUPS['on'])"],
+ env=env, capture_output=True, text=True, check=True).stdout.strip()
+ assert out == str(expect)
+
+
+def test_plain_decode_packs_eight_jobs_per_forward():
+ assert RG.plan_groups([1] * 4, 1, 8) == [(0, 4)]
+ assert RG.plan_groups([1] * 8, 1, 8) == [(0, 8)]
+ assert RG.plan_groups([1] * 9, 1, 8) == [(0, 8), (8, 9)]
+ assert RG.plan_groups([1] * 20, 1, 8) == [(0, 8), (8, 16), (16, 20)]
+
+
+def test_verify_rows_split_by_width():
+ # four jobs of 2, 3, 4 and 8 token rows
+ assert RG.plan_groups([1] * 4, 2, 8) == [(0, 4)]
+ assert RG.plan_groups([1] * 4, 3, 8) == [(0, 2), (2, 4)]
+ assert RG.plan_groups([1] * 4, 4, 8) == [(0, 2), (2, 4)]
+ assert RG.plan_groups([1] * 4, 8, 8) == [(0, 1), (1, 2), (2, 3), (3, 4)]
+ assert RG.plan_groups([1] * 3, 5, 8) == [(0, 1), (1, 2), (2, 3)]
+
+
+def test_groups_cover_every_job_once_in_order():
+ for n in range(0, 12):
+ for width in range(1, 9):
+ for cap in (1, 2, 5, 8, 16):
+ spans = RG.plan_groups([1] * n, width, cap)
+ flat = [j for a, b in spans for j in range(a, b)]
+ assert flat == list(range(n)), (n, width, cap, spans)
+ for a, b in spans:
+ assert b > a
+ assert (b - a) * width <= max(cap, width), (n, width, cap, spans)
+
+
+def test_multi_sequence_jobs_stay_whole():
+ # a job with 3 sequences and width 2 carries 6 rows; the next job (2 rows) does not fit in the same group of 8
+ assert RG.plan_groups([3, 1, 1], 2, 8) == [(0, 2), (2, 3)]
+ # a job larger than the cap is its own group
+ assert RG.plan_groups([5, 1], 2, 8) == [(0, 1), (1, 2)]
+
+
+class _Job:
+ def __init__(self, nseq=1):
+ self.sequences = [object() for _ in range(nseq)]
+
+
+def _fake_model(log):
+ """Logits row = f(token id, cache_seqlen, group size): any slicing mistake or reordering shows."""
+ def forward(input_ids, params):
+ bsz, width = input_ids.shape
+ assert params["block_table"].shape[0] == bsz
+ assert params["cache_seqlens"].shape[0] == bsz
+ assert len(params["recurrent_states"]) == bsz
+ if "dflash_table_pages" in params:
+ assert len(params["dflash_table_pages"]) == bsz
+ log.append((bsz, width, bool(params.get("dflash_verify"))))
+ out = (input_ids.float() * 1000 + params["cache_seqlens"].float().view(-1, 1)).unsqueeze(-1).repeat(1, 1, 4)
+ params["export_states"] = [out[..., :2].clone(), out[..., 2:].clone() + 0.5]
+ return out
+ return types.SimpleNamespace(forward=forward)
+
+
+def _run(n, width, draft, cap=8):
+ jobs = [_Job() for _ in range(n)]
+ ids = torch.arange(n * width, dtype=torch.long).view(n, width) + 10
+ params = {
+ "block_table": torch.arange(n * 6, dtype=torch.int32).view(n, 6),
+ "cache_seqlens": torch.arange(n, dtype=torch.int32) * 100 + 7,
+ "recurrent_states": [object() for _ in range(n)],
+ "positions": None,
+ "dflash_verify": draft,
+ }
+ own = [16 + i for i in range(n)] if draft else None
+ log = []
+ gen = types.SimpleNamespace(model=_fake_model(log))
+ spans = RG.plan_groups([1] * n, width, cap)
+ out = Generator._forward_groups(gen, ids, params, jobs, spans, own)
+ whole_params = dict(params)
+ ref = _fake_model([]).forward(ids, whole_params)
+ return out, ref, params, whole_params, log
+
+
[email protected]("n,width,draft", [(4, 1, False), (4, 3, True), (3, 8, True), (9, 1, False), (5, 2, True)])
+def test_grouped_forward_equals_the_whole_batch(n, width, draft):
+ out, ref, params, whole_params, log = _run(n, width, draft)
+ assert torch.equal(out, ref)
+ for a, b in zip(params["export_states"], whole_params["export_states"]):
+ assert torch.equal(a, b)
+ assert sum(b for b, _, _ in log) == n
+ assert all(b * w <= 8 or b == 1 for b, w, _ in log)
+
+
+def test_plain_group_of_several_rows_takes_the_verify_kernels():
+ _, _, _, _, log = _run(4, 1, False)
+ assert log == [(4, 1, True)]
+ _, _, _, _, log = _run(9, 1, False)
+ assert log == [(8, 1, True), (1, 1, False)] # a lone one-row job keeps the one-row path
+
+
+def test_several_forwards_do_not_share_the_pinned_embedding_staging():
+ seen = []
+ gen = types.SimpleNamespace(model=types.SimpleNamespace(forward=lambda input_ids, params: (
+ seen.append(params.get("pinned_staging")) or torch.zeros(input_ids.shape[0], input_ids.shape[1], 2))))
+ for n, expect in ((4, [True]), (9, [False, False])):
+ del seen[:]
+ jobs = [_Job() for _ in range(n)]
+ params = {"block_table": torch.zeros(n, 3, dtype=torch.int32), "cache_seqlens": torch.zeros(n, dtype=torch.int32),
+ "recurrent_states": [object() for _ in range(n)], "pinned_staging": True}
+ Generator._forward_groups(gen, torch.zeros(n, 1, dtype=torch.long), params, jobs, RG.plan_groups([1] * n, 1, 8), None)
+ assert seen == expect, (n, seen)
+
+
+def test_cap_one_runs_every_job_alone():
+ _, _, _, _, log = _run(3, 3, True, cap=1)
+ assert [b for b, _, _ in log] == [1, 1, 1]
+ assert all(v for _, w, v in log) # width 3: still the verify rows of the solo path
+
+
+def test_group_of_several_sequences_runs_attention_per_sequence():
+ seen = []
+ gen = types.SimpleNamespace(model=types.SimpleNamespace(forward=lambda input_ids, params: (
+ seen.append((input_ids.shape[0], bool(params.get("row_inv_per_seq")))) or torch.zeros(input_ids.shape[0], input_ids.shape[1], 2))))
+ jobs = [_Job() for _ in range(9)]
+ params = {"block_table": torch.zeros(9, 3, dtype=torch.int32), "cache_seqlens": torch.zeros(9, dtype=torch.int32),
+ "recurrent_states": [object() for _ in range(9)]}
+ Generator._forward_groups(gen, torch.zeros(9, 1, dtype=torch.long), params, jobs, RG.plan_groups([1] * 9, 1, 8), None)
+ # the eight-sequence group splits its attention per sequence, the lone job keeps the plain path
+ assert seen == [(8, True), (1, False)]
+
+
+def test_split_params_by_sequence_slices_every_per_sequence_input():
+ from exllamav3.modules.attn import split_params_by_sequence
+ seqlens = torch.tensor([5, 9, 300], dtype=torch.int32)
+ params = {
+ "block_table": torch.arange(12, dtype=torch.int32).view(3, 4),
+ "cache_seqlens": seqlens,
+ "positions": seqlens, # what prepare_flash_attn does for a plain decode: an alias
+ "dev_cache": {"cache_seqlens": object()},
+ "causal": True,
+ }
+ parts = split_params_by_sequence(params, 3)
+ assert len(parts) == 3
+ for b, p in enumerate(parts):
+ assert torch.equal(p["block_table"], params["block_table"][b:b + 1])
+ assert torch.equal(p["cache_seqlens"], seqlens[b:b + 1])
+ assert p["positions"] is p["cache_seqlens"]
+ assert "dev_cache" not in p and p["causal"] is True
+ # separate positions (a caller that set them) are sliced on their own
+ params["positions"] = seqlens + 1
+ parts = split_params_by_sequence(params, 3)
+ assert [int(p["positions"]) for p in parts] == [6, 10, 301]
+ # none: stays none
+ params["positions"] = None
+ assert all(p["positions"] is None for p in split_params_by_sequence(params, 3))
+ # per-sequence position ids are not sliced here: refuse instead of running wrong
+ params["position_ids"] = torch.zeros(3, 1, dtype=torch.long)
+ with pytest.raises(AssertionError):
+ split_params_by_sequence(params, 3)
diff --git a/tests/test_tail_ckpt_rows.py b/tests/test_tail_ckpt_rows.py
new file mode 100644
index 0000000..dbbf56d
--- /dev/null
+++ b/tests/test_tail_ckpt_rows.py
@@ -0,0 +1,128 @@
+"""Job.tail_ckpt_rows: which chunk rows get a dense prompt-tail checkpoint (CPU only)."""
+import os, sys, types
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
+from exllamav3.generator.job import Job
+from exllamav3.generator.pagetable import PAGE_SIZE
+
+
+def rows(prompt_len, start, end, taken=(), dense="7"):
+ os.environ["EXL3_TAIL_DENSE"] = dense
+ seq = types.SimpleNamespace(sequence_ids = list(range(prompt_len + 1))) # the last token is not prefilled
+ return Job.tail_ckpt_rows(None, seq, start, end, list(taken))
+
+
+def test_pages_below_last_page():
+ # 97537-token prompt, last chunk [94208, 97537): last page 97536, dense rows are the 7 pages below it
+ got = rows(97537, 94208, 97537)
+ assert got == [97536 - k * PAGE_SIZE - 94208 for k in range(1, 8)]
+ assert all(r % PAGE_SIZE == 0 and 0 < r < 97537 - 94208 for r in got)
+
+
+def test_off_and_short_prompt():
+ assert rows(97537, 94208, 97537, dense = "0") == []
+ assert all(0 < r < 1000 for r in rows(1000, 0, 1000))
+
+
+def test_taken_rows_and_slot_cap():
+ last = 97536 - 94208
+ got = rows(97537, 94208, 97537, taken = [last, last - 2 * PAGE_SIZE, None])
+ assert last not in got and last - 2 * PAGE_SIZE not in got
+ assert len(got) + 2 <= 8
+ assert len(rows(97537, 94208, 97537, taken = [1, 2, 3, 4, 5, 6])) == 2
+
+
+def sub(prompt_len, start, end, taken = (), n = "4"):
+ os.environ["EXL3_TAIL_SUB"] = n
+ me = types.SimpleNamespace(_tail_ok = lambda seq: True, generator = types.SimpleNamespace(tail_ckpt_min = 512))
+ seq = types.SimpleNamespace(sequence_ids = list(range(prompt_len + 1)))
+ return Job.sub_ckpt_rows(me, seq, start, end, list(taken))
+
+
+def test_sub_rows_are_the_last_multiples_of_64():
+ # last chunk [94208, 97537): 3329 rows -> rows 3328, 3264, 3200, 3136
+ assert sub(97537, 94208, 97537) == [3328, 3264, 3200, 3136]
+ assert sub(97537, 94208, 97537, n = "0") == []
+ assert sub(97537, 94209, 97537) == [] # unaligned chunk start
+ assert sub(97537, 94208, 97000) == [] # not the chunk that holds the prompt end
+ assert sub(97537, 94208, 97537, taken = [3328]) == [3264, 3200, 3136, 3072]
+ assert len(sub(97537, 94208, 97537, taken = [1, 2, 3, 4, 5, 6])) == 2
+
+
+class _Page:
+ def __init__(self, phash):
+ self.phash, self.kv_position = phash, PAGE_SIZE
+
+
+def torch_equal(a, b):
+ import torch
+ return torch.equal(a, b)
+
+
+def _stash_env(sub_max, n_pages = 3):
+ import torch
+ ids = torch.arange(n_pages * PAGE_SIZE + 64)
+ seq = types.SimpleNamespace(allocated_pages = [_Page(100 + i) for i in range(n_pages)],
+ sequence_ids = types.SimpleNamespace(torch_slice = lambda a, b: ids[a:b]))
+ gen = types.SimpleNamespace(sub_ckpts = [], sub_ckpt_max = sub_max)
+ return types.SimpleNamespace(generator = gen, mtp_defer = False), seq, ids
+
+
+def _stash(me, seq, pos, salt = 0):
+ import torch
+ old = seq.sequence_ids
+ seq.sequence_ids = types.SimpleNamespace(torch_slice = lambda a, b: old.torch_slice(a, b) + salt)
+ try:
+ return Job._stash_sub(me, seq, pos, {"position": pos})
+ finally:
+ seq.sequence_ids = old
+
+
+def test_sub_stash_replaces_same_content_by_identity():
+ # the entry to replace is not the first of the list: list.remove() would compare the dicts before it, tensors inside, and raise
+ me, seq, _ = _stash_env(8)
+ pos = PAGE_SIZE + 64
+ assert _stash(me, seq, pos, salt = 0) == 1
+ assert _stash(me, seq, pos, salt = 1) == 1
+ first, second = me.generator.sub_ckpts
+ assert _stash(me, seq, pos, salt = 1) == 1
+ got = me.generator.sub_ckpts
+ assert len(got) == 2 and got[0] is first and got[1] is not second and torch_equal(got[1]["ids"], second["ids"])
+
+
+def test_sub_stash_cap_and_zero():
+ me, seq, _ = _stash_env(2)
+ for salt in range(5):
+ _stash(me, seq, PAGE_SIZE + 64, salt = salt)
+ assert len(me.generator.sub_ckpts) == 2
+ me0, seq0, _ = _stash_env(0)
+ assert _stash(me0, seq0, PAGE_SIZE + 64) == 0 and me0.generator.sub_ckpts == [] # EXL3_TAIL_SUB_MAX=0: IndexError before
+ me0.generator.sub_ckpt_max = 0
+ me0._tail_ok = lambda s: True
+ me0.generator.tail_ckpt_min = 512
+ os.environ["EXL3_TAIL_SUB"] = "4"
+ assert Job.sub_ckpt_rows(me0, types.SimpleNamespace(sequence_ids = list(range(97538))), 94208, 97537, []) == []
+
+
+def test_mode1_split_declines_page_spaced_rows():
+ # EXL3_MIDCHUNK_CKPT=1 splits the layer at the rows and declines when a segment is 256 rows or less: rows one page apart
+ # always do, which is why the job adds dense rows in mode 2 only
+ from exllamav3.modules.gated_delta_net import GatedDeltaNet
+ me = types.SimpleNamespace(kda = True)
+ seg = lambda r: GatedDeltaNet._midchunk_segments(me, {"checkpoint_rows": r, "midchunk_mode": 1}, 1, 8192, True, False)
+ assert seg([1024, 2048]) == [0, 1024, 2048, 8192]
+ assert seg([1024, 1024 + PAGE_SIZE]) is None
+
+
+def test_kda_fused_h_siblings_differ_only_in_slot_count():
+ from exllamav3.vendor.fla.hip.kda_fused_h_hip import _siblings
+ pf = "BRL=1 UNI=1 OPQ=15 -mllvm -disable-lsr"
+ assert _siblings(pf + " CK4=1") == [pf, pf + " CK8=1"]
+ assert _siblings(pf) == [pf + " CK4=1", pf + " CK8=1"]
+ assert _siblings("") == ["CK4=1", "CK8=1"]
+ assert _siblings("CK8=1") == ["", "CK4=1"]
+
+
+if __name__ == "__main__":
+ for n, f in list(globals().items()):
+ if n.startswith("test_"):
+ f(); print("ok", n)
diff --git a/tools/bench_flint.py b/tools/bench_flint.py
new file mode 100644
index 0000000..94343db
--- /dev/null
+++ b/tools/bench_flint.py
@@ -0,0 +1,72 @@
+"""Flint speed bench, one (depth) row per process. usage:
+ bench_flint.py PACK --depth 32768 [--gen 64] [--kv 16|8,8|6,6|4,4] [--seed 0] [-o row.json]
+Prompt = real text tokens (c4/wiki/code mix). pp = depth / ttft; tg = steady decode tok/s over --gen tokens (greedy)."""
+import argparse, json, os, sys, time
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+import torch
+from exllamav3 import Config, Model, Cache, Tokenizer, Generator, Job
+from exllamav3.cache import CacheLayer_quant
+from exllamav3.generator.sampler.presets import GreedySampler
+
+ap = argparse.ArgumentParser()
+ap.add_argument("pack"); ap.add_argument("--depth", type=int, required=True); ap.add_argument("--gen", type=int, default=64)
+ap.add_argument("--kv", default="16"); ap.add_argument("--seed", type=int, default=0); ap.add_argument("-o", "--out")
+ap.add_argument("--chunk", type=int, default=0)
+a = ap.parse_args()
+
+cfg = Config.from_directory(a.pack)
+model = Model.from_config(cfg)
+tok = Tokenizer.from_config(cfg)
+ctx = ((a.depth + a.gen + 512 + 255) // 256) * 256
+if a.kv == "16":
+ cache = Cache(model, max_num_tokens=ctx)
+else:
+ kb, vb = (int(x) for x in a.kv.split(","))
+ cache = Cache(model, max_num_tokens=ctx, layer_type=CacheLayer_quant, k_bits=kb, v_bits=vb)
+t0 = time.time()
+model.load(progressbar=False)
+print(f"loaded in {time.time() - t0:.1f}s, {torch.cuda.memory_allocated() / 2**30:.2f} GiB", flush=True)
+kw = {"max_chunk_size": a.chunk} if a.chunk else {}
+gen = Generator(model=model, cache=cache, tokenizer=tok, **kw)
+
+D = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "exllamav3/conversion/standard_cal_data")
+def real_ids(n, seed):
+ out = []
+ for f in ("c4.utf8", "wiki.utf8", "code.utf8", "technical.utf8"):
+ s = open(f"{D}/{f}", encoding="utf8").read()
+ a0 = (seed * 7919) % max(1, len(s) // 3)
+ out.append(tok.encode(s[a0:a0 + max(int(n * 6), 200000)], add_bos=False)[0])
+ ids = torch.cat(out)
+ # interleave blocks of 4096 tokens from each source so every source is present at every depth
+ blocks = [o[:len(o) // 4096 * 4096].view(-1, 4096) for o in out]
+ mix = torch.cat([blocks[i % 4][(i // 4) % blocks[i % 4].shape[0]] for i in range(n // 4096 + 2)])
+ return mix[:n].view(1, -1)
+
+def run(ids, ngen):
+ job = Job(input_ids=ids, max_new_tokens=ngen, sampler=GreedySampler())
+ gen.enqueue(job)
+ t0 = time.time(); ttft = None; times = []; ntok = 0
+ while gen.num_remaining_jobs():
+ for r in gen.iterate():
+ if r.get("error"): print("JOB ERROR", r["error"], flush=True)
+ if r.get("text", ""):
+ now = time.time()
+ if ttft is None: ttft = now - t0
+ else: times.append(now)
+ ntok += 1
+ return ttft, ntok, times, time.time() - t0
+
+run(real_ids(256, 99), 8) # warm-up (graph capture, kernels)
+torch.cuda.reset_peak_memory_stats()
+ids = real_ids(a.depth, 1000 + a.seed)
+ttft, ntok, times, total = run(ids, a.gen)
+if ttft is None: # no token came back: the job errored (printed above), e.g. prompt longer than max_seq_len or cache OOM
+ print(json.dumps({"depth": a.depth, "kv": a.kv, "error": "no tokens generated", "ctx": ctx}), flush=True)
+ sys.exit(1)
+tg = (len(times) - 1) / (times[-1] - times[0]) if len(times) > 2 else 0.0
+res = {"depth": a.depth, "kv": a.kv, "ttft": ttft, "pp": a.depth / ttft, "tg": tg, "ntok": ntok,
+ "peak_gib": torch.cuda.max_memory_allocated() / 2**30, "reserved_gib": torch.cuda.max_memory_reserved() / 2**30}
+print(json.dumps(res), flush=True)
+if a.out: json.dump(res, open(a.out, "w"))
+r = model.__dict__.get("_cuda_graph_runner")
+if r is not None: print("GRAPH", dict(r.stats.get("declines", {})), {k: v for k, v in r.stats.items() if k != "declines"}, "model_ok", r._model_ok, flush=True)
diff --git a/tools/cuda/README.md b/tools/cuda/README.md
new file mode 100644
index 0000000..4587007
--- /dev/null
+++ b/tools/cuda/README.md
@@ -0,0 +1,32 @@
+# Kyojin on NVIDIA (CUDA) — build and smoke test
+
+One source tree for ROCm and CUDA. AMD-specific constructs in the Kyojin kernels go through
+`exllamav3/exllamav3_ext/port.cuh`; every macro expands on ROCm to the exact text the ROCm build always used
+(checked by compiling the touched files for gfx1151 before/after and diffing the assembly).
+
+## Toolchain without a system CUDA (tested on an RTX 3090, sm_86)
+NVIDIA PyPI wheels, `pip download --no-deps`, unpacked into one CUDA_HOME directory:
+| wheel | sha256 |
+|---|---|
+| nvidia_cuda_nvcc-13.0.88 | 56fe502eb77625a12f25172caa3cdddb4e4c8ba2c8c17dba44b164761b380f03 |
+| nvidia_nvvm-13.0.88 | c5f41ffeb6466944a026dfa5317d7d85355c119bbec279205d22f1869d1054e0 |
+| nvidia_cuda_crt-13.0.88 | 2c8043c7c9e02492716426e9919fc78d2c5b3b2a7a768a88e952676b08aa55a4 |
+| nvidia_cuda_cccl-13.0.85 | e0da7ad981f3a8aff08241b5bfc1af868742a63e2762f53a5171c492ef242649 |
+
+CUDA_HOME layout: `bin/` (nvcc, ptxas, ...), `include/` (crt + cccl headers merged), `nvvm/`, and `lib64/` holding
+unversioned links (`libcudart.so`, `libcublas.so`, `libcublasLt.so`, `libcurand.so`) to the `nvidia/cu13/lib/*.so.N`
+files of the torch cu130 wheel's venv (the linker wants the unversioned names; the wheels only ship `.so.N`).
+torch: 2.10 cu130 (CUDA major must match nvcc). Host compiler: gcc 13.
+
+## Build
+ tools/cuda/build.sh /path/to/cuda13 /path/to/venv-cuda/bin/python
+~3 min with 10 jobs; output `exllamav3_ext*.so` in the tree root. Never point TMPDIR at /tmp on shared machines.
+`EXL3_PORT_DEC=1` also compiles the Kyojin HIP decode GEMV family (`quant/exl3_dec.cu`) for CUDA; it is bound only
+when `EXL3_PORT_DEC=1` is set at import too (Python enables these kernels by `hasattr`, and until a port beats the
+upstream CUDA kernel it must not replace it silently). That file alone takes cicc a long time (fully unrolled decode).
+
+## Test
+ python -I tools/cuda/smoke.py <tree> <model dir> out.json 256 # 3 prompts, greedy, ttft / prefill / decode tok/s
+env: `SMOKE_KV=K,V` (quantized cache bits, default fp16), `SMOKE_MTP=n` (Kyojin MTP drafter), `SMOKE_POLICY=fixed|mix`, `SMOKE_DFLASH=<DFlash2 drafter dir>`.
+For lossless numbers set `EXL3_INT8_GEMV=0` (upstream's CUDA default quantizes 1-2 row GEMV activations to int8).
+Kernel parity / speed of a ported kernel: `tests/port/` (e.g. `bench_dec.py`).
diff --git a/tools/cuda/build.sh b/tools/cuda/build.sh
new file mode 100755
index 0000000..f1d43a8
--- /dev/null
+++ b/tools/cuda/build.sh
@@ -0,0 +1,15 @@
+#!/bin/bash
+# Build the Kyojin extension for NVIDIA (sm_86 by default) with nvcc from NVIDIA's PyPI wheels; no system CUDA needed.
+# usage: tools/cuda/build.sh TOOLCHAIN_DIR [TORCH_PYTHON] (run from anywhere; builds in place in this tree)
+# TOOLCHAIN_DIR: a CUDA_HOME made by tools/cuda/README.md (bin/nvcc, include, nvvm, lib64 with unversioned .so links)
+# TORCH_PYTHON: python of a venv with a CUDA torch whose CUDA major matches nvcc (torch 2.10 cu130 <-> nvcc 13.0)
+# env: ARCH (default 8.6), MAX_JOBS (default 10), EXL3_PORT_DEC=1 to also compile the HIP decode kernels (long: see README),
+# SCRATCH (TMPDIR for nvcc, default <tree>/build/tmp)
+set -eu
+E=$(cd "$(dirname "$0")/../.." && pwd); T=$(readlink -f "$1"); PY=${2:-python3}
+export CUDA_HOME=$T TORCH_CUDA_ARCH_LIST=${ARCH:-8.6} MAX_JOBS=${MAX_JOBS:-10} TMPDIR=${SCRATCH:-$E/build/tmp}
+export PATH=$CUDA_HOME/bin:$(dirname "$PY"):$PATH
+mkdir -p "$TMPDIR"; cd "$E"
+nvcc --version | tail -2
+nice -n 10 "$PY" -I setup.py build_ext --inplace -j "$MAX_JOBS"
+CUDA_VISIBLE_DEVICES= "$PY" -I -c "import sys; sys.path.insert(0, '$E'); import torch, exllamav3_ext as e; print('ok', len([n for n in dir(e) if not n.startswith('_')]), 'names')"
diff --git a/tools/cuda/prompt_long.txt b/tools/cuda/prompt_long.txt
new file mode 100644
index 0000000..43dbad7
--- /dev/null
+++ b/tools/cuda/prompt_long.txt
@@ -0,0 +1,178 @@
+> ## 🟥 AMD port — adds RDNA 3.5 (gfx1151 / Strix Halo) support
+>
+> **This branch adds AMD GPU functionality that is not in upstream ExLlamaV3.** Upstream targets
+> CUDA; the [`sdougbrown/exllamav3`](https://github.com/sdougbrown/exllamav3) base this is built on
+> adds a ROCm/HIP decode path for **gfx12 (RDNA 4)** only. This branch extends that path to
+> **gfx11.5 (RDNA 3.5)** — the Ryzen AI Max+ 395 / Radeon 8060S iGPU in the Framework Desktop.
+>
+> **What's added for AMD:** RDNA3.5 WMMA GEMV kernel (oracle-verified fragment layout), grouped-MoE
+> and fused-router paths enabled for gfx11.5, an int8-activation GEMV HIP port (`cp.async` → register
+> staging), `v_sad_u8` trellis decode, a CPU expert-offload port, and an LDS bank-conflict fix in the
+> WMMA staging buffer.
+>
+> **Measured** on Qwen3.8-Flash-Next-EXL3 (3.05 bpw) on one gfx1151: decode **4.27 → 34.9 tok/s mean**
+> (41.1 peak), perplexity unchanged at 4.2259.
+>
+> 👉 **See [`README.strix-halo.md`](README.strix-halo.md)** for the AMD build instructions, env knobs,
+> benchmark harnesses and measured results. The Installation section below is upstream's and is
+> **CUDA-specific** — do not follow it for AMD.
+>
+> NVIDIA/CUDA code paths are untouched; everything here is behind `USE_ROCM` / arch guards.
+
+<p align="center">
+ <img src="doc/logo.png" width="640" alt="Llama 3.1 8B Instruct quantization benchmark across bits per weight">
+</p>
+
+[Installation](#installation) · [Supported models](#architecture-support) · [Examples](#examples) · [Quantization](#exl3-quantization) · [Community](#community)
+
+ExLlamaV3 is an inference library for running local LLMs on modern consumer GPUs, with flexible quantization and parallel inference.
+
+- **Quantization** - [EXL3](doc/exl3.md), based on QTIP, plus 2–8 bit cache quantization.
+- **Parallel inference** - Flexible tensor-parallel and expert-parallel inference for consumer hardware setups.
+- **CPU offloading** - Allows large MoE models to run with limited GPU resources. AVX2 and AVX512 support.
+- **Generation** - Continuous, dynamic batching, speculative decoding, multimodal support.
+- **Integrations** - Broad [HF model support](#architecture-support), a [Transformers plugin](examples/transformers_integration.py), and an OpenAI-compatible API via [TabbyAPI](https://github.com/theroyallab/tabbyAPI/).
+
+> [!TIP]
+> **Looking for a server?** [TabbyAPI](https://github.com/theroyallab/tabbyAPI/) is the official and recommended backend server. It provides an OpenAI-compatible API for local or remote inference, HF model downloading, embedding model support, and HF Jinja2 chat templates. Its startup script manages and installs prerequisites to help you get started.
+
+<p align="center">
+ <img src="doc/qb_kld.png" width="640" alt="Llama 3.1 8B Instruct quantization benchmark across bits per weight">
+</p>
+
+## Installation
+
+Start by making sure you have the appropriate version of [PyTorch](https://pytorch.org/get-started/locally/) installed (CUDA 12.4 or later) since the Torch dependency is not automatically handled by `pip`. Then pick a method below:
+
+### Prebuilt wheel · recommended
+
+Pick a wheel from the [releases page](https://github.com/turboderp-org/exllamav3/releases), then e.g.:
+
+```sh
+pip install https://github.com/turboderp-org/exllamav3/releases/download/v0.0.6/exllamav3-0.0.6+cu128.torch2.8.0-cp313-cp313-linux_x86_64.whl
+```
+
+### Install from PyPI
+
+```sh
+pip install exllamav3
+```
+Note that the PyPI package does not contain a prebuilt extension and requires the CUDA toolkit and build prerequisites (i.e. VS Build Tools on Windows, gcc on Linux, `python-dev` headers etc.).
+
+### Build from source
+
+<details>
+<summary>Source installation with uv or pip</summary>
+
+
+`exllamav3` declares a minimum `torch` version (>= 2.6.0) and CUDA version (>= 12.4), but beyond that the user is free to select a version of `torch` that is compatible with their environment.
+
+`torch` can be installed in three ways (from least to most effort):
+1. **with `uv`, setting only `--extra cuXXX`** installs `torch` automatically with the specified CUDA version, `torch` version is selected by `uv` from compatible versions in the specific index associated with the chosen CUDA version (options 1 and 2)
+2. **with `uv`, creating a thin project that depends on `exllamav3[cuXXX]` and pins a specific `torch` version** — like (1) but `torch` is pinned in the thin project's `pyproject.toml`, see [pinning a specific PyTorch version (optional)](#pinning-a-specific-pytorch-version-optional) for details
+3. Manually with `uv pip` or `pip` (options 3 and 4)
+
+The flavor extras (`--extra`) are `cu124`, `cu126`, `cu128`, `cu129`, `cu130`, and `cu132` — pick the one matching your installed CUDA build. Both `uv sync` and `pip install .` build the package in an isolated environment where your `torch` is not visible, so they install the extension sources and compile them at first import (JIT, a few minutes once per torch version). For a precompiled install run `pip install --no-build-isolation .` in an environment that already has `torch`, or use the release wheels. Selecting a flavor installs the matching CUDA build of `torch`.
+
+**Option 1 — Working in the cloned repo directly (`uv sync`):**
+
+```sh
+git clone https://github.com/turboderp-org/exllamav3
+cd exllamav3
+# (Optional) switch to dev branch for latest in-progress features
+git checkout dev
+
+uv venv
+uv sync --extra cu130
+# add --extra examples and/or --extra eval for those extra dependencies
+```
+
+**Option 2 — Using `exllamav3` as a dependency from another project (`uv add`):**
+
+```sh
+# `uv add` works inside an existing project (a directory with a pyproject.toml).
+# `uv init` creates one if you're starting a new project, if integrating into
+# an existing project skip `uv init`.
+uv init my-project
+cd my-project
+
+# local checkout
+uv add 'path/to/exllamav3[cu130]' # non-editable
+uv add 'path/to/exllamav3[cu130]' --editable # editable
+
+# straight from GitHub
+uv add 'git+https://github.com/turboderp-org/exllamav3.git[cu130]' # default branch
+uv add 'git+https://github.com/turboderp-org/exllamav3.git[cu130]' --branch dev # specific branch
+```
+
+**Option 3 — Bring your own `torch` and let `uv` pick the backend automatically:**
+
+```sh
+uv venv # or: uv venv --python-preference only-managed
+source .venv/bin/activate
+uv pip install torch --torch-backend=auto
+uv pip install .
+```
+
+`--torch-backend=auto` inspects your system and installs the matching PyTorch CUDA build; see [Automatic backend selection](https://docs.astral.sh/uv/guides/integration/pytorch/#automatic-backend-selection).
+
+**Option 4 — With `pip`:**
+
+On Windows, you also need the `triton-windows` package (declared as a dependency in `pyproject.toml`); the attention, cache and recurrent kernels are Triton and ExLlamaV3 does not import without it.
+
+```sh
+# install a CUDA-enabled torch first so it matches your setup, e.g.:
+pip install torch --index-url https://download.pytorch.org/whl/cu128
+pip install .
+```
+
+</details>
+
+<details>
+<summary>Pinning a specific PyTorch version (optional)</summary>
+
+#### Pinning a specific PyTorch version (optional)
+
+The flavor extra picks the *index*, but by default torch resolves to the latest version on that
+index that satisfies `>=2.6.0`. To pin a specific torch version while developing on `exllamav3`,
+create a **"thin" project** that consumes your local checkout as an editable install and declares
+the exact `torch` version itself. This keeps the pin out of the `exllamav3` pyproject, so
+you can change the torch version freely without touching the repo.
+
+```
+my-exllamav3-dev/ # thin project (uv init)
+├── pyproject.toml
+└── src/ # package sources (auto-generated)
+```
+
+In `pyproject.toml`:
+
+```toml
+[project]
+name = "my-exllamav3-dev"
+version = "0.1.0"
+description = "Dev environment for exllamav3"
+requires-python = ">=3.10.11"
+dependencies = [
+ "exllamav3[cu130]", # select correct CUDA version
+ "torch==2.13.0", # pin the exact torch version you need
+]
+
+[tool.uv.sources]
+exllamav3 = { path = "../exllamav3", editable = true }
+```
+
+Adjust `../exllamav3` to point at your local checkout, then a plain `uv sync` sets up an
+environment with the correct PyTorch index (routed via the `cuXXX` extra),
+the pinned version of `torch` from that index (as long as it exists), and an editable install of `exllamav3` so code
+changes apply immediately. Switch CUDA flavors by changing the extra (`exllamav3[cu124]`,
+`exllamav3[cu128]`, …) and/or the torch pin in the thin project.
+
+Or, if you're installing torch manually with `uv pip install torch` (e.g. as in Option 3 above),
+specify the version directly, e.g. `uv pip install "torch==2.11.0" --torch-backend=auto`.
+
+</details>
+
+After installing with one of the options above, you should be able to run the conversion, eval and
+example scripts from the main repo directory, e.g., `uv run python convert.py -i ...` or, for manual
+installations once the venv is active
\ No newline at end of file
diff --git a/tools/cuda/smoke.py b/tools/cuda/smoke.py
new file mode 100644
index 0000000..d9ff8ec
--- /dev/null
+++ b/tools/cuda/smoke.py
@@ -0,0 +1,64 @@
+# Kyojin CUDA smoke (tools/cuda/README.md): load an EXL3 model with the engine at ENGINE (sys.path), greedy plain decode, time prefill and decode.
+# usage: python -I tools/cuda/smoke.py ENGINE_DIR MODEL_DIR OUT.json [NEW_TOKENS]
+import sys, os, time, json
+eng, mdir, out = sys.argv[1], sys.argv[2], sys.argv[3]; NEW = int(sys.argv[4]) if len(sys.argv) > 4 else 256
+sys.path.insert(0, eng)
+import torch
+from exllamav3 import Config, Model, Cache, Tokenizer, Generator
+from exllamav3.cache import CacheLayer_quant
+from exllamav3.generator.sampler import ArgmaxSampler
+import exllamav3
+res = {"engine": exllamav3.__file__, "version": exllamav3.__version__ if hasattr(exllamav3, "__version__") else None,
+ "model": mdir, "env": {k: v for k, v in os.environ.items() if k.startswith("EXL3_")}, "runs": []}
+t0 = time.time()
+MTP = int(os.environ.get("SMOKE_MTP", "0")); POL = os.environ.get("SMOKE_POLICY", "fixed") # MTP drafts (0 = plain), fixed | mix
+cfg = Config.from_directory(mdir); model = Model.from_config(cfg)
+KV = os.environ.get("SMOKE_KV", "16") # 16 or K,V bits of the quantized attention cache (e.g. 4,4)
+qkw = {} if KV == "16" else dict(layer_type=CacheLayer_quant, k_bits=int(KV.split(",")[0]), v_bits=int(KV.split(",")[1]))
+cache = Cache(model, max_num_tokens=8192, **qkw, **({"max_history": max(3, MTP), "max_batch_size": 1} if MTP else {})); model.load(); tok = Tokenizer.from_config(cfg)
+kw = {}
+DFL = os.environ.get("SMOKE_DFLASH") # DFlash2 drafter dir (upstream 1.6.0 only): a served speculative config
+if DFL:
+ dcfg = Config.from_directory(DFL); dm = Model.from_config(dcfg); dc = Cache(dm, max_num_tokens=16 * 256); dm.load()
+ dc.max_num_tokens = 8192 # ring cache as in a served drafter: the generator only compares sizes
+ kw = dict(draft_model=dm, draft_cache=dc, num_draft_tokens=MTP or 7)
+if MTP and not DFL:
+ dm = Model.from_config(cfg, component="mtp"); dc = Cache(dm, max_num_tokens=8192, max_history=max(3, MTP)); dm.load()
+ kw = dict(draft_model=dm, draft_cache=dc, num_draft_tokens=MTP)
+res["load_s"] = time.time() - t0; res["vram_gib"] = torch.cuda.max_memory_allocated() / 2**30
+gen = Generator(model=model, cache=cache, tokenizer=tok, **kw)
+res["mtp"] = MTP; res["policy"] = POL; res["kv"] = KV
+if MTP and POL == "mix":
+ sys.path.insert(0, os.path.join(eng, "tools", "qwen")); import spec_policy
+ thf, thv, maxd = spec_policy.env_defaults(MTP)
+ spec_policy.install(gen, dm, model, thf, thv, maxd, (2, 3, 5), {}, rule=spec_policy.rule_from_env(thf, thv, maxd), fixed=None)
+S = ArgmaxSampler()
+base = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "prompt_long.txt")).read()
+prompts = [
+ "<|im_start|>user\nWrite a short story about a lighthouse keeper who finds a message in a bottle.<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n",
+ "<|im_start|>user\nWrite a Python function that parses an ISO 8601 date string without using datetime, with tests.<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n",
+ "<|im_start|>user\nSummarise the following text in five bullet points:\n" + base + "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n",
+]
+from exllamav3 import Job
+def run(ids, new):
+ job = Job(input_ids=ids, max_new_tokens=new, sampler=S, stop_conditions=[])
+ torch.cuda.synchronize(); t0 = time.time(); tf = None; out = []
+ gen.enqueue(job)
+ while gen.num_remaining_jobs():
+ for r in gen.iterate():
+ if r.get("stage") == "streaming":
+ t = r.get("token_ids")
+ if t is not None and t.numel():
+ if tf is None: torch.cuda.synchronize(); tf = time.time()
+ out += t.flatten().tolist()
+ torch.cuda.synchronize(); te = time.time()
+ return out, tf - t0, te - tf
+run(tok.encode("Hello, warm-up."), 16) # warm-up (graphs, tuners)
+for p in prompts:
+ ids = tok.encode(p); n_in = ids.shape[-1]
+ oids, tp, td = run(ids, NEW)
+ r = {"n_in": n_in, "ttft_s": tp, "prefill_tps": n_in / tp, "decode_s": td, "decode_tps": (len(oids) - 1) / td,
+ "n_out": len(oids), "ids": oids, "text": tok.decode(torch.tensor([oids]))[0][:600] if oids else ""}
+ res["runs"].append(r); print(json.dumps({k: v for k, v in r.items() if k not in ("text", "ids")}), flush=True)
+res["max_vram_gib"] = torch.cuda.max_memory_allocated() / 2**30
+json.dump(res, open(out, "w"), indent=1)
diff --git a/tools/cuda/smoke_dflash2.py b/tools/cuda/smoke_dflash2.py
new file mode 100644
index 0000000..a9e0844
--- /dev/null
+++ b/tools/cuda/smoke_dflash2.py
@@ -0,0 +1,80 @@
+# DFlash2 smoke (GPU, run by hand): the target alone vs target + DFlash2 drafter, greedy, num_draft 7.
+# The two token streams must be identical for every prompt; prints tok/s and the drafter's gain.
+# usage: python -I smoke_dflash2.py ENGINE_DIR TARGET_DIR DRAFT_DIR OUT.json [NEW_TOKENS] [NUM_DRAFT]
+# Needs a prompt_long.txt next to this file or at PROMPT_FILE (third prompt); falls back to a repeated paragraph.
+# Exit code 0 = all streams identical, 1 = mismatch.
+import sys, os, time, json
+eng, mdir, ddir, out = sys.argv[1:5]
+NEW = int(sys.argv[5]) if len(sys.argv) > 5 else 256
+ND = int(sys.argv[6]) if len(sys.argv) > 6 else 7
+sys.path.insert(0, eng)
+import torch
+from exllamav3 import Config, Model, Cache, Tokenizer, Generator, Job
+from exllamav3.generator.sampler import ArgmaxSampler
+import exllamav3
+
+CTX = int(os.environ.get("SMOKE_CTX", 8192))
+res = {"engine": exllamav3.__file__, "target": mdir, "draft": ddir, "num_draft": ND, "runs": []}
+
+# Drafter first (as a server loads it): its cache holds the same number of tokens as the target's
+dcfg = Config.from_directory(ddir); dm = Model.from_config(dcfg)
+assert "dflash_draft" in dm.caps and dm.caps.get("attach_target"), "not a DFlash2 drafter"
+dc = Cache(dm, max_num_tokens = CTX); dm.load()
+cfg = Config.from_directory(mdir); model = Model.from_config(cfg)
+# The target is hybrid (recurrent): a rejected draft rolls its state back from max_history snapshots
+hist = max(dm.caps.get("default_draft_size", 4), ND)
+cache = Cache(model, max_num_tokens = CTX, max_history = hist, max_batch_size = 1); model.load()
+tok = Tokenizer.from_config(cfg)
+S = ArgmaxSampler()
+
+pf = os.environ.get("PROMPT_FILE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "prompt_long.txt"))
+base = open(pf).read() if os.path.exists(pf) else "The quick brown fox jumps over the lazy dog near the river bank. " * 120
+tail = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
+prompts = [
+ "<|im_start|>user\nWrite a short story about a lighthouse keeper who finds a message in a bottle." + tail,
+ "<|im_start|>user\nWrite a Python function that parses an ISO 8601 date string without using datetime, with tests." + tail,
+ "<|im_start|>user\nSummarise the following text in five bullet points:\n" + base + tail,
+]
+
+def run(gen, ids, new):
+ job = Job(input_ids = ids, max_new_tokens = new, sampler = S, stop_conditions = [])
+ torch.cuda.synchronize(); t0 = time.time(); tf = None; o = []
+ gen.enqueue(job)
+ while gen.num_remaining_jobs():
+ for r in gen.iterate():
+ if r.get("stage") == "streaming":
+ t = r.get("token_ids")
+ if t is not None and t.numel():
+ if tf is None: torch.cuda.synchronize(); tf = time.time()
+ o += t.flatten().tolist()
+ torch.cuda.synchronize()
+ return o, tf - t0, time.time() - tf
+
+def bench(gen, label):
+ run(gen, tok.encode("Hello, warm-up."), 16)
+ outs = []
+ for p in prompts:
+ ids = tok.encode(p)
+ o, tp, td = run(gen, ids, NEW)
+ r = {"mode": label, "n_in": ids.shape[-1], "ttft_s": tp, "n_out": len(o), "decode_s": td,
+ "decode_tps": (len(o) - 1) / td, "ids": o}
+ res["runs"].append(r); outs.append(o)
+ print(json.dumps({k: v for k, v in r.items() if k != "ids"}), flush = True)
+ return outs
+
+plain = bench(Generator(model = model, cache = cache, tokenizer = tok), "plain")
+gen = Generator(model = model, cache = cache, tokenizer = tok, draft_model = dm, draft_cache = dc, num_draft_tokens = ND)
+assert gen.dflash_draft, "generator did not pick the DFlash path"
+spec = bench(gen, "dflash2")
+
+ok = True
+for i, (a, b) in enumerate(zip(plain, spec)):
+ n = min(len(a), len(b)); first = next((j for j in range(n) if a[j] != b[j]), None)
+ same = first is None and len(a) == len(b)
+ ok &= same
+ tp = res["runs"][i]["decode_tps"]; ts = res["runs"][3 + i]["decode_tps"]
+ print(f"prompt {i}: identical={same} first_diff={first} plain={tp:.1f} tok/s dflash2={ts:.1f} tok/s x{ts / tp:.2f}", flush = True)
+res["identical"] = ok
+json.dump(res, open(out, "w"), indent = 1)
+print("RESULT", "OK identical" if ok else "MISMATCH", flush = True)
+sys.exit(0 if ok else 1)
diff --git a/tools/flint/kvgate.py b/tools/flint/kvgate.py
new file mode 100644
index 0000000..f1d8933
--- /dev/null
+++ b/tools/flint/kvgate.py
@@ -0,0 +1,117 @@
+"""Flint KV-format gate (copy of tools/qwen/kvgate.py): teacher-forced KL / top-1 of a quantized attention cache vs the fp16 cache, plus needle retrieval.
+ kvgate.py kl --kv 16|K,V [--depth 32768] [--win 512] [--text nat|copy] [--ref REF.pt | --save REF.pt]
+ kvgate.py needle --kv 16|K,V --ctx 131072 [--pos 0.1,0.5,0.9] [--seed 0]
+Prefix = real text (wiki/c4/technical, coherent run), window = the next --win tokens forced one by one through the decode path
+('copy' = the window repeats a passage from near the start, so the model must read far K/V)."""
+import argparse, ast, json, os, re, sys, time
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, os.path.abspath(os.path.join(HERE, "..", "..")))
+import torch
+from exllamav3 import Config, Model, Cache, Tokenizer, Generator, Job
+from exllamav3.cache import CacheLayer_quant
+from exllamav3.generator.sampler.sampler import Sampler
+
+ap = argparse.ArgumentParser()
+ap.add_argument("mode", choices=("kl", "needle"))
+ap.add_argument("--model", required=True)
+ap.add_argument("--kv", default="16"); ap.add_argument("--depth", type=int, default=32768); ap.add_argument("--win", type=int, default=512)
+ap.add_argument("--text", default="nat"); ap.add_argument("--ref"); ap.add_argument("--save")
+ap.add_argument("--ctx", type=int, default=131072); ap.add_argument("--pos", default="0.1,0.5,0.9"); ap.add_argument("--seed", type=int, default=0)
+ap.add_argument("--chunk", type=int, default=0); ap.add_argument("--gen", type=int, default=40)
+a = ap.parse_args()
+
+cfg = Config.from_directory(a.model); model = Model.from_config(cfg); tok = Tokenizer.from_config(cfg)
+need = a.depth + a.win if a.mode == "kl" else a.ctx
+ctx = ((need + 1024 + 255) // 256) * 256
+if a.kv == "16": cache = Cache(model, max_num_tokens=ctx, max_batch_size=1)
+else:
+ kb, vb = (int(x) for x in a.kv.split(","))
+ cache = Cache(model, max_num_tokens=ctx, max_batch_size=1, layer_type=CacheLayer_quant, k_bits=kb, v_bits=vb)
+t0 = time.time(); model.load(progressbar=False)
+print(f"loaded {time.time()-t0:.0f}s alloc {torch.cuda.memory_allocated()/2**30:.2f} GiB kv={a.kv} ctx={ctx}", flush=True)
+gen = Generator(model=model, cache=cache, tokenizer=tok, **({"max_chunk_size": a.chunk} if a.chunk else {}))
+D = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "exllamav3", "conversion", "standard_cal_data")
+
+def long_text_ids(n, seed=0):
+ """n tokens of coherent real text: wiki, then c4, then technical, then wiki again from another offset (no synthetic filler)."""
+ out, tot, files, i = [], 0, ["wiki.utf8", "c4.utf8", "technical.utf8", "code.utf8"], 0
+ cache_t = {}
+ while tot < n:
+ f = files[i % 4]; i += 1
+ if f not in cache_t: cache_t[f] = tok.encode(open(f"{D}/{f}", encoding="utf8").read(), add_bos=False)[0].view(-1)
+ t = cache_t[f]; take = min(len(t), n - tot + 16, 120000)
+ o = (seed * 7919 + i * 31337) % max(1, len(t) - take + 1)
+ out.append(t[o:o + take]); tot += take
+ return torch.cat(out)[:n]
+
+class TF(Sampler):
+ """teacher-forced sampler: returns the next true token, scores the logits against the reference run."""
+ def __init__(self, tgt, ref):
+ super().__init__(); self.tgt, self.ref, self.i = tgt, ref, 0; self.logs = []; self.kl = []; self.t1 = []; self.nll = []
+ def forward(self, logits, *args, **kw):
+ lg = logits.reshape(-1).float(); t = self.tgt[self.i]
+ lp = torch.log_softmax(lg, -1)
+ self.nll.append(-lp[t].item())
+ if self.ref is None: self.logs.append(lg.half().cpu())
+ else:
+ r = self.ref[self.i].to(lg.device).float(); rp = torch.log_softmax(r, -1)
+ self.kl.append((rp.exp() * (rp - lp)).sum().item()); self.t1.append(float(r.argmax() == lg.argmax()))
+ self.i += 1
+ return torch.tensor([[t]], device=logits.device)
+
+def run_kl():
+ n = a.depth + a.win; ids = long_text_ids(n, a.seed)
+ if a.text == "copy":
+ src0 = 1000; ids[a.depth:] = ids[src0:src0 + a.win]
+ prefix, tgt = ids[:a.depth].view(1, -1), ids[a.depth:].tolist()
+ ref = torch.stack(torch.load(a.ref)) if a.ref else None
+ if ref is not None: assert ref.shape[0] == a.win
+ s = TF(tgt, ref)
+ # warm-up on a short job (kernel compile / graph capture) before the timed one
+ w = Job(input_ids=ids[:600].view(1, -1), max_new_tokens=4, sampler=TF(ids[600:700].tolist(), None)); gen.enqueue(w)
+ while gen.num_remaining_jobs(): list(gen.iterate())
+ torch.cuda.reset_peak_memory_stats(); t0 = time.time()
+ job = Job(input_ids=prefix, max_new_tokens=a.win, sampler=s, stop_conditions=[]); gen.enqueue(job)
+ while gen.num_remaining_jobs():
+ for r in gen.iterate():
+ if r.get("error"): print("JOB ERROR", r["error"])
+ dt = time.time() - t0
+ assert s.i == a.win, s.i
+ res = {"kv": a.kv, "depth": a.depth, "text": a.text, "win": a.win, "nll": sum(s.nll) / len(s.nll), "peak_gib": torch.cuda.max_memory_allocated() / 2**30, "sec": dt}
+ if ref is None:
+ if a.save: torch.save(s.logs, a.save)
+ else:
+ kl = torch.tensor(s.kl); res.update(kl=kl.mean().item(), kl_med=kl.median().item(), kl_p99=kl.quantile(0.99).item(), top1=sum(s.t1) / len(s.t1))
+ print("RESULT", json.dumps(res), flush=True)
+
+WORDS = ["amber", "falcon", "granite", "harbor", "indigo", "juniper", "kestrel", "lantern", "marble", "nectar", "orchid", "pewter"]
+def run_needle():
+ base = long_text_ids(a.ctx, a.seed + 5)
+ fill = a.ctx - 1500
+ ok = 0; res = []
+ import random; rng = random.Random(a.seed)
+ # warm-up
+ w = Job(input_ids=base[:600].view(1, -1), max_new_tokens=4, sampler=TF(base[600:700].tolist(), None)); gen.enqueue(w)
+ while gen.num_remaining_jobs(): list(gen.iterate())
+ for p in [float(x) for x in a.pos.split(",")]:
+ code = f"{rng.choice(WORDS)}-{rng.randint(1000,9999)}-{rng.choice(WORDS)}"
+ needle = tok.encode(f"\n\nNote for the record: the vault passphrase of the Zeta project is {code}. Remember it.\n\n", add_bos=False)[0].view(-1)
+ q = tok.encode("\n\n---\nQuestion: what is the vault passphrase of the Zeta project? Answer with the passphrase only.", add_bos=False)[0].view(-1)
+ at = int(fill * p)
+ # chat-formatted question, thinking off, so the answer is the first thing generated
+ q = torch.cat([q, tok.encode("<|assistant|><think></think>", add_bos=False, encode_special_tokens=True)[0].view(-1)])
+ pre = tok.encode("<|user|>", add_bos=False, encode_special_tokens=True)[0].view(-1)
+ ids = torch.cat([pre, base[:at], needle, base[at:fill], q]).view(1, -1)
+ t0 = time.time()
+ job = Job(input_ids=ids, max_new_tokens=a.gen, sampler=__import__("exllamav3.generator.sampler.presets", fromlist=["x"]).GreedySampler()); gen.enqueue(job)
+ txt = ""
+ while gen.num_remaining_jobs():
+ for r in gen.iterate():
+ if r.get("error"): print("JOB ERROR", r["error"])
+ txt += r.get("text", "")
+ hit = code in txt; ok += hit
+ res.append({"pos": p, "len": ids.shape[1], "code": code, "out": txt.strip()[:60], "hit": hit, "sec": round(time.time() - t0, 1)})
+ print("NEEDLE", json.dumps(res[-1]), flush=True)
+ print("RESULT", json.dumps({"kv": a.kv, "ctx": a.ctx, "hits": f"{ok}/{len(res)}", "peak_gib": torch.cuda.max_memory_allocated() / 2**30}), flush=True)
+
+run_kl() if a.mode == "kl" else run_needle()
diff --git a/tools/flint/serve.py b/tools/flint/serve.py
new file mode 100644
index 0000000..dd54441
--- /dev/null
+++ b/tools/flint/serve.py
@@ -0,0 +1,317 @@
+#!/usr/bin/env python3
+"""flint-serve -- OpenAI-compatible server for Flint EXL3 packs (single GPU, one resident model).
+
+ python tools/flint/serve.py --model <pack> --port 8000 -c 131072 [--kv 8,8]
+
+POST /v1/chat/completions (stream and non-stream), GET /v1/models, GET /health. Uses the model's own chat template
+(<pack>/chat_template.jinja), the recommended sampling (temp 1.0 / top-p 0.95 / top-k 20, taken from
+generation_config.json) and parses Flint's output: <think>..</think> -> reasoning_content, <tool_call>name<arg_key>k
+</arg_key><arg_value>v</arg_value>..</tool_call> -> tool_calls. No grammar constraint on tool calls (the vendor SGLang
+kit adds one); finish_reason "tool_calls" when a call was parsed.
+"""
+from __future__ import annotations
+
+import argparse, asyncio, json, os, re, sys, threading, time, uuid, queue
+from pathlib import Path
+
+from aiohttp import web
+import jinja2
+from jinja2.sandbox import ImmutableSandboxedEnvironment
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+
+THINK_OPEN, THINK_CLOSE = "<think>", "</think>"
+TOOL_OPEN, TOOL_CLOSE = "<tool_call>", "</tool_call>"
+_CALL_RE = re.compile(r"<tool_call>(.*?)(?:</tool_call>|\Z)", re.S)
+_ARG_RE = re.compile(r"<arg_key>(.*?)</arg_key>\s*<arg_value>(.*?)</arg_value>", re.S)
+
+
+def render_prompt(template: str, messages: list[dict], tools: list[dict] | None) -> str:
+ env = ImmutableSandboxedEnvironment()
+ env.filters["tojson"] = lambda v, ensure_ascii=False, **kw: json.dumps(v, ensure_ascii=ensure_ascii)
+ fixed = []
+ for m in messages:
+ if m.get("tool_calls"):
+ calls = []
+ for c in m["tool_calls"]:
+ fn = dict(c.get("function", c))
+ if isinstance(fn.get("arguments"), str):
+ try: fn["arguments"] = json.loads(fn["arguments"])
+ except json.JSONDecodeError: fn["arguments"] = {}
+ calls.append({"function": fn})
+ m = dict(m, tool_calls=calls)
+ if isinstance(m.get("content"), list): # OpenAI content parts -> text
+ m = dict(m, content="".join(p.get("text", "") for p in m["content"] if isinstance(p, dict)))
+ fixed.append(m)
+ return env.from_string(template).render(messages=fixed, tools=tools or None, add_generation_prompt=True)
+
+
+def _val(raw: str):
+ try: return json.loads(raw)
+ except json.JSONDecodeError: return raw
+
+
+def parse_completion(text: str) -> dict:
+ """text = everything the model wrote after <|assistant|>."""
+ reasoning, content = "", text
+ if THINK_OPEN in text:
+ before, _, rest = text.partition(THINK_OPEN)
+ reasoning, close, after = rest.partition(THINK_CLOSE)
+ content = before + after if close else before
+ if not close: # cut off inside the reasoning
+ content = before
+ calls = []
+ for m in _CALL_RE.finditer(content):
+ body = m.group(1)
+ name = body.split("<arg_key>", 1)[0].strip()
+ if not name or not body.rstrip().endswith("</arg_value>") and "<arg_key>" in body and TOOL_CLOSE not in m.group(0):
+ continue
+ args = {k.strip(): _val(v) for k, v in _ARG_RE.findall(body)}
+ calls.append({"id": f"call_{uuid.uuid4().hex[:24]}", "type": "function",
+ "function": {"name": name, "arguments": json.dumps(args, ensure_ascii=False)}})
+ content = _CALL_RE.sub("", content).strip()
+ msg = {"role": "assistant", "content": content}
+ if reasoning.strip(): msg["reasoning_content"] = reasoning.strip()
+ if calls: msg["tool_calls"] = calls
+ return msg
+
+
+class Engine:
+ """One Generator on a worker thread; requests are Jobs, results are pushed to per-job queues."""
+
+ def __init__(self, model_dir: str, ctx: int, kv: str, max_batch: int, ngram: int = 0):
+ import torch
+ if torch.version.cuda and not torch.version.hip:
+ os.environ.setdefault("EXL3_CUDA_GRAPH", "1") # NVIDIA preset: whole-forward decode graph (read at import)
+ from exllamav3 import Config, Model, Cache, Tokenizer, Generator
+ from exllamav3.cache import CacheLayer_quant
+ self.config = Config.from_directory(model_dir)
+ self.model = Model.from_config(self.config)
+ if kv == "16":
+ self.cache = Cache(self.model, max_num_tokens=ctx)
+ else:
+ kb, vb = (int(x) for x in kv.split(","))
+ self.cache = Cache(self.model, max_num_tokens=ctx, layer_type=CacheLayer_quant, k_bits=kb, v_bits=vb)
+ self.model.load()
+ self.tok = Tokenizer.from_config(self.config)
+ self.gen = Generator(model=self.model, cache=self.cache, tokenizer=self.tok, max_batch_size=max_batch, **({'ngram_match_min': ngram} if ngram else {}))
+ self.ctx = ctx
+ self.inbox: queue.Queue = queue.Queue()
+ self.outq: dict[int, asyncio.Queue] = {}
+ self.jobs: dict = {}
+ self.loop = None
+ self.eos = list(self.config.eos_token_id_list) if getattr(self.config, "eos_token_id_list", None) else [150001, 150003, 150005, 150018]
+ threading.Thread(target=self._run, daemon=True).start()
+
+ def _run(self):
+ try:
+ self._loop()
+ except BaseException: # a dead engine thread leaves a zombie server holding the GPU: exit loudly instead
+ import traceback; traceback.print_exc(); sys.stderr.flush()
+ os._exit(1)
+
+ def _loop(self):
+ while True:
+ try:
+ while True:
+ ident, job = self.inbox.get(block=not self.gen.num_remaining_jobs(), timeout=None if not self.gen.num_remaining_jobs() else 0)
+ if job is None: # cancel request
+ j = self.jobs.pop(ident, None)
+ if j is not None:
+ try: self.gen.cancel(j)
+ except Exception: pass
+ continue
+ self.jobs[ident] = job
+ self.gen.enqueue(job)
+ except queue.Empty:
+ pass
+ if not self.gen.num_remaining_jobs():
+ continue
+ for r in self.gen.iterate():
+ q = self.outq.get(r["identifier"])
+ if q is not None:
+ self.loop.call_soon_threadsafe(q.put_nowait, r)
+ if r.get("eos"):
+ self.jobs.pop(r["identifier"], None)
+
+ def cancel(self, ident):
+ self.outq.pop(ident, None)
+ self.inbox.put((ident, None))
+
+ async def submit(self, prompt: str, max_new: int, sampler, stop: list[str]):
+ from exllamav3 import Job
+ ids = self.tok.encode(prompt, add_bos=False, encode_special_tokens=True)
+ ident = uuid.uuid4().int & 0x7FFFFFFF
+ self.loop = asyncio.get_running_loop()
+ q = asyncio.Queue()
+ self.outq[ident] = q
+ job = Job(input_ids=ids, max_new_tokens=max_new, sampler=sampler, stop_conditions=self.eos + stop,
+ identifier=ident, token_healing=False, decode_special_tokens=True)
+ self.inbox.put((ident, job))
+ return ident, ids.shape[-1], q
+
+
+def make_app(engine: Engine, model_id: str, template: str, defaults: dict) -> web.Application:
+ from exllamav3.generator.sampler import ComboSampler
+
+ async def chat_inner(request: web.Request):
+ body = await request.json()
+ msgs, tools = body.get("messages") or [], body.get("tools")
+ prompt = render_prompt(template, msgs, tools)
+ temp = float(body.get("temperature", defaults["temperature"]))
+ top_p = float(body.get("top_p", defaults["top_p"]))
+ top_k = int(body.get("top_k", defaults["top_k"]))
+ sampler = ComboSampler(temperature=temp, top_p=top_p, top_k=top_k)
+ n_prompt = len(engine.tok.encode(prompt, add_bos=False, encode_special_tokens=True)[0])
+ room = engine.ctx - n_prompt - 1
+ if room <= 0:
+ return web.json_response({"error": {"message": f"prompt is {n_prompt} tokens, context is {engine.ctx}"}}, status=400)
+ max_new = min(int(body.get("max_tokens") or body.get("max_completion_tokens") or defaults["max_new"]), room)
+ stop = body.get("stop") or []
+ stop = [stop] if isinstance(stop, str) else stop
+ ident, n_in, q = await engine.submit(prompt, max_new, sampler, stop)
+ request["ident"] = ident
+ created, cid = int(time.time()), f"chatcmpl-{uuid.uuid4().hex[:20]}"
+ stream = bool(body.get("stream"))
+ text, n_out, finish = "", 0, "stop"
+ stats: dict = {}
+ t_req = time.time()
+
+ def log_req():
+ print(f"req prompt={n_in} cached={stats.get('cached_tokens', 0)} new={n_in - stats.get('cached_tokens', 0)} "
+ f"out={n_out} prefill_s={stats.get('time_prefill', 0):.2f} generate_s={stats.get('time_generate', 0):.2f} "
+ f"queued_s={stats.get('time_enqueued', 0):.2f} wall_s={time.time() - t_req:.2f} finish={finish}", flush=True)
+
+ def usage():
+ c = int(stats.get("cached_tokens", 0))
+ return {"prompt_tokens": n_in, "completion_tokens": n_out, "total_tokens": n_in + n_out,
+ "prompt_tokens_details": {"cached_tokens": c}}
+
+ async def collect(on_text=None):
+ nonlocal text, n_out, finish
+ while True:
+ r = await q.get()
+ if r.get("text"):
+ text += r["text"]
+ if on_text: await on_text(r["text"])
+ if r.get("token_ids") is not None:
+ n_out += int(r["token_ids"].numel())
+ if r.get("eos"):
+ stats.update({k: r[k] for k in ("cached_tokens", "time_prefill", "time_generate", "time_enqueued") if k in r})
+ finish = "length" if r.get("eos_reason") == "max_new_tokens" else "stop"
+ break
+ engine.outq.pop(ident, None)
+
+ if not stream:
+ await collect()
+ msg = parse_completion(text)
+ if msg.get("tool_calls"): finish = "tool_calls"
+ log_req()
+ return web.json_response({"id": cid, "object": "chat.completion", "created": created, "model": model_id,
+ "choices": [{"index": 0, "message": msg, "finish_reason": finish}],
+ "usage": usage()})
+
+ resp = web.StreamResponse(headers={"Content-Type": "text/event-stream", "Cache-Control": "no-cache"})
+ await resp.prepare(request)
+ state = {"mode": "pre", "buf": ""} # pre: before any marker; think; content; tool
+
+ async def send(delta, fin=None):
+ chunk = {"id": cid, "object": "chat.completion.chunk", "created": created, "model": model_id,
+ "choices": [{"index": 0, "delta": delta, "finish_reason": fin}]}
+ await resp.write(f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n".encode())
+
+ await send({"role": "assistant", "content": ""})
+
+ async def on_text(t):
+ # a tiny state machine: emit reasoning / content as they arrive, hold tool-call text back
+ state["buf"] += t
+ while True:
+ b, m = state["buf"], state["mode"]
+ if m in ("pre", "content"):
+ marks = [(b.find(x), x) for x in (THINK_OPEN, TOOL_OPEN) if b.find(x) >= 0]
+ if marks:
+ i, x = min(marks)
+ if i: await send({"content": b[:i]})
+ state["buf"] = b[i + len(x):]
+ state["mode"] = "think" if x == THINK_OPEN else "tool"
+ if x == TOOL_OPEN: state["buf"] = TOOL_OPEN + state["buf"]
+ continue
+ keep = max((k for x in (THINK_OPEN, TOOL_OPEN) for k in range(1, len(x)) if b.endswith(x[:k])), default=0)
+ if len(b) > keep:
+ await send({"content": b[:len(b) - keep]}); state["buf"] = b[len(b) - keep:]
+ return
+ if m == "think":
+ i = b.find(THINK_CLOSE)
+ if i >= 0:
+ if i: await send({"reasoning_content": b[:i]})
+ state["buf"] = b[i + len(THINK_CLOSE):]; state["mode"] = "content"; continue
+ keep = max((k for k in range(1, len(THINK_CLOSE)) if b.endswith(THINK_CLOSE[:k])), default=0)
+ if len(b) > keep:
+ await send({"reasoning_content": b[:len(b) - keep]}); state["buf"] = b[len(b) - keep:]
+ return
+ return # tool: buffered until the end
+
+ await collect(on_text)
+ rest = state["buf"]
+ if state["mode"] in ("pre", "content") and rest:
+ await send({"content": rest})
+ elif state["mode"] == "think" and rest:
+ await send({"reasoning_content": rest})
+ calls = []
+ if state["mode"] == "tool" or TOOL_OPEN in text:
+ msg = parse_completion(text)
+ calls = msg.get("tool_calls", [])
+ if calls:
+ await send({"tool_calls": [dict(c, index=i) for i, c in enumerate(calls)]})
+ finish = "tool_calls"
+ await send({}, finish)
+ if body.get("stream_options", {}).get("include_usage", True):
+ await resp.write(f"data: {json.dumps({'id': cid, 'object': 'chat.completion.chunk', 'created': created, 'model': model_id, 'choices': [], 'usage': usage()})}\n\n".encode())
+ log_req()
+ await resp.write(b"data: [DONE]\n\n")
+ return resp
+
+ async def chat(request: web.Request):
+ try:
+ return await chat_inner(request)
+ except BaseException: # client went away (or error): free the job
+ if request.get("ident") is not None:
+ engine.cancel(request["ident"])
+ raise
+
+ async def models(_):
+ return web.json_response({"object": "list", "data": [{"id": model_id, "object": "model", "owned_by": "local"}]})
+
+ async def health(_):
+ return web.json_response({"status": "ok"})
+
+ app = web.Application()
+ app.router.add_post("/v1/chat/completions", chat)
+ app.router.add_get("/v1/models", models)
+ app.router.add_get("/health", health)
+ return app
+
+
+def main():
+ ap = argparse.ArgumentParser(allow_abbrev=False)
+ ap.add_argument("--host", default="127.0.0.1"); ap.add_argument("--port", type=int, default=8000)
+ ap.add_argument("--model", required=True); ap.add_argument("--model-id", default="flint")
+ ap.add_argument("-c", "--ctx", type=int, default=131072)
+ ap.add_argument("--kv", default=None, help="16 or K,V bits for the full-attention KV cache, e.g. 8,8 (default: 6,6 on NVIDIA, which fits 256K in 24 GB; 16 elsewhere)")
+ ap.add_argument("--max-batch", type=int, default=4)
+ ap.add_argument("--ngram", type=int, default=0, help="n-gram speculative drafting, min match length (0 = off; 5 gave +9 %% decode on code prompts, lossless)")
+ ap.add_argument("--default-max-new", type=int, default=32768, help="reply budget when a request omits max_tokens (thinking included)")
+ a = ap.parse_args()
+ if a.kv is None:
+ import torch
+ a.kv = "6,6" if torch.version.cuda and not torch.version.hip else "16"
+ gc = json.loads((Path(a.model) / "generation_config.json").read_text())
+ defaults = {"max_new": a.default_max_new, "temperature": gc.get("temperature", 1.0), "top_p": gc.get("top_p", 0.95), "top_k": gc.get("top_k", 20)}
+ template = (Path(a.model) / "chat_template.jinja").read_text()
+ engine = Engine(a.model, a.ctx, a.kv, a.max_batch, a.ngram)
+ print(f"flint-serve: {a.model} ctx={a.ctx} kv={a.kv} on {a.host}:{a.port}", flush=True)
+ web.run_app(make_app(engine, a.model_id, template, defaults), host=a.host, port=a.port)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/flint_memgate.py b/tools/flint_memgate.py
new file mode 100644
index 0000000..36016c5
--- /dev/null
+++ b/tools/flint_memgate.py
@@ -0,0 +1,81 @@
+"""Memory/gate probe: usage: flint_memgate.py PACK --depth N --kv 8,8 [--gen 128] [--prompts 2] [-o tokens.json]
+Prints memory_allocated after load, peak/reserved per prompt, and dumps greedy tokens."""
+import argparse, json, os, sys, time
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+import torch
+from exllamav3 import Config, Model, Cache, Tokenizer, Generator, Job
+from exllamav3.cache import CacheLayer_quant
+from exllamav3.generator.sampler.presets import GreedySampler
+ap = argparse.ArgumentParser()
+ap.add_argument("pack"); ap.add_argument("--depth", type=int, required=True); ap.add_argument("--gen", type=int, default=128)
+ap.add_argument("--kv", default="8,8"); ap.add_argument("--prompts", type=int, default=2); ap.add_argument("-o", "--out")
+ap.add_argument("--snap", action="store_true")
+a = ap.parse_args()
+G = 2**30
+def nt():
+ f, t = torch.cuda.mem_get_info(); return (t - f - torch.cuda.memory_reserved()) / G
+cfg = Config.from_directory(a.pack); model = Model.from_config(cfg); tok = Tokenizer.from_config(cfg)
+ctx = ((a.depth + a.gen + 512 + 255) // 256) * 256
+kb, vb = (int(x) for x in a.kv.split(","))
+cache = Cache(model, max_num_tokens=ctx, layer_type=CacheLayer_quant, k_bits=kb, v_bits=vb)
+model.load(progressbar=False)
+print(f"after load: alloc {torch.cuda.memory_allocated()/G:.3f} reserved {torch.cuda.memory_reserved()/G:.3f} non_torch {nt():.3f}", flush=True)
+gen = Generator(model=model, cache=cache, tokenizer=tok)
+D = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "exllamav3/conversion/standard_cal_data")
+def real_ids(n, seed):
+ out = []
+ for f in ("c4.utf8", "wiki.utf8", "code.utf8", "technical.utf8"):
+ s = open(f"{D}/{f}", encoding="utf8").read()
+ a0 = (seed * 7919) % max(1, len(s) // 3)
+ out.append(tok.encode(s[a0:a0 + max(int(n * 6), 200000)], add_bos=False)[0])
+ blocks = [o[:len(o) // 4096 * 4096].view(-1, 4096) for o in out]
+ mix = torch.cat([blocks[i % 4][(i // 4) % blocks[i % 4].shape[0]] for i in range(n // 4096 + 2)])
+ return mix[:n].view(1, -1)
+def run(ids, ngen):
+ job = Job(input_ids=ids, max_new_tokens=ngen, sampler=GreedySampler(), return_top_tokens=0)
+ gen.enqueue(job); t0 = time.time(); ttft = None; times = []; toks = []; txt = ""
+ while gen.num_remaining_jobs():
+ for r in gen.iterate():
+ if r.get("error"): print("JOB ERROR", r["error"], flush=True)
+ if r.get("text", ""):
+ now = time.time()
+ if ttft is None: ttft = now - t0
+ else: times.append(now)
+ txt += r["text"]
+ return ttft, times, txt
+run(real_ids(256, 99), 8)
+print(f"after warmup: alloc {torch.cuda.memory_allocated()/G:.3f} reserved {torch.cuda.memory_reserved()/G:.3f} non_torch {nt():.3f}", flush=True)
+import threading, collections
+free0, tot = torch.cuda.mem_get_info(); print(f"mem_get_info free {free0/G:.3f} total {tot/G:.3f}", flush=True)
+cb = sum(t.numel()*t.element_size() for l in cache.layers.values() for t in l.get_tensors()) if hasattr(next(iter(cache.layers.values())), "get_tensors") else -1
+print(f"cache bytes {cb/G:.3f} GiB", flush=True)
+best = {"peak": 0, "snap": None}; stop = False
+def poll():
+ import time as _t
+ while not stop:
+ m = torch.cuda.memory_allocated()
+ if m > best["peak"] + (48 << 20) and m > 0:
+ best["peak"] = m; best["snap"] = torch.cuda.memory.memory_snapshot()
+ _t.sleep(0.02)
+if a.snap: threading.Thread(target=poll, daemon=True).start()
+res = []
+for p in range(a.prompts):
+ torch.cuda.reset_peak_memory_stats()
+ ttft, times, txt = run(real_ids(a.depth, 1000 + p), a.gen)
+ if ttft is None: print("NO TOKENS", torch.cuda.max_memory_allocated()/G, torch.cuda.max_memory_reserved()/G); break
+ tg = (len(times) - 1) / (times[-1] - times[0]) if len(times) > 2 else 0
+ print(json.dumps({"p": p, "pp": a.depth / ttft, "tg": tg, "peak": torch.cuda.max_memory_allocated()/G,
+ "resv": torch.cuda.max_memory_reserved()/G, "cur_alloc": torch.cuda.memory_allocated()/G}), flush=True)
+ res.append(txt)
+if a.out: json.dump(res, open(a.out, "w"))
+
+stop = True
+if best["snap"]:
+ c = collections.Counter()
+ for seg in best["snap"]:
+ for b in seg["blocks"]:
+ if b["state"] == "active_allocated": c[b["size"]] += 1
+ print("snapshot at ~peak %.3f GiB; active blocks by total size:" % (best["peak"]/G))
+ for sz, n in sorted(c.items(), key=lambda x: -x[0]*x[1])[:25]:
+ print(f" {n:5d} x {sz/2**20:10.2f} MiB = {n*sz/G:7.3f} GiB")
+ print("segments:", len(best["snap"]), "reserved", sum(s["total_size"] for s in best["snap"])/G)
diff --git a/tools/glm/SERVE.md b/tools/glm/SERVE.md
index 4c87273..8af6c82 100644
--- a/tools/glm/SERVE.md
+++ b/tools/glm/SERVE.md
@@ -111,6 +111,8 @@ Honored:
`top_p` (default: the pack's `generation_config.json`, 1.0 and 0.95), `stop` (string or array; also fed to EXL3 as stop conditions).
- `model` — must equal `--model-id` if present, else 400.
- `clear_thinking` — forwarded to the template as a Jinja variable.
+- `loop_guard` (bool, chat and `/v1/completions`) — `false` turns the answer-phase loop guard off for this request; absent or `true`
+ follows `EXL3_LOOP_GUARD` (default on). See "Loop guard" below.
Ignored (accepted, no effect): `n`, `seed`, `logprobs`, `top_k`, `presence_penalty`,
`frequency_penalty`, `response_format`, `stream_options`, `user`, `parallel_tool_calls`,
@@ -220,6 +222,15 @@ one salt namespace at a time (requests without a salt are one namespace): when i
prompt cache is dropped (a fresh Generator over the same cache) and the request starts. The same salt, or no salt at all,
never drops anything. `chat_template_kwargs` (`reasoning_effort`, `clear_thinking`) is read like the top-level fields and wins.
+### Loop guard
+The server watches the answer (the text after `</think>`, or the whole reply when the prompt opens no think block) and ends a reply
+that fell into a loop: a repeated token period, or a tail that replays itself. The thinking block itself is not watched. The guard
+cancels the job and the turn reports `finish_reason` `length`, `choices[0].stop_reason` `loop_guard` and the detail in
+`timings.loop_guard` (`phase`, `kind`, `at`, `cut`), so a client can tell a guard stop from a natural end. Valid repetitive output
+(dense code, tables, JSON records) is not cut, and neither is repetitive data (a grid of zeros, identical JSON lines, a zero-padded
+hex dump) until it has repeated for 16384 tokens. `EXL3_LOOP_GUARD=0` turns the guard off for the server; `"loop_guard": false` in a
+request body turns it off for that request (a non-boolean value answers 400). It is not applied with `ignore_eos: true`.
+
### Thinking
GLM's generation prompt ends with `<think>`, so the model *starts inside* the block.
`opens_thinking()` detects that (`prompt.rstrip().endswith("<think>")`) and the server
diff --git a/tools/glm/serve.py b/tools/glm/serve.py
index 999c34c..1911a26 100644
--- a/tools/glm/serve.py
+++ b/tools/glm/serve.py
@@ -25,6 +25,7 @@ from jinja2.sandbox import ImmutableSandboxedEnvironment
sys.path.append(str(Path(__file__).resolve().parent.parent))
import startup_health # noqa: E402 (GET /health with load progress while the model loads)
+from loopguard import AnswerTap, loop_guard_default # noqa: E402 (answer-phase loop guard shared with the Qwen server)
import serve_compat # noqa: E402 (vLLM-style token-id prompts, cache_salt, /tokenize, usage details)
from l21_prompt_encode_cache import PromptEncodeCache # noqa: E402 (incremental prompt encode)
# serve_metrics.py is a symlink to the shared tools/strix_halo/serve_metrics.py
@@ -115,6 +116,16 @@ SPEED_ENV = {
# side-writes the state where those pages end, so the next one resumes there: first token after a shared 9K / 12.1K prefix
# 2.41 -> 1.94 s, 3.84 -> 2.06 s; the writing prompt is bitwise unchanged, KLD vs a cold prefill at the resumed-turn level.
"EXL3_BRANCH_CKPT": "1",
+ # prompt-tail recurrent checkpoints on the last 7 page boundaries before the prompt end: a re-sent prefix whose last page
+ # checkpoint lies after the divergence resumes within one page of it. 89.6K prompt, new question at the end: 6.0 -> 1.7 s,
+ # 1539 -> 259 rows replayed (one forward pass); about +0.4 GiB host memory, flat over 20 turns. A resume replays a different
+ # number of rows than a cold prefill and the GEMM path depends on the row count, so the output is not yet bit-identical to a
+ # cold prefill; the fix is in progress. Off on GLM until then (the Qwen preset has it on).
+ "EXL3_TAIL_DENSE": "0",
+ # sub-page prompt-tail checkpoints on the last 4 multiples of 64 rows: a prompt that diverges in its final tokens replays
+ # about 65 rows instead of up to a page (89.6K prompt, new question at the end: 1.7 -> 0.8 s first token); at most
+ # EXL3_TAIL_SUB_MAX (8) entries of 142 MiB host memory. Same numerics caveat as the dense checkpoints; off.
+ "EXL3_TAIL_SUB": "0",
# such a resume (page-aligned, off the 2048 chunk grid) with a short remainder keeps the tail in its one chunk (prompt-end tail
# checkpoint) instead of a separate last-page forward: 2.00 -> 1.42 s, 2.44 -> 1.51 s; KLD vs a cold prefill unchanged in class.
"EXL3_TAIL_OFFGRID": "1",
@@ -474,6 +485,24 @@ def parse_completion(text: str) -> dict[str, Any]:
return message
+def token_count(event: dict) -> int:
+ t = event.get("token_ids")
+ return int(t.numel()) if t is not None else 0
+
+
+def guard_hit(tap, event: dict) -> dict | None:
+ """Feed one generator event to the answer-phase guard; the hit dict when the answer loops."""
+ if tap is None or event.get("eos"):
+ return None
+ t = event.get("token_ids")
+ return tap.feed(t.flatten().tolist() if t is not None and t.numel() else [], event.get("text") or "")
+
+
+def guard_stats(hit: dict, n_new: int) -> dict:
+ """The end-of-job report of a request the guard stopped (the job was cancelled, so it has no eos event)."""
+ return {"eos_reason": "loop_guard", "new_tokens": n_new, "loop_guard": hit}
+
+
def opens_thinking(prompt: str) -> bool:
"""The GLM generation prompt ends in <think>, so the model output starts inside the block."""
return prompt.rstrip().endswith("<think>")
@@ -649,6 +678,9 @@ class ResidentEngine:
self.lookup_stats: dict[str, int] = {}
self.cache = Cache(self.model, max_num_tokens=ctx + 4096,
max_history=max_history, max_batch_size=slots)
+ from exllamav3.util import jit_log, kernel_seed
+ kernel_seed.install() # shipped Triton kernels for this Triton version: nothing to compile on a first start
+ jit_log.install() # EXL3_LOG_JIT=1: one line per Triton compile
startup_health.stage("target weights")
self.model.load(device="cuda:0", progressbar=False, callback=startup_health.load_callback())
if num_draft > 0:
@@ -876,7 +908,8 @@ class ResidentEngine:
top_p: float, stop: list[str], sampler_kw: dict | None = None,
cancel: asyncio.Event | None = None,
images: list | None = None, stats: dict | None = None, img_stats: dict | None = None,
- prompt_ids: list[int] | None = None, ignore_eos: bool = False) -> AsyncIterator[str]:
+ prompt_ids: list[int] | None = None, ignore_eos: bool = False,
+ loop_guard: bool | None = None) -> AsyncIterator[str]:
"""Yield incremental decoded text. With sessions == 1 the caller serializes access to this method; with
sessions > 1 several calls may run at once and the final stats of a request land in `stats`.
@@ -928,10 +961,13 @@ class ResidentEngine:
job = self.Job(input_ids=ids, max_new_tokens=max_tokens, sampler=sampler,
stop_conditions=conditions, embeddings=embs or None)
if self.sessions > 1:
- async for piece in self._run_shared(job, ids, cancel, stats if stats is not None else {}, t0, probe):
+ async for piece in self._run_shared(job, ids, cancel, stats if stats is not None else {}, t0, probe, prompt, ignore_eos, loop_guard):
yield piece
return
loop = asyncio.get_running_loop()
+ guard_on = loop_guard_default() if loop_guard is None else bool(loop_guard) # loop_guard=False in the request turns it off
+ tap = AnswerTap(opens_thinking(prompt)) if guard_on and not ignore_eos else None
+ seen = 0 # tokens streamed so far, for the guard stop report
generator.enqueue(job)
try:
while generator.num_remaining_jobs():
@@ -945,6 +981,13 @@ class ResidentEngine:
text = event.get("text", "")
if text:
yield text
+ hit = guard_hit(tap, event)
+ if hit is not None and not event.get("eos"):
+ generator.cancel(job)
+ seen += token_count(event)
+ self.last_stats = guard_stats(hit, seen)
+ return
+ seen += token_count(event)
if event.get("eos"):
self.last_stats = event
if probe is not None:
@@ -1054,11 +1097,15 @@ class ResidentEngine:
if q is not None: # None: cancelled after the step started
q.put_nowait(evs)
- async def _run_shared(self, job, ids, cancel, stats: dict, t0: float, probe) -> AsyncIterator[str]:
+ async def _run_shared(self, job, ids, cancel, stats: dict, t0: float, probe, prompt: str = "", ignore_eos: bool = False,
+ loop_guard: bool | None = None) -> AsyncIterator[str]:
"""One request's job in the shared Generator: enqueue on the driver, stream its events, and (whatever way this
ends) remove the job, so no leftover job runs inside another request."""
q: asyncio.Queue = asyncio.Queue()
generator = self.greedy_generator
+ guard_on = loop_guard_default() if loop_guard is None else bool(loop_guard)
+ tap = AnswerTap(opens_thinking(prompt)) if guard_on and not ignore_eos else None
+ seen = 0
def enqueue():
self._routes[generator.enqueue(job)] = q # on the driver: no step can emit before the route exists
@@ -1079,6 +1126,12 @@ class ResidentEngine:
text = event.get("text", "")
if text:
yield text
+ hit = guard_hit(tap, event)
+ if hit is not None and not event.get("eos"):
+ stats.update(guard_stats(hit, seen + token_count(event)))
+ self.last_stats = stats
+ return # the finally block cancels the job
+ seen += token_count(event)
if event.get("eos"):
stats.update(event)
self.last_stats = stats
@@ -1414,6 +1467,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
**({"images": body["_images"]} if body.get("_images") else {}),
**({"prompt_ids": body["_prompt_ids"]} if body.get("_prompt_ids") is not None else {}),
**({"ignore_eos": True} if body.get("_ignore_eos") else {}),
+ **({"loop_guard": body["_loop_guard"]} if body.get("_loop_guard") is not None else {}),
**({"stats": request_stats} if sessions > 1 else {})):
if not first_token:
first_token = True
@@ -1512,6 +1566,9 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
raise web.HTTPBadRequest(reason="messages must be a non-empty array")
if "stream" in body and not isinstance(body["stream"], bool):
raise web.HTTPBadRequest(reason="stream must be boolean")
+ if body.get("loop_guard") is not None and not isinstance(body["loop_guard"], bool):
+ raise web.HTTPBadRequest(reason="loop_guard must be boolean")
+ body["_loop_guard"] = body.get("loop_guard") # False: this request runs without the answer-phase loop guard
stops = body.get("stop", [])
body["_stop"] = [stops] if isinstance(stops, str) else list(stops)
urls = extract_images(body["messages"])
@@ -1571,7 +1628,8 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
def finish_for(message: dict[str, Any], raw: str) -> str:
# A reply cut by max_tokens is "length", not "stop" (clients use it to tell a truncated answer).
finish = message.pop("finish_reason", "stop")
- if finish == "stop" and engine.count_tokens(raw) >= token_limit(body):
+ if finish == "stop" and (request_stats.get("eos_reason") == "loop_guard"
+ or engine.count_tokens(raw) >= token_limit(body)):
finish = "length"
return finish
@@ -1584,7 +1642,8 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
return {"cache_n": cache_n, "prompt_n": max(prompt_tokens - cache_n, 0),
"prompt_ms": pre * 1000, "predicted_n": n, "predicted_ms": gen * 1000,
"prompt_per_second": (prompt_tokens - cache_n) / pre if pre else 0.0,
- "predicted_per_second": n / gen if gen else 0.0}
+ "predicted_per_second": n / gen if gen else 0.0,
+ **({"loop_guard": st["loop_guard"]} if st.get("loop_guard") else {})}
if body.get("stream", False):
response = web.StreamResponse(headers={"Content-Type": "text/event-stream", "Cache-Control": "no-cache"})
@@ -1630,8 +1689,10 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
if "tool_calls" in message:
for n, call in enumerate(message["tool_calls"]): # one stream message per call (clients that read one call per message)
await writer.write(sse(event({"tool_calls": [dict(call, index=n)]})))
- await writer.write(sse(event({}, finish_for(message, text[len(prefix):])) |
- {"usage": usage(text[len(prefix):]), "timings": timings(text)}))
+ final = event({}, finish_for(message, text[len(prefix):])) | {"usage": usage(text[len(prefix):]), "timings": timings(text)}
+ if request_stats.get("eos_reason") == "loop_guard":
+ final["choices"][0]["stop_reason"] = "loop_guard"
+ await writer.write(sse(final))
await writer.write(b"data: [DONE]\n\n")
await response.write_eof()
lifecycle.stream_done(body["_reqid"], int(request_stats.get("new_tokens") or 0))
@@ -1668,10 +1729,13 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
text, _ = stop_text(prefix + raw, body["_stop"])
message = parse_completion(text)
finish = finish_for(message, text[len(prefix):])
- return web.json_response({
+ payload = {
"id": request_id, "object": "chat.completion", "created": created, "model": model_id,
"choices": [{"index": 0, "message": message, "finish_reason": finish}],
- "usage": usage(text[len(prefix):]), "timings": timings(text)})
+ "usage": usage(text[len(prefix):]), "timings": timings(text)}
+ if request_stats.get("eos_reason") == "loop_guard":
+ payload["choices"][0]["stop_reason"] = "loop_guard"
+ return web.json_response(payload)
async def apply_template(request: web.Request) -> web.Response:
"""llama.cpp's POST /apply-template: render the chat template, generate nothing.
@@ -1801,7 +1865,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
raise web.HTTPBadRequest(reason="prompt must be a non-empty string or a list of token ids (one prompt per request)")
if body.get("n") not in (None, 1) or body.get("echo") or body.get("best_of") not in (None, 1):
raise web.HTTPBadRequest(reason="n, best_of and echo are not supported")
- for key in ("stream", "ignore_eos"):
+ for key in ("stream", "ignore_eos", "loop_guard"):
if body.get(key) is not None and not isinstance(body[key], bool):
raise web.HTTPBadRequest(reason=f"{key} must be boolean")
max_tokens = 16 if body.get("max_tokens") is None else body["max_tokens"]
@@ -1813,6 +1877,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
raise web.HTTPBadRequest(reason="stop must be a string or a list of strings")
prompt_tokens = len(prompt_ids) if prompt_ids is not None else engine.count_tokens(prompt)
job = {"_prompt": prompt, "_prompt_ids": prompt_ids, "_ignore_eos": body.get("ignore_eos") is True,
+ "_loop_guard": body.get("loop_guard"),
"max_tokens": max_tokens, "_room": reply_room(engine, prompt_tokens), "_stop": list(stops),
"temperature": float(SERVE_DEFAULTS["temperature"] if body.get("temperature") is None else body["temperature"]),
"top_p": float(SERVE_DEFAULTS["top_p"] if body.get("top_p") is None else body["top_p"]),
@@ -1838,7 +1903,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
def finish_and_usage(text: str, stopped: str | None) -> tuple[str, dict[str, Any]]:
n_new = int(request_stats.get("new_tokens") or engine.count_tokens(text))
- reason = "length" if stopped is None and (request_stats.get("eos_reason") == "max_new_tokens" or n_new >= limit) else "stop"
+ reason = "length" if stopped is None and (request_stats.get("eos_reason") in ("max_new_tokens", "loop_guard") or n_new >= limit) else "stop"
return reason, serve_compat.usage(prompt_tokens, n_new, int(request_stats.get("cached_tokens") or 0))
hold = max((len(x) for x in job["_stop"]), default=1) - 1
@@ -1871,7 +1936,11 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
if len(text) > sent:
await writer.write(sse(chunk(text[sent:], None)))
reason, usage = finish_and_usage(text, stopped)
- await writer.write(sse(chunk("", reason) | {"usage": usage}))
+ last = chunk("", reason) | {"usage": usage}
+ if request_stats.get("eos_reason") == "loop_guard":
+ last["choices"][0]["stop_reason"] = "loop_guard"
+ last["timings"] = {"loop_guard": request_stats.get("loop_guard")}
+ await writer.write(sse(last))
await writer.write(b"data: [DONE]\n\n")
await response.write_eof()
lifecycle.stream_done(job["_reqid"], int(request_stats.get("new_tokens") or 0))
@@ -1904,7 +1973,11 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
raise
text, stopped = stop_text(raw, job["_stop"])
reason, usage = finish_and_usage(text, stopped)
- return web.json_response(chunk(text, reason) | {"usage": usage})
+ out_ = chunk(text, reason) | {"usage": usage}
+ if request_stats.get("eos_reason") == "loop_guard":
+ out_["choices"][0]["stop_reason"] = "loop_guard"
+ out_["timings"] = {"loop_guard": request_stats.get("loop_guard")}
+ return web.json_response(out_)
async def slots(_: web.Request) -> web.Response:
return web.json_response(engine.slot_store.slots())
@@ -2025,6 +2098,9 @@ def main() -> None:
f"(per-session window = -c / sessions when all are busy); greedy output is not guaranteed equal to the same "
f"request run alone; slot save/restore waits for every running request and acts on the last prompt noted",
file=sys.stderr, flush=True)
+ if os.environ.get("EXL3_SCHED_CHUNK_IL", "0") == "1":
+ # chunked-prefill interleave (exllamav3/generator/chunk_il.py): needs another request running beside the big prefill
+ print("serve: chunk_il ON " + ("" if args.sessions > 1 else "(no effect: needs --sessions >= 2)"), file=sys.stderr, flush=True)
if args.no_uncensor:
os.environ["EXL3_ABLIT_RUNTIME"] = "off"
SERVE_DEFAULTS.update(pack_sampling(args.model))
diff --git a/tools/glm/test_serve.py b/tools/glm/test_serve.py
index 829fb95..9f08bd4 100644
--- a/tools/glm/test_serve.py
+++ b/tools/glm/test_serve.py
@@ -892,6 +892,17 @@ class VllmCompatTests(unittest.TestCase):
self.assertEqual(body["usage"]["prompt_tokens_details"], {"cached_tokens": 4}) # engine said 99: clamped
self.assertEqual((body["choices"][0]["text"], body["choices"][0]["finish_reason"]), ("abc", "length"))
+ def test_loop_guard_opt_out_reaches_the_engine(self):
+ # per-request loop_guard=false (as on the Qwen server): passed to generate(); absent when the request says nothing
+ eng = self.Eng()
+ for path, payload in (("/v1/completions", {"model": "m", "prompt": [1, 2], "max_tokens": 4}),
+ ("/v1/chat/completions", {"model": "m", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 4})):
+ self.assertEqual(self.one(eng, path, payload)[0], 200, path)
+ self.assertNotIn("loop_guard", eng.calls[-1][1])
+ self.assertEqual(self.one(eng, path, payload | {"loop_guard": False})[0], 200, path)
+ self.assertIs(eng.calls[-1][1]["loop_guard"], False)
+ self.assertEqual(self.one(eng, path, payload | {"loop_guard": "no"})[0], 400, path)
+
def test_stream_ends_with_usage_and_done(self):
eng = self.Eng()
st, raw = self.one(eng, "/v1/completions", {"model": "m", "prompt": [1, 2, 3], "max_tokens": 8, "stream": True,
diff --git a/tools/kernel_seed/build.py b/tools/kernel_seed/build.py
new file mode 100755
index 0000000..fa02d02
--- /dev/null
+++ b/tools/kernel_seed/build.py
@@ -0,0 +1,40 @@
+#!/usr/bin/env python3
+"""Pack a populated Triton cache into the shipped kernel seed.
+
+ 1. Start the server with an EMPTY cache and the portable cache keys, without installing the old seed:
+ EXL3_KERNEL_SEED=build TRITON_CACHE_DIR=/scratch/tcache (and HOME on a scratch dir) ...
+ 2. python tools/kernel_seed/sweep.py --url http://127.0.0.1:8731 --model <id>
+ 3. python tools/kernel_seed/build.py /scratch/tcache [/scratch/tcache2 ...]
+Run steps 1-2 once per server family (same or separate cache dirs; build.py merges several) to get one seed for qwen + glm. Writes
+exllamav3/kernel_seed/triton-<triton version>-<arch>.tar.xz (replace, do not merge: rebuild from the full set).
+The cache keys of a seed built without EXL3_KERNEL_SEED=build hold the install prefix of the build machine: they would not hit
+anywhere else (see exllamav3/util/kernel_seed.py). pack() strips the debug sections of the code objects with llvm-objcopy (ROCm
+toolchain; LLVM_OBJCOPY overrides the lookup), writes a placeholder for the library paths in the metadata, and fails when a member
+still holds a local path.
+"""
+import argparse, sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+from exllamav3.util import kernel_seed # noqa: E402
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("cache", nargs="+", help="populated Triton cache directories (one per server family; a key in several: first wins)")
+ ap.add_argument("--arch", default=None, help="default: the architecture of the GPU in this machine, else gfx1151")
+ ap.add_argument("--triton-version", default=None)
+ a = ap.parse_args()
+ if a.arch is None:
+ a.arch = kernel_seed.device_arch() or "gfx1151"
+ if a.triton_version is None:
+ import triton
+ a.triton_version = triton.__version__
+ out = kernel_seed.SEED_DIR / kernel_seed.seed_name(a.triton_version, a.arch)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ n = kernel_seed.pack([Path(c) for c in a.cache], out)
+ print(f"{n} kernels -> {out} ({out.stat().st_size / 1e6:.2f} MB)")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/kernel_seed/sweep.py b/tools/kernel_seed/sweep.py
new file mode 100755
index 0000000..e50f3ab
--- /dev/null
+++ b/tools/kernel_seed/sweep.py
@@ -0,0 +1,41 @@
+#!/usr/bin/env python3
+"""Drive a running server through the request shapes a user reaches, so that every Triton kernel variant gets compiled
+(used to build the kernel seed, see build.py). Greedy and sampled, prompt lengths from a few tokens to several chunks,
+prose / code / digits (different speculative acceptance, so different verify lengths), plus a repeated prompt (cache hit)."""
+import argparse, json, random, urllib.request
+
+LENGTHS = (3, 12, 33, 70, 130, 300, 700, 1500, 3000, 4200, 4800, 6500, 9000)
+SEEDS = ("The history of the Roman empire, told as a story. ", "def fib(n):\n return n if n < 2 else fib(n-1) + fib(n-2)\n",
+ "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ", "Explain in detail how a transformer language model works. ")
+
+
+def post(url, model, content, max_tokens, temperature, timeout=900):
+ body = {"model": model, "messages": [{"role": "user", "content": content}], "max_tokens": max_tokens,
+ "temperature": temperature, "top_p": 0.95 if temperature else 1.0}
+ req = urllib.request.Request(url + "/v1/chat/completions", json.dumps(body).encode(), {"content-type": "application/json"})
+ with urllib.request.urlopen(req, timeout=timeout) as r:
+ return json.load(r)
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__)
+ ap.add_argument("--url", default="http://127.0.0.1:8731")
+ ap.add_argument("--model", required=True)
+ ap.add_argument("--max-tokens", type=int, default=96)
+ a = ap.parse_args()
+ rnd = random.Random(0)
+ n = 0
+ for i, ln in enumerate(LENGTHS):
+ for j, seed in enumerate(SEEDS):
+ words = (seed * (ln // max(len(seed.split()), 1) + 1)).split()[:ln]
+ text = " ".join(words) + "\nContinue."
+ for temp in (0.0, 0.8):
+ post(a.url, a.model, text, a.max_tokens, temp)
+ n += 1
+ post(a.url, a.model, "Say hi.", 1, 0.0)
+ post(a.url, a.model, "Say hi.", 1, 0.0)
+ print(f"{n + 2} requests done")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/l21_prompt_encode_cache.py b/tools/l21_prompt_encode_cache.py
index 866322a..41c0e17 100644
--- a/tools/l21_prompt_encode_cache.py
+++ b/tools/l21_prompt_encode_cache.py
@@ -10,8 +10,15 @@
# pec = PromptEncodeCache(tokenizer, n=8, cut="<|im_start|>", render=lambda msgs: render_prompt(template, msgs, None))
# ids, hit = pec.encode(prompt) # ids: 1-D LongTensor (CPU), same as tokenizer.encode(prompt, add_bos=False, encode_special_tokens=True)
#
+# Soft cuts: a long text that shares a prefix but has no turn-start token inside it (same document, another question in the same
+# user message) is also cut after a newline that is followed by a non-space character. That position is a pre-tokenizer boundary
+# (the newline run ends there whatever follows), so the ids equal the full encode's; the cache needs the backend's token offsets
+# for it (HF tokenizers, no extra specials) and a construction self-test on punctuation / digits / indentation / unicode text turns
+# soft cuts off where the equality fails.
+#
# Not for prompts with image embeddings (encode those in full). Thread-safe (one lock).
import re, threading
+import numpy as np
import torch
@@ -20,12 +27,14 @@ class PromptEncodeCache:
def __init__(self, tokenizer, n: int = 8, cut="<|im_start|>", render=None, check: bool = False, log=print):
cuts = [cut] if isinstance(cut, str) else list(cut)
self.tokenizer, self.n, self.check, self.log = tokenizer, n, check, log
- self.e = [] # [text, ids, marker char starts, marker token positions], most recent first
+ self.e = [] # [text, ids, marker char starts, marker token positions, soft cuts, token starts, token ends], most recent first
+ self.soft, self.n_soft_hits = False, 0
self.lock = threading.Lock()
mids = [self.full(c) for c in cuts]
if not cuts or any(m.numel() != 1 for m in mids):
log(f"prompt encode cache off: {cuts!r} not one token each"); self.n = 0; return
self.mids = torch.tensor([int(m[0]) for m in mids])
+ self.soft_re = re.compile(r"(?<=\n)(?=\S)")
self.cut_re = re.compile("|".join(re.escape(c) for c in sorted(cuts, key=len, reverse=True)))
msgs = [{"role": "system", "content": "S x"}, {"role": "user", "content": "Hi there, how are you?"},
{"role": "assistant", "content": "Fine. And you?"}, {"role": "user", "content": "Tell me about pages."}]
@@ -41,38 +50,89 @@ class PromptEncodeCache:
if not ok:
log("prompt encode cache off: self-test failed"); self.n = 0
self.e = []
+ self.soft = False
+ hf = getattr(tokenizer, "tokenizer", None)
+ if self.n and hf is not None and hasattr(hf, "encode") and not getattr(tokenizer, "unspecial_piece_to_id", None) \
+ and not getattr(tokenizer, "missing_special_piece_to_id", None):
+ self.hf, self.soft = hf, True
+ try:
+ doc = ("Intro line.\n\nSecond paragraph, with numbers 12345 and 'quotes' (and) {braces}:\n def f(x):\n"
+ " return x + 1 # c\n\n\nThird para, odd spacing...\n\n indented\n\ttab\n\nnaïve café 日本語 \U0001F600\n\n")
+ for tail in ("Question one: why?", "Question two: how 42?", " x"):
+ self.encode(doc + doc.upper() + tail)
+ p2 = doc + doc.upper() + tail.replace("one", "three").replace("two", "four") + "\n" + cuts[0]
+ ids, hit = self.encode(p2)
+ if not (hit and torch.equal(ids, self.full(p2))):
+ self.soft = False; break
+ self.soft = self.soft and self.n_soft_hits > 0
+ except Exception as ex:
+ self.soft = False; log(f"prompt encode cache soft cuts error: {ex}")
+ if not self.soft:
+ log("prompt encode cache: soft cuts off")
+ self.e = []
def full(self, p: str) -> torch.Tensor:
ids = self.tokenizer.encode(p, add_bos=False, encode_special_tokens=True)
ids = ids[0] if isinstance(ids, tuple) else ids
return ids.reshape(-1).cpu()
+ def full_off(self, p: str):
+ """ids, token start offsets, token end offsets (numpy) of p, one backend pass (same ids as full())."""
+ self.hf.encode_special_tokens = False
+ enc = self.hf.encode(p, add_special_tokens = False)
+ off = np.asarray(enc.offsets, dtype = np.int64).reshape(-1, 2)
+ return torch.tensor(enc.ids, dtype = torch.long), off[:, 0], off[:, 1]
+
def encode(self, p: str):
if not self.n:
return self.full(p), False
with self.lock:
- best = None
- for i, (t, ids, cs, ts) in enumerate(self.e):
+ best = None # (entry index, char cut, token position, extends-last-item, is soft)
+ for i, (t, ids, cs, ts, sc, st, en) in enumerate(self.e):
lo, hi = -1, len(cs) - 1 # last marker whose start lies inside the shared text: binary search over the markers
while lo < hi:
mid = (lo + hi + 1) // 2
if cs[mid] <= len(p) and p[:cs[mid]] == t[:cs[mid]]: lo = mid
else: hi = mid - 1
if lo >= 0 and cs[lo] > 0 and (best is None or cs[lo] > best[1]):
- best = (i, cs[lo], ts[lo], lo == len(cs) - 1) # last item: p extends this entry (same conversation)
+ best = (i, cs[lo], ts[lo], lo == len(cs) - 1, False) # last item: p extends this entry (same conversation)
+ if self.soft and sc:
+ # soft cut c: t[c - 1] is a newline, t[c] is not whitespace; p must share t[:c + 1] (so p[c] is that character too)
+ lo, hi = -1, len(sc) - 1
+ while lo < hi:
+ mid = (lo + hi + 1) // 2
+ if sc[mid] + 1 <= len(p) and p[:sc[mid] + 1] == t[:sc[mid] + 1]: lo = mid
+ else: hi = mid - 1
+ while lo >= 0 and (best is None or sc[lo] > best[1]):
+ k = int(np.searchsorted(st, sc[lo]))
+ if 0 < k < len(st) and st[k] == sc[lo] and en[k - 1] == sc[lo]:
+ best = (i, sc[lo], k, False, True)
+ break
+ lo -= 1
if best is not None:
- i, c, tpos, _ = best
- ids = torch.cat([self.e[i][1][:tpos], self.full(p[c:])])
+ i, c, tpos, _, soft = best
+ if self.soft:
+ sids, sst, sen = self.full_off(p[c:])
+ e = self.e[i]
+ ids = torch.cat([e[1][:tpos], sids])
+ off = (np.concatenate([e[5][:tpos], sst + c]), np.concatenate([e[6][:tpos], sen + c]))
+ else:
+ ids = torch.cat([self.e[i][1][:tpos], self.full(p[c:])]); off = None
+ self.n_soft_hits += 1 if soft else 0
if self.check and not torch.equal(ids, self.full(p)):
- self.log("prompt encode cache MISMATCH, full encode used"); ids, best = self.full(p), None
+ self.log("prompt encode cache MISMATCH, full encode used"); ids, best, off = self.full(p), None, None
+ elif self.soft:
+ ids, st, en = self.full_off(p); off = (st, en)
else:
- ids = self.full(p)
- self._add(p, ids, best[0] if best is not None and best[3] else None)
+ ids = self.full(p); off = None
+ self._add(p, ids, best[0] if best is not None and best[3] else None, off)
return ids, best is not None
- def _add(self, p, ids, drop=None):
+ def _add(self, p, ids, drop=None, off=None):
cs = [m.start() for m in self.cut_re.finditer(p)]
ts = torch.isin(ids, self.mids).nonzero().reshape(-1).tolist()
if len(cs) == len(ts):
if drop is not None: self.e.pop(drop)
- self.e.insert(0, [p, ids, cs, ts]); del self.e[self.n:]
+ sc = [m.start() for m in self.soft_re.finditer(p)] if (self.soft and off is not None) else []
+ st, en = off if off is not None else (None, None)
+ self.e.insert(0, [p, ids, cs, ts, sc, st, en]); del self.e[self.n:]
diff --git a/tools/loopguard.py b/tools/loopguard.py
new file mode 100644
index 0000000..8f5f084
--- /dev/null
+++ b/tools/loopguard.py
@@ -0,0 +1,242 @@
+"""Loop guard shared by the Qwen and GLM servers: an n-gram period detector and a text rule for loops that drift.
+
+Thinking uses the release-gate rule of tools/evalgate/loops.py; an answer needs proof of replay on top, so that valid
+repetitive code or data is not cut (see answer_text_loop). CPU only, no model needed: tools/qwen/loopguard_gate.py replays a
+labelled corpus through it with the real tokenizers.
+"""
+from __future__ import annotations
+
+import os
+import re
+from typing import Any
+
+
+# An n-gram period detector, plus a text rule for loops that drift (no exact period): the release-gate rule of tools/evalgate/loops.py (zlib ratio of the last 1000 chars
+# < 30 % AND a 50-char span seen >= 3 times in the last 3000 chars) that must hold for a sustained stretch. Greedy
+# thinking on a near-tie (the Qwen3.8 trait, ifeval-0015/0114/0195) is the target: the guard closes the think block.
+GUARD_MAX_N = 64
+GUARD_THINK = {"k": 4, "min_span": 48, "sustain": 320} # tokens; GLM thresholds for the period rule
+GUARD_ANSWER = {"k": 6, "min_span": 96, "sustain": 640} # stricter: an answer may repeat items legitimately
+GUARD_CHECK_EVERY = 16 # tokens between two evaluations of the text rule
+TEXT_WINDOW, TEXT_RATIO, TEXT_MIN_CHARS = 1000, 0.30, 200
+SPAN_TAIL, SPAN_LEN, SPAN_MIN = 3000, 50, 3
+
+
+def loop_guard_default() -> bool:
+ return os.environ.get("EXL3_LOOP_GUARD", "1") != "0"
+
+
+def text_loop(text: str) -> bool:
+ """tools/evalgate/loops.is_loop (kept identical; test_serve checks both agree)."""
+ import zlib
+ from collections import Counter
+ w = text[-TEXT_WINDOW:]
+ if len(w) < TEXT_MIN_CHARS or len(zlib.compress(w.encode())) / max(len(w.encode()), 1) >= TEXT_RATIO:
+ return False
+ t = text[-SPAN_TAIL:]
+ return max(Counter(t[i:i + SPAN_LEN] for i in range(len(t) - SPAN_LEN + 1)).values(), default=0) >= SPAN_MIN
+
+
+ANSWER_REPEAT_MIN, ANSWER_SHINGLE = 0.5, 60 # answer rule: share of 60-character shingles of the tail already seen in it
+ANSWER_SATURATED = 0.07 # answer rule: zlib ratio of the last 3000 characters
+ANSWER_UNIT_MIN, ANSWER_UNITS_MIN, ANSWER_UNITS_ALONE = 25, 0.3, 0.6 # answer rule: share of repeated lines / sentences
+DATA_LETTERS_MAX, DATA_MIN_CHARS, DATA_SUSTAIN = 0.10, 40, 16384 # content check: letters share of a data tail; tokens a data repetition may run before it is cut anyway
+COUNTER_SUSTAIN, COUNTER_RATIO = 2000, 0.09 # counter arm: tokens it must hold, zlib ratio of the last 3000 characters (valid ramps: 0.10 and up)
+
+
+def counter_drift(text: str) -> bool:
+ """The last lines (25 characters or more) are one template whose numbers only move by 0 or 1 from line to line:
+ `fillBox(cx-1,cx+1,254,254,...)`, `fillBox(...,255,255,...)`, ... A loop that counts has no repeated stretch and a
+ tail that compresses to about 0.07; a table or a list of values has a field that jumps, and a valid ramp (a list of
+ 300 numbered links) still compresses less (0.10 and up). Needs 8 lines."""
+ import zlib
+ from collections import Counter
+ b = text[-SPAN_TAIL:].encode()
+ if len(zlib.compress(b)) / max(len(b), 1) >= COUNTER_RATIO:
+ return False
+ lines = [ln for ln in text[-SPAN_TAIL:].split("\n") if len(ln.strip()) >= ANSWER_UNIT_MIN]
+ if len(lines) < 8:
+ return False
+ tmpl = [re.sub(r"\d+", "#", ln) for ln in lines]
+ top, n = Counter(tmpl).most_common(1)[0]
+ if n < 0.8 * len(lines):
+ return False
+ rows = [[int(x) for x in re.findall(r"\d+", ln)] for ln, t in zip(lines, tmpl) if t == top]
+ steps = [all(abs(a - b) <= 1 for a, b in zip(r1, r2)) for r1, r2 in zip(rows, rows[1:])]
+ return sum(steps) >= 0.9 * len(steps)
+
+
+def _json_doc(line: str) -> bool:
+ import json
+ try:
+ return isinstance(json.loads(line), (dict, list))
+ except ValueError:
+ return False
+
+
+def data_like(text: str) -> bool:
+ """The tail of an answer is data, not prose or code: almost no letters (a grid of zeros, a zero-padded hex dump, a table of
+ numbers), or JSON lines (every complete line of the tail is a JSON object or array). Such output repeats because the data
+ does (80 rows of 40 zeros, 60 identical records), not because the model is stuck, and a stop is final. The answer rules
+ still cut it, but only after DATA_SUSTAIN tokens, so a loop on data does not run to the token limit."""
+ t = text[-SPAN_TAIL:]
+ body = [c for c in t if not c.isspace()]
+ if len(body) < DATA_MIN_CHARS:
+ return False
+ if sum(c.isalpha() for c in body) <= DATA_LETTERS_MAX * len(body):
+ return True
+ lines = [ln.strip() for ln in t.split("\n")[1:-1] if ln.strip()] # the first and last lines may be cut by the window
+ return len(lines) >= 4 and all(_json_doc(ln) for ln in lines)
+
+
+def shingle_repeat(text: str, k: int = ANSWER_SHINGLE) -> float:
+ """Share of the k-character shingles of the last 3000 characters that already occurred earlier in that tail. A loop
+ brings back whole stretches of text, so nearly every shingle is a repeat (0.55 and more); valid repetitive output
+ (dense code, tables, JSON records) shares short idioms but writes new text around them (0.43 at most in our corpus, real code 0.16)."""
+ t = text[-SPAN_TAIL:]
+ seen: set[str] = set()
+ hits = 0
+ for i in range(len(t) - k + 1):
+ s = t[i:i + k]
+ if s in seen:
+ hits += 1
+ else:
+ seen.add(s)
+ return hits / max(len(t) - k + 1, 1)
+
+
+def repeated_units(text: str) -> float:
+ """Share of the lines and sentences (25 characters or more) of the last 3000 characters that repeat an earlier one
+ word for word; 0.0 below 6 units. A loop that drifts re-emits the same few units in changing order, so no long stretch
+ repeats but the units do. Valid code and data write a new line each time (0.2 at most in our corpus)."""
+ units = [u.strip() for u in re.split(r"\n+|(?<=[.!?])\s+", text[-SPAN_TAIL:]) if len(u.strip()) >= ANSWER_UNIT_MIN]
+ return 1 - len(set(units)) / len(units) if len(units) >= 6 else 0.0
+
+
+def answer_text_loop(text: str) -> bool:
+ """The release-gate rule (text_loop) is the right trigger for a thinking block, where a restart costs a few tokens.
+ In an answer a stop is final, and valid code or data is often repetitive enough to trip it (a one-shot HTML page with
+ a dozen dense helper functions did: zlib ratio 0.296, one 50-character idiom four times). So the answer needs proof
+ that nothing new is written, on top of a repeated 50-character span: most of the tail replays itself
+ (shingle_repeat >= 0.5), the same lines come back (repeated_units >= 0.3), or the tail compresses to almost nothing
+ although no stretch is replayed (a template that only changes a counter). Lines that come back in more than half of
+ the units are a loop without any span. The 0.30 zlib ratio of the gate rule is not asked here: it misses loops in
+ scripts whose UTF-8 bytes compress poorly (Hindi, Thai); the replay shares do not depend on the script."""
+ import zlib
+ t = text[-SPAN_TAIL:]
+ if len(t) < TEXT_MIN_CHARS:
+ return False
+ units = repeated_units(t)
+ if units >= ANSWER_UNITS_ALONE:
+ return True
+ if max_span_repeat(t) < SPAN_MIN:
+ return False
+ if units >= ANSWER_UNITS_MIN or shingle_repeat(t) >= ANSWER_REPEAT_MIN:
+ return True
+ b = t.encode()
+ return len(zlib.compress(b)) / max(len(b), 1) < ANSWER_SATURATED
+
+
+class LoopMonitor:
+ """Watches the tokens of one generation. feed() returns None, or a dict
+ {phase, kind ("period"|"text"|"budget"), cut (tokens of the current phase to keep), at, period}.
+ Phases: "think" (until the </think> token) then "answer"; a request without a think block starts in "answer".
+ With detect=False only the thinking budget is enforced."""
+
+ def __init__(self, phase: str, close_id: int | None, budget: int | None = None, detect: bool = True):
+ self.close_id, self.budget, self.detect = close_id, budget, detect
+ self.start_phase(phase)
+
+ def start_phase(self, phase: str) -> None:
+ self.phase = phase
+ self.cfg = GUARD_THINK if phase == "think" else GUARD_ANSWER
+ self.ids: list[int] = []
+ self.run = [0] * (GUARD_MAX_N + 1)
+ self.text = ""
+ self.last_check = 0
+ self.flag_from: int | None = None
+ self.counter_from: int | None = None
+ self._data_at, self._data = -GUARD_CHECK_EVERY, False # data_like() of the tail, refreshed every GUARD_CHECK_EVERY tokens
+
+ def _data_tail(self, at: int) -> bool:
+ if at - self._data_at >= GUARD_CHECK_EVERY:
+ self._data_at, self._data = at, data_like(self.text)
+ return self._data
+
+ def feed(self, tokens, text: str = "") -> dict[str, Any] | None:
+ tokens = [int(t) for t in tokens]
+ if self.phase == "think" and self.close_id is not None and self.close_id in tokens:
+ k = tokens.index(self.close_id)
+ hit = self._feed(tokens[:k], text)
+ if hit:
+ return hit
+ self.start_phase("answer")
+ return self._feed(tokens[k + 1:], "")
+ return self._feed(tokens, text)
+
+ def _feed(self, tokens, text: str) -> dict[str, Any] | None:
+ ids, run, cfg = self.ids, self.run, self.cfg
+ self.text += text
+ for t in tokens:
+ i = len(ids)
+ ids.append(t)
+ if self.phase == "think" and self.budget is not None and i + 1 >= self.budget:
+ return {"phase": "think", "kind": "budget", "cut": self.budget, "at": i + 1, "period": 0}
+ if not self.detect:
+ continue
+ for n in range(1, GUARD_MAX_N + 1):
+ r = run[n] + 1 if i >= n and t == ids[i - n] else 0
+ run[n] = r
+ if r >= max(n * (cfg["k"] - 1), cfg["min_span"] - n):
+ if r < DATA_SUSTAIN and self.phase == "answer" and self._data_tail(i):
+ continue # legit repetitive data: the period must hold for DATA_SUSTAIN tokens before it is a loop
+ return {"phase": self.phase, "kind": "period", "cut": max(i - r + 1, 1), "at": i + 1, "period": n}
+ if self.detect and len(ids) - self.last_check >= GUARD_CHECK_EVERY:
+ prev, self.last_check = self.last_check, len(ids)
+ if (answer_text_loop if self.phase == "answer" else text_loop)(self.text[-(SPAN_TAIL + 200):]):
+ if self.flag_from is None:
+ self.flag_from = prev
+ if len(ids) - self.flag_from >= (DATA_SUSTAIN if self.phase == "answer" and self._data_tail(len(ids)) else cfg["sustain"]):
+ return {"phase": self.phase, "kind": "text", "cut": max(self.flag_from, 1), "at": len(ids), "period": 0}
+ else:
+ self.flag_from = None
+ if self.phase == "answer" and counter_drift(self.text[-(SPAN_TAIL + 200):]):
+ if self.counter_from is None:
+ self.counter_from = prev
+ if len(ids) - self.counter_from >= (DATA_SUSTAIN if self._data_tail(len(ids)) else COUNTER_SUSTAIN):
+ return {"phase": "answer", "kind": "counter", "cut": max(self.counter_from, 1), "at": len(ids), "period": 0}
+ else:
+ self.counter_from = None
+ if len(self.text) > 4 * SPAN_TAIL:
+ self.text = self.text[-SPAN_TAIL * 2:]
+ return None
+
+
+def max_span_repeat(text: str) -> int:
+ t = text[-SPAN_TAIL:]
+ from collections import Counter
+ return max(Counter(t[i:i + SPAN_LEN] for i in range(len(t) - SPAN_LEN + 1)).values(), default=0)
+
+
+class AnswerTap:
+ """Answer-phase guard for a server that streams events of text and token ids and cannot retract (GLM).
+
+ A reply that opens inside a think block (`thinking=True`) is not watched until the closing tag shows up in the
+ text; after that, or from the start without a think block, every event feeds an answer-phase LoopMonitor.
+ feed() returns None, or the monitor's hit dict (kind, at, cut, period) once the answer loops."""
+
+ def __init__(self, thinking: bool, close_tag: str = "</think>"):
+ self.close_tag, self.waiting, self.tail = close_tag, thinking, ""
+ self.mon = None if thinking else LoopMonitor("answer", None)
+
+ def feed(self, tokens, text: str) -> dict[str, Any] | None:
+ if self.waiting:
+ joined = self.tail + text
+ k = joined.find(self.close_tag)
+ if k < 0:
+ self.tail = joined[-len(self.close_tag):]
+ return None
+ self.waiting, text = False, joined[k + len(self.close_tag):]
+ tokens = [] # the tokens of this event are not split at the tag: only the text after it is fed
+ self.mon = LoopMonitor("answer", None)
+ return self.mon.feed(tokens, text)
diff --git a/tools/make_readme_table.py b/tools/make_readme_table.py
index 0030b78..3ee6b5e 100644
--- a/tools/make_readme_table.py
+++ b/tools/make_readme_table.py
@@ -9,6 +9,7 @@ def ck(c): return "500K" if int(c) == 499712 else f"{int(c) // 1024}K" # 49971
def b(m, v): return v if m.get("earlier") else f"<b>{v}</b>"
def label(m): return f'{m["name"]} <sub>({m["earlier"]})</sub>' if m.get("earlier") else f'<b>{m["name"]}</b>'
rows = "".join(f'<tr><td>{label(m)}</td><td align="right">{m["pack_gb"]:g} GB</td><td align="right">{m["table"]["prefill"]}</td><td align="right">{b(m, m["table"]["decode"])}</td></tr>\n' for m in F["models"])
+rows += "".join(r + "\n" for r in F.get("readme_extra_rows", [])) # rows with no chart curves (DeepSeek-V4.1-Flash)
table = ('<table align="center">\n<tr><th align="left">Model</th><th>Pack</th><th>Prefill</th><th>Speculative decode</th></tr>\n' + rows + '</table>')
CT = sorted({int(c) for m in F["models"] for c in m["prefill"]})
in_main = F["models"]
@@ -46,8 +47,9 @@ def long_block():
pts = [131072, 262144, 499712]
ms = [m for m in F["models"] if all(str(c) in m["prefill"] and m["decode"].get(str(c)) for c in pts)]
if not ms: return ""
+ # the release the figures were measured on (figures.json), not the version of the tree the README is built from
vf = os.path.join(root, "exllamav3", "version.py")
- ver = re.search(r'"([^"]+)"', open(vf).read()).group(1) if os.path.exists(vf) else F.get("version", "")
+ ver = F.get("version") or (re.search(r'"([^"]+)"', open(vf).read()).group(1) if os.path.exists(vf) else "")
t = '<table align="center">\n<tr><th align="left">Model</th>' + "".join(f"<th>{ck(c)}</th>" for c in pts) + "</tr>\n"
for m in ms:
t += f'<tr><td>{label(m)}</td>' + "".join(f'<td align="right">{f(m["prefill"][str(c)])} / {f(m["decode"][str(c)])}</td>' for c in pts) + "</tr>\n"
diff --git a/tools/qwen/SERVE.md b/tools/qwen/SERVE.md
index a348dd1..911cc45 100644
--- a/tools/qwen/SERVE.md
+++ b/tools/qwen/SERVE.md
@@ -36,7 +36,7 @@ Quick test:
| `--model-id` | `Qwen3.8-Flash-Yamz` | id in `/v1/models`; requests that name another model get 400 |
| `--host`, `--port` | `127.0.0.1`, 8000 | listen address |
| `-c`, `--ctx` | 65536 | KV cache size in tokens (prompt + answer must fit) |
-| `--cache-bits` | 0 | `0` = fp16 K/V cache pages (default); `8` = packed int8 pages: 2.6 GiB less at 256K (peak 83.6 vs 86.2 GiB), but output is not row-invariant when several rows decode together |
+| `--cache-bits` | 0 | `0` = fp16 K/V cache pages (default); `8` = packed int8 pages: 2.6 GiB less at 256K (peak 83.6 vs 86.2 GiB), but greedy output differs from the 16-bit cache; with `EXL3_ROW_INV_GROUPS=1` four parallel sessions matched solo runs, 16 of 16 (see Concurrent sessions) |
| `--ndt` | 7 | max draft tokens per speculative round (the rule drafts up to 3 on most rounds, deeper only on confident chains) |
| `--draft-policy` | `mix` | `mix` shipped rule, `mtp` fixed MTP chain, `off` plain decode (no drafter loaded) |
| `--no-vision` | off | do not load the vision tower (less memory, image input answers 400) |
@@ -76,6 +76,12 @@ The pack is tied to one set of weights: download it from the same model repo.
Give thinking room: with a small `max_tokens` the budget can end inside the thought, so `content` is empty and
`finish_reason` is `length`.
- `finish_reason`: `stop`, `length` (cut by `max_tokens`), `tool_calls`.
+ The loop guard can end an answer that degenerated into a loop. That turn reports `finish_reason` `length`,
+ `choices[0].stop_reason` `loop_guard` (chat and completions, stream and JSON) and the detail in `timings.loop_guard`
+ (`phase`, `kind`, `at`, `cut`). A natural end never carries `stop_reason`. Valid repetitive output (dense code, tables,
+ JSON records) is not cut: in an answer the guard needs most of the tail to replay itself, or a tail that compresses to
+ almost nothing. Repetitive data (a grid of zeros, identical JSON lines, a zero-padded hex dump) is cut only after 16384 tokens of
+ repetition. `loop_guard: false` in the request body turns the guard off.
- Tool calls: the model writes `<tool_call><function=NAME><parameter=KEY>VALUE</parameter></function></tool_call>`.
They come back as OpenAI `tool_calls`; argument types follow the tool's JSON schema. In a stream, tool calls arrive
as one delta after the text. Text after a closed call (or between two calls) is returned as `content`.
@@ -166,12 +172,23 @@ Measured with `--ndt 3`, `-c 262144`, temperature 0, two short prompts sent toge
| 4 | 8 | no (2 of 4 differ) | 2.19 s | 51.4 |
| 4 | 0 | no (2 of 4 differ) | not measured | 54.4 (reported, another machine) |
-With N > 1, greedy output is not guaranteed equal to a solo run, for either cache width: the decode attention kernel
-chooses how it splits the cache from the batch it runs with, so the last bits of the sums, and now and then a near-tie
-token, can change. What was measured: the 16-bit cache (`--cache-bits 0`) stayed equal on two short prompts at 2 sessions and differed on 2 of 4 at 4 sessions (reported by @felladrin on 1.3);
-the 8-bit cache did not (rows above). Two short prompts show nothing more than that.
-
-The server prints this warning at start-up whenever N > 1, and a second one past 8 verify rows (`N x (ndt + 1)`).
+By default the answers of parallel requests can differ from solo runs (rows above). `EXL3_ROW_INV_GROUPS=1` (opt-in) makes the
+decode step row-exact: the jobs of one step are packed into forwards of at most 8 token rows, and the attention layers of a
+forward with several sequences run one sequence at a time, so each row gets the bits of the same row decoded alone. With
+`--ndt 7`, four cold 8K prompts sent together at `--sessions 4` gave greedy answers equal to the same prompts sent one at a
+time, 16 of 16, with the 16-bit cache and with `--cache-bits 8` (without it: 5 to 7 of 16). A step with one job runs as before, so
+`--sessions 1` is unchanged. Cost: about 3 % more wall time on that four-prompt load, and 8 to 10 % less aggregate decode
+throughput on short prompts (four parallel sessions then decode no faster than one).
+
+Where the opt-in is not exact:
+- A request whose context grows past about 2051 tokens while it shares a step with other requests can hit one different token:
+ the step where a sequence crosses the sparse-attention threshold, if the draft width of the group differs from the width the
+ request would have drafted alone (measured: 7 of 8 equal on 2030-token prompts). The 8K gate prompts start past the threshold
+ and never cross it. Fixing it needs a per-job draft width at the crossing step.
+- While a request with images in its prompt is active, every step it shares runs as one forward (no groups), so the other
+ requests lose the guarantee. Vision was off in every measurement above.
+
+The server prints a warning at start-up with N > 1 unless `EXL3_ROW_INV_GROUPS=1`.
## Tests
diff --git a/tools/qwen/batch_inv.py b/tools/qwen/batch_inv.py
new file mode 100644
index 0000000..96fbc52
--- /dev/null
+++ b/tools/qwen/batch_inv.py
@@ -0,0 +1,607 @@
+#!/usr/bin/env python
+"""Row invariance of the Qwen decode / verify forward when several requests are decoded together (--sessions N).
+
+One engine load with the serve defaults (SERVE_ENV of serve.py, the speculative policy of the server). Stages:
+ ref : plain greedy continuation of each probe prompt, one request alone (feeds the oracle drafts of `ops`)
+ rinv : one request alone, greedy ids for the plain step, the shipped draft policy and fixed draft depths 1/3/7:
+ the ids a request gets must not depend on how deep its neighbours make it draft
+ ops : one verify forward of job A alone against the same job next to N-1 others, per module and per row, in
+ execution order (the first differing module is the culprit). Drafts come from the plain continuation
+ (some positions corrupted on purpose, so the accept lengths differ), depth --depths, step --steps
+ e2e : greedy ids of every probe prompt alone and in groups of --sessions, shipped policy; arms --arms
+ speed : decode wall time of one request and of --sessions requests together, per arm
+Arms: ROW_INV["on"] (exllamav3.util.row_inv) and GROUPS["on"] (exllamav3.generator.row_groups) flipped together in process.
+Run it alone on the GPU. Writes one json per stage into --out.
+"""
+import argparse, hashlib, json, os, sys, time, traceback
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+ap = argparse.ArgumentParser()
+ap.add_argument("-m", "--model", required=True)
+ap.add_argument("--corpus", required=True, help="text file the probe prompts are cut from")
+ap.add_argument("--out", default="out")
+ap.add_argument("--stages", default="ref,rinv,ops,e2e")
+ap.add_argument("--arms", default="off,on")
+ap.add_argument("--sessions", type=int, default=4)
+ap.add_argument("--ctx", type=int, default=24576)
+ap.add_argument("--plen", default="300", help="prompt lengths in tokens, comma list; one probe set per length")
+ap.add_argument("--n-prompts", type=int, default=8)
+ap.add_argument("--tokens", type=int, default=64)
+ap.add_argument("--depths", default="1,3,7")
+ap.add_argument("--steps", type=int, default=3, help="ops: verify forwards compared per run")
+ap.add_argument("--no-vision", action="store_true", default=True)
+ap.add_argument("--policy", default="mix")
+ap.add_argument("--cache-bits", type=int, default=0, choices=(0, 8), help="K/V page format: 0 = fp16, 8 = packed int8")
+ap.add_argument("--planes", default="keep", choices=["keep", "zero", "nan"], help="slots/pf/e2e: what the QSA side planes hold before each run (keep = whatever the previous run left)")
+ap.add_argument("--fixd", default="mix", help="e2e: draft depth policies, comma list of mix or a fixed depth (QWSPEC_FIXD)")
+ap.add_argument("--subops", action="store_true", help="ops: also compare the attention internals (they run once per sequence in a grouped step, so the names do not line up)")
+args = ap.parse_args()
+os.makedirs(args.out, exist_ok=True)
+sys.path.insert(0, HERE)
+sys.path.insert(0, os.path.dirname(HERE))
+sys.path.insert(0, os.path.dirname(os.path.dirname(HERE)))
+
+import serve as S # noqa: E402 (tools/qwen/serve.py: the server's engine and environment)
+
+t_load = time.perf_counter()
+eng = S.QwenEngine(args.model, args.ctx, ndt=7, draft_policy=args.policy, vision=False, cache_bits=args.cache_bits, sessions=args.sessions)
+torch = eng.torch
+from exllamav3.util.row_inv import ROW_INV # noqa: E402
+from exllamav3.generator.row_groups import GROUPS as ROW_GROUPS # noqa: E402
+from exllamav3.modules import block_graph as BG # noqa: E402
+SPEC = eng.draft_model is not None
+
+
+def log(*a):
+ print(time.strftime("%H:%M:%S"), *a, flush=True)
+
+
+def save(name, obj):
+ json.dump(obj, open(os.path.join(args.out, name + ".json"), "w"), indent=1)
+
+
+def sha(t):
+ return hashlib.sha256(json.dumps(t).encode()).hexdigest()[:12]
+
+
+def set_arm(arm):
+ ROW_INV["on"] = ROW_GROUPS["on"] = arm == "on"
+ BG.purge()
+
+
+log("loaded", round(time.perf_counter() - t_load, 1), "s; sessions", args.sessions, "spec", SPEC,
+ "env", {k: v for k, v in os.environ.items() if k.startswith("EXL3_ROW") or k.startswith("QWSPEC")})
+
+corpus = open(args.corpus, errors="replace").read()
+PLENS = [v if v.startswith("mix:") else int(v) for v in args.plen.split(",")] # "mix:300+2300" = job k takes the k-th length, cycled
+
+
+def make_prompts(plen, n):
+ """n prompts of exactly plen tokens (cut from the corpus at different offsets, the first tokens are a chat header)."""
+ head = eng.tokenizer.encode("<|im_start|>user\n", add_bos=False, encode_special_tokens=True)
+ out = []
+ stride = max(1, (len(corpus) - plen * 6) // max(n, 1))
+ for i in range(n):
+ seg = corpus[i * stride: i * stride + plen * 6 + 200]
+ ids = eng.tokenizer.encode(seg, add_bos=False, encode_special_tokens=True)
+ ids = torch.cat((head, ids), dim=-1)[:, :plen].contiguous()
+ assert ids.shape[-1] == plen, (ids.shape, plen)
+ out.append(ids)
+ return out
+
+
+def mkjob(ids, n):
+ return eng.Job(input_ids=ids, max_new_tokens=n, sampler=eng._sampler({"temperature": 0.0}), stop_conditions=[])
+
+
+def run_jobs(gen, items):
+ """items: list of (ids, ntok); all enqueued together. Returns (token lists, wall seconds of the loop)."""
+ jobs = [mkjob(i, n) for i, n in items]
+ for j in jobs:
+ gen.enqueue(j)
+ toks = {id(j): [] for j in jobs}
+ t = time.perf_counter()
+ while gen.num_remaining_jobs():
+ for r in gen.iterate():
+ if r["stage"] == "streaming" and "token_ids" in r:
+ toks[id(r["job"])] += r["token_ids"].flatten().tolist()
+ torch.cuda.synchronize()
+ return [toks[id(j)] for j in jobs], time.perf_counter() - t
+
+
+def rebuild():
+ """eng._build(SPEC), plus the --planes fill of the cache's QSA side planes (they outlive a Generator)."""
+ eng._build(SPEC)
+ if args.planes != "keep":
+ with torch.inference_mode():
+ for layer in eng.cache.layers.values():
+ for nm in ("raw_k", "pooled"):
+ t = getattr(layer, nm, None)
+ if t is not None:
+ t.fill_(float("nan") if args.planes == "nan" else 0.0)
+ torch.cuda.synchronize()
+
+
+def first_diff(a, b):
+ for i, (x, y) in enumerate(zip(a, b)):
+ if x != y:
+ return i
+ return None if len(a) == len(b) else min(len(a), len(b))
+
+
+REF = {} # (plen, i) -> plain greedy continuation
+
+
+def stage_ref():
+ eng._build(False)
+ for plen in PLENS:
+ for i, ids in enumerate(prompts_for(plen, args.n_prompts)):
+ toks, dt = run_jobs(eng.generator, [(ids, args.tokens)])
+ REF[(plen, i)] = toks[0]
+ log("ref", plen, [sha(REF[(plen, i)]) for i in range(args.n_prompts)])
+ save("ref", {f"{k[0]}:{k[1]}": v for k, v in REF.items()})
+
+
+def stage_rinv():
+ res = []
+ for plen in PLENS:
+ if not isinstance(plen, int):
+ continue
+ prompts = make_prompts(plen, min(3, args.n_prompts))
+ for i, ids in enumerate(prompts):
+ ref = REF.get((plen, i))
+ if ref is None:
+ eng._build(False)
+ ref = run_jobs(eng.generator, [(ids, args.tokens)])[0][0]
+ row = {"plen": plen, "prompt": i, "plain": sha(ref)}
+ if SPEC:
+ for name, fx in (("mix", None), ("fixd1", "1"), ("fixd3", "3"), ("fixd7", "7")):
+ if fx is None:
+ os.environ.pop("QWSPEC_FIXD", None)
+ else:
+ os.environ["QWSPEC_FIXD"] = fx
+ eng._build(True)
+ toks = run_jobs(eng.generator, [(ids, args.tokens)])[0][0]
+ row[name] = {"equal": toks == ref, "first_diff": first_diff(toks, ref), "sha": sha(toks)}
+ os.environ.pop("QWSPEC_FIXD", None)
+ eng._build(True)
+ res.append(row)
+ log("rinv", row)
+ save("rinv", res)
+
+
+# ---------------------------------------------------------------------------------------------------- ops
+CAP = {"on": False, "armed": False, "rec": [], "cnt": {}, "gen": None, "kidx": {}, "jr": {}, "cur": 0, "snap": {}}
+
+
+def cap(name, t):
+ if not CAP["on"] or not isinstance(t, torch.Tensor) or torch.cuda.is_current_stream_capturing():
+ return
+ k = CAP["cnt"].get(name, 0)
+ CAP["cnt"][name] = k + 1
+ CAP["rec"].append((f"{name}#{k}", t.detach().clone().cpu()))
+
+
+_hooked = [False]
+
+
+def install_hooks():
+ if _hooked[0]:
+ return
+ _hooked[0] = True
+ for i, top in enumerate(eng.model.modules):
+ for m in top:
+ f0 = m.forward
+
+ def mk(f0, name):
+ def w(*a, **k):
+ o = f0(*a, **k)
+ if CAP["on"]:
+ cap(name, o[0] if isinstance(o, tuple) else o)
+ return o
+ return w
+ m.forward = mk(f0, f"{i}:{m.key}")
+ # the attention core is not a module: record the dense / sparse dispatch output, the projections around it and which path ran
+ from exllamav3.modules import attn as A
+ d0 = A.attn_dispatch
+
+ def d(*a, **k):
+ o = d0(*a, **k)
+ if CAP["on"]:
+ cap("attn_dispatch", o)
+ return o
+ A.attn_dispatch = d
+ for nm in ("project_qkv", "project_o"):
+ def mkp(f0, nm):
+ def w(self, *a, **k):
+ o = f0(self, *a, **k)
+ if CAP["on"]:
+ for i, t in enumerate(o if isinstance(o, tuple) else (o,)):
+ cap(f"{nm}.{i}", t)
+ return o
+ return w
+ setattr(A.Attention, nm, mkp(getattr(A.Attention, nm), nm))
+ b0 = A.Attention.bc_attn_step
+
+ seen = set()
+
+ def bs(self, *a, **k):
+ o = b0(self, *a, **k)
+ if o is None and (self.layer_idx, a[0].shape[0]) not in seen:
+ seen.add((self.layer_idx, a[0].shape[0]))
+ log("bc_attn_step declined: layer", self.layer_idx, "x", tuple(a[0].shape), a[0].dtype, "contiguous", a[0].is_contiguous(),
+ "bc", {kk: (v is not False and v is not None) for kk, v in self.bc_attn.items()})
+ if CAP["on"]:
+ cap("bc_attn_step", torch.tensor([[1.0 if o is not None else 0.0]]) if o is None else o)
+ return o
+ A.Attention.bc_attn_step = bs
+ fwd0 = eng.model.forward
+
+ def fwd(*a, **k):
+ x = a[0] if a else k.get("input_ids")
+ p = k.get("params")
+ # decode / verify forwards of the run (prefill chunks of an MTP engine pass through model.forward too: no history flag)
+ eligible = (CAP["armed"] and p is not None and p.get("recurrent_history") and p.get("block_table") is not None
+ and not torch.cuda.is_current_stream_capturing())
+ arm = False
+ if eligible:
+ g = CAP["gen"]
+ ks_all = [CAP["kidx"][id(j)] for j in g.active_jobs if j.is_prefill_done()]
+ cur = CAP["cur"]
+ ks = ks_all[cur:cur + x.shape[0]]
+ CAP["cur"] = cur + x.shape[0] if cur + x.shape[0] < len(ks_all) else 0
+ rounds = [CAP["jr"].get(kk, 0) for kk in ks]
+ for kk in ks:
+ CAP["jr"][kk] = CAP["jr"].get(kk, 0) + 1
+ arm = any(r < args.steps for r in rounds)
+ if arm:
+ CAP["on"] = True
+ CAP["rec"] = []
+ CAP["cnt"] = {}
+ ids = x.clone().cpu()
+ seqlens = p["cache_seqlens"].clone().cpu().tolist()
+ verify = bool(p.get("dflash_verify"))
+ try:
+ r = fwd0(*a, **k)
+ finally:
+ if arm:
+ CAP["on"] = False
+ if arm:
+ lg = (r["logits"] if isinstance(r, dict) else r).float().reshape(x.shape[0] * x.shape[-1], -1).cpu()
+ rec = merge_rec(CAP["rec"])
+ for kk_local, (kk, rd) in enumerate(zip(ks, rounds)):
+ if rd < args.steps:
+ CAP["snap"][(kk, rd)] = dict(rec=list(rec), lg=lg, ids=ids, seqlens=seqlens, kk=kk_local, nb=len(ks), verify=verify)
+ return r
+ eng.model.forward = fwd
+
+
+def merge_rec(rec):
+ """A module the per-sequence attention calls once per sequence is recorded as name#0, name#1, ...: stack those
+ one-sequence outputs back into the batched tensor, as a batched forward would have produced it."""
+ by = {}
+ for nm, t in rec:
+ by.setdefault(nm.rsplit("#", 1)[0], []).append(t)
+ out = []
+ for base, ts in by.items():
+ if len(ts) > 1 and all(t.dim() >= 1 and t.shape[0] == 1 and t.shape == ts[0].shape for t in ts):
+ ts = [torch.cat(ts, dim=0)]
+ out += [(f"{base}#{i}", t) for i, t in enumerate(ts)]
+ return out
+
+
+def make_oracle_gen(depth, specs):
+ """A Generator whose n-gram slot answers with the plain continuation (some positions corrupted on purpose)."""
+ G = eng.Generator
+ val = G.__dict__["_validate_ngram_drafting_support"]
+ G._validate_ngram_drafting_support = staticmethod(lambda: None)
+ try:
+ g = G(model=eng.model, cache=eng.cache, tokenizer=eng.tokenizer, ngram_match_min=2, num_draft_tokens=depth)
+ finally:
+ G._validate_ngram_drafting_support = val
+
+ def oracle(results):
+ rows = []
+ for j in g.active_jobs:
+ if not j.is_prefill_done():
+ continue
+ ref, k = specs[id(j)]
+ n = j.new_tokens
+ d = []
+ for pos in range(depth):
+ t = ref[n + pos] if n + pos < len(ref) else 0
+ if (n * 7 + pos * 3 + k) % 11 == 0:
+ t = (t + 1 + pos) % eng.vocab_size
+ d.append(t)
+ rows.append(d)
+ if not rows:
+ return None
+ return torch.tensor(rows, dtype=torch.long)
+ g.iterate_ngram_gen = oracle
+ return g
+
+
+def run_capture(prompts_refs, depth, kids=None):
+ """Decode the jobs together (or alone) with oracle drafts; returns {(job, round): snapshot of that verify forward}.
+ kids: the job numbers (default 0..n-1); the same number gives the same corrupted draft positions alone and in a group."""
+ specs = {}
+ g = make_oracle_gen(depth, specs)
+ jobs = []
+ CAP["gen"], CAP["kidx"], CAP["jr"], CAP["cur"], CAP["snap"] = g, {}, {}, 0, {}
+ for k, (ids, ref) in zip(kids if kids is not None else range(len(prompts_refs)), prompts_refs):
+ j = mkjob(ids, max(8, args.steps * (depth + 1) + 2))
+ specs[id(j)] = (ref, k)
+ CAP["kidx"][id(j)] = k
+ jobs.append(j)
+ CAP["armed"] = True
+ for j in jobs:
+ g.enqueue(j)
+ while g.num_remaining_jobs():
+ for _ in g.iterate():
+ pass
+ CAP["armed"] = False
+ return dict(CAP["snap"])
+
+
+def pick(a, b, idx, nb):
+ """slice of the batched tensor b (nb jobs) that belongs to job idx of the solo tensor a"""
+ if a.shape == b.shape:
+ return b if nb == 1 else None
+ n = a.shape[0]
+ if b.shape[1:] == a.shape[1:] and b.shape[0] == nb * n:
+ return b[idx * n:(idx + 1) * n]
+ return None
+
+
+def compare(solo, batched, idx, nb, rows):
+ ds = dict(solo)
+ out = []
+ missing = 0
+ for name, b in batched:
+ if ":" not in name and not args.subops:
+ continue
+ a = ds.get(name)
+ if a is None:
+ missing += 1
+ continue
+ b0 = pick(a, b, idx, nb)
+ if b0 is None:
+ out.append([name, "shape", list(a.shape), list(b.shape)])
+ continue
+ if not torch.equal(a, b0):
+ d = float((a.float() - b0.float()).abs().max()) if a.dtype.is_floating_point else -1.0
+ nrow = None
+ if a.dim() >= 2 and a.shape[0] == 1:
+ af, bf = a.reshape(rows, -1), b0.reshape(rows, -1)
+ nrow = [bool(torch.equal(af[r], bf[r])) for r in range(rows)] if af.shape[0] == rows else None
+ out.append([name, "diff", d, nrow])
+ return out, missing
+
+
+def prompts_for(spec, n):
+ """n prompts for a --plen entry: one length, or mix:a+b (job k takes length a, b, a, ... so neighbours differ in block-table width)"""
+ if isinstance(spec, int):
+ return make_prompts(spec, n)
+ lens = [int(v) for v in spec[4:].split("+")]
+ sets = {m: make_prompts(m, n) for m in set(lens)}
+ return [sets[lens[k % len(lens)]][k] for k in range(n)]
+
+
+def stage_ops():
+ install_hooks()
+ res = {}
+ for plen in PLENS:
+ prompts = prompts_for(plen, args.sessions)
+ refs = []
+ eng._build(False)
+ for i, ids in enumerate(prompts):
+ refs.append(REF.get((plen, i)) or run_jobs(eng.generator, [(ids, args.tokens)])[0][0])
+ for depth in [int(v) for v in args.depths.split(",")]:
+ rows = depth + 1
+ for arm in args.arms.split(","):
+ set_arm(arm)
+ solo = {}
+ for k in range(args.sessions):
+ for key, v in run_capture([(prompts[k], refs[k])], depth, [k]).items():
+ solo[(k, key[1])] = v
+ batched = run_capture(list(zip(prompts, refs)), depth)
+ for (k, rd) in sorted(batched):
+ b = batched[(k, rd)]
+ if (k, rd) not in solo:
+ continue
+ s0 = solo[(k, rd)]
+ nb, kk = b["nb"], b["kk"]
+ same_in = bool(torch.equal(b["ids"][kk:kk + 1], s0["ids"])) and b["seqlens"][kk] == s0["seqlens"][0]
+ diffs, missing = compare(s0["rec"], b["rec"], kk, nb, rows)
+ lrow = s0["lg"].reshape(rows, -1)
+ prow = b["lg"].reshape(nb * rows, -1)[kk * rows:(kk + 1) * rows]
+ ent = {"plen": plen, "depth": depth, "rows_total": args.sessions * rows, "fwd_rows": nb * rows, "arm": arm,
+ "round": rd, "job": k, "inputs_equal": same_in, "verify_flag": [s0["verify"], b["verify"]],
+ "logits_rows_equal": [bool(torch.equal(lrow[r], prow[r])) for r in range(rows)],
+ "n_diff_ops": len(diffs), "n_unmatched": missing, "first_10": diffs[:10],
+ "first_block_diff": next((d for d in diffs if ":" in d[0] and "." not in d[0].split(":", 1)[1].split("#")[0]), None)}
+ res.setdefault(f"{plen}/{depth}/{arm}", []).append(ent)
+ log("ops", plen, "d", depth, arm, "round", rd, "job", k, "fwd_rows", nb * rows, "inputs", same_in, "logits",
+ "".join("1" if v else "0" for v in ent["logits_rows_equal"]), "n_diff", len(diffs), "first", diffs[:1])
+ save("ops", res)
+ eng._build(SPEC)
+
+
+# ---------------------------------------------------------------------------------------------------- e2e
+def stage_e2e():
+ res = []
+ for plen in PLENS:
+ prompts = prompts_for(plen, args.n_prompts)
+ for fd in args.fixd.split(","):
+ if fd == "mix":
+ os.environ.pop("QWSPEC_FIXD", None)
+ else:
+ os.environ["QWSPEC_FIXD"] = fd
+ for arm in args.arms.split(","):
+ set_arm(arm)
+ rebuild()
+ solo = [run_jobs(eng.generator, [(ids, args.tokens)])[0][0] for ids in prompts]
+ rebuild() # a fresh prompt cache: the parallel phase prefills cold, as the solo phase did
+ par = []
+ for g0 in range(0, len(prompts), args.sessions):
+ grp = prompts[g0:g0 + args.sessions]
+ par += run_jobs(eng.generator, [(ids, args.tokens) for ids in grp])[0]
+ eq = [p == s for p, s in zip(par, solo)]
+ row = {"plen": plen, "fixd": fd, "arm": arm, "sessions": args.sessions, "equal": eq, "n_equal": sum(eq), "n": len(eq),
+ "first_diff": [first_diff(p, s) for p, s in zip(par, solo)], "solo": [sha(s) for s in solo]}
+ res.append(row)
+ log("e2e", row)
+ os.environ.pop("QWSPEC_FIXD", None)
+ save("e2e", res)
+
+
+# ---------------------------------------------------------------------------------------------------- slots
+def stage_slots():
+ """Is a difference tied to the prompt or to the slot of the group? Each prompt alone (cold), then the same prompts
+ as one group in several orders (cold each time)."""
+ res = []
+ for plen in PLENS:
+ prompts = prompts_for(plen, args.sessions)
+ for arm in args.arms.split(","):
+ set_arm(arm)
+ rebuild()
+ solo = []
+ for ids in prompts:
+ rebuild()
+ solo.append(run_jobs(eng.generator, [(ids, args.tokens)])[0][0])
+ again = []
+ for ids in prompts:
+ rebuild()
+ again.append(run_jobs(eng.generator, [(ids, args.tokens)])[0][0])
+ row = {"plen": plen, "arm": arm, "solo_repeat_equal": [a == b for a, b in zip(solo, again)], "perms": {}}
+ n = len(prompts)
+ for perm in ([*range(n)], [*reversed(range(n))], [*range(1, n), 0], [*range(2, n), *range(2)]):
+ rebuild()
+ par = run_jobs(eng.generator, [(prompts[i], args.tokens) for i in perm])[0]
+ row["perms"][",".join(map(str, perm))] = [first_diff(par[slot], solo[i]) for slot, i in enumerate(perm)]
+ res.append(row)
+ log("slots", row)
+ save("slots", res)
+
+
+# ---------------------------------------------------------------------------------------------------- pf
+def stage_pf():
+ """Every model forward of a cold run, per prompt: input hash, cache length, rows, output hash. Alone vs as a group."""
+ calls = []
+ fwd0 = eng.model.forward
+
+ def fwd(*a, **k):
+ x = a[0] if a else k.get("input_ids")
+ p = k.get("params") or {}
+ r = fwd0(*a, **k)
+ o = r["logits"] if isinstance(r, dict) else r
+ h = hashlib.sha256(o.detach().cpu().float().numpy().tobytes()).hexdigest()[:8] if isinstance(o, torch.Tensor) else None
+ calls.append((hashlib.sha256(x.cpu().numpy().tobytes()).hexdigest()[:8], tuple(x.shape), p["cache_seqlens"].cpu().tolist()
+ if p.get("cache_seqlens") is not None else None, bool(p.get("recurrent_history")), h))
+ return r
+ eng.model.forward = fwd
+ for plen in PLENS:
+ prompts = prompts_for(plen, args.sessions)
+ for arm in args.arms.split(","):
+ set_arm(arm)
+ solo = []
+ for ids in prompts:
+ rebuild()
+ del calls[:]
+ toks = run_jobs(eng.generator, [(ids, args.tokens)])[0][0]
+ solo.append((toks, [c for c in calls if not c[3]]))
+ rebuild()
+ del calls[:]
+ par = run_jobs(eng.generator, [(i, args.tokens) for i in prompts])[0]
+ pcalls = [c for c in calls if not c[3]]
+ for slot, ids in enumerate(prompts):
+ stoks, scalls = solo[slot]
+ log("pf", plen, arm, "slot", slot, "tokens equal", par[slot] == stoks, "first_diff", first_diff(par[slot], stoks))
+ log("pf solo prefill forwards", scalls[:6])
+ log("pf group forwards (all)", pcalls[:12])
+ eng.model.forward = fwd0
+
+
+# ---------------------------------------------------------------------------------------------------- hz
+def stage_hz():
+ """Where is the host/device race of a group of cold prefills? Same group as the slots stage, with a device sync at one place."""
+ mode = {"m": "none"}
+
+ def sync():
+ torch.cuda.synchronize()
+
+ def wrap(obj, name, when):
+ f0 = getattr(obj, name)
+
+ def w(*a, **k):
+ if mode["m"] == when + "_pre":
+ sync()
+ r = f0(*a, **k)
+ if mode["m"] == when + "_post":
+ sync()
+ return r
+ setattr(obj, name, w)
+ wrap(eng.model, "forward", "fwd")
+ wrap(eng.model, "prefill", "mprefill")
+ if eng.draft_model is not None:
+ wrap(eng.draft_model, "prefill", "dprefill")
+ J = eng.Job
+ p0 = J.prefill
+
+ def jp(self, *a, **k):
+ if mode["m"] == "job_pre":
+ sync()
+ r = p0(self, *a, **k)
+ if mode["m"] == "job_post":
+ sync()
+ return r
+ J.prefill = jp
+ for plen in PLENS:
+ prompts = prompts_for(plen, args.sessions)
+ for arm in args.arms.split(","):
+ set_arm(arm)
+ mode["m"] = "none"
+ solo = []
+ for ids in prompts:
+ rebuild()
+ solo.append(run_jobs(eng.generator, [(ids, args.tokens)])[0][0])
+ for m in ["none", "job_post", "job_pre", "fwd_post", "fwd_pre", "mprefill_post", "dprefill_post", "dprefill_pre"]:
+ mode["m"] = m
+ rebuild()
+ par = run_jobs(eng.generator, [(i, args.tokens) for i in prompts])[0]
+ log("hz", plen, arm, m, [first_diff(a, b) for a, b in zip(par, solo)])
+ mode["m"] = "none"
+ J.prefill = p0
+
+
+# ---------------------------------------------------------------------------------------------------- speed
+def stage_speed():
+ res = []
+ for plen in PLENS:
+ prompts = prompts_for(plen, args.sessions)
+ for arm in args.arms.split(","):
+ set_arm(arm)
+ eng._build(SPEC)
+ run_jobs(eng.generator, [(prompts[0], 8)])
+ ntok = args.tokens
+ solo_t = []
+ for _ in range(2):
+ toks, dt = run_jobs(eng.generator, [(prompts[0], ntok)])
+ solo_t.append((len(toks[0]), dt))
+ par_t = []
+ for _ in range(2):
+ toks, dt = run_jobs(eng.generator, [(p, ntok) for p in prompts])
+ par_t.append((sum(len(t) for t in toks), dt))
+ res.append({"plen": plen, "arm": arm, "solo": solo_t, "par": par_t})
+ log("speed", res[-1])
+ save("speed", res)
+
+
+for st in args.stages.split(","):
+ log("stage", st)
+ try:
+ {"ref": stage_ref, "rinv": stage_rinv, "ops": stage_ops, "e2e": stage_e2e, "slots": stage_slots, "pf": stage_pf, "hz": stage_hz, "speed": stage_speed}[st]()
+ except Exception:
+ traceback.print_exc()
+ log("stage failed", st)
+log("done")
diff --git a/tools/qwen/fixtures/loopguard/legit/hexagon_kyojin.html b/tools/qwen/fixtures/loopguard/legit/hexagon_kyojin.html
new file mode 100644
index 0000000..a4b15f9
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/legit/hexagon_kyojin.html
@@ -0,0 +1,427 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1.0" />
+<title>Bouncing Balls in a Spinning Hexagon</title>
+<style>
+ :root {
+ --bg: #0b0f1a;
+ --panel: #131a2b;
+ --accent: #5eead4;
+ --text: #e6edf3;
+ --muted: #8b98b8;
+ }
+ * { box-sizing: border-box; }
+ html, body {
+ margin: 0;
+ height: 100%;
+ background: radial-gradient(1200px 800px at 50% -10%, #16203a 0%, var(--bg) 60%);
+ color: var(--text);
+ font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
+ overflow: hidden;
+ }
+ .app {
+ display: grid;
+ grid-template-rows: auto 1fr auto;
+ height: 100%;
+ }
+ header {
+ padding: 14px 20px 6px;
+ display: flex;
+ align-items: baseline;
+ gap: 12px;
+ flex-wrap: wrap;
+ }
+ header h1 {
+ font-size: 18px;
+ margin: 0;
+ letter-spacing: 0.3px;
+ font-weight: 650;
+ }
+ header p {
+ margin: 0;
+ color: var(--muted);
+ font-size: 13px;
+ }
+ .stage {
+ position: relative;
+ display: grid;
+ place-items: center;
+ min-height: 0;
+ }
+ canvas {
+ display: block;
+ border-radius: 16px;
+ background: linear-gradient(180deg, rgba(255,255,255,0.02), rgba(0,0,0,0.15));
+ box-shadow: 0 20px 60px rgba(0,0,0,0.45), inset 0 0 0 1px rgba(255,255,255,0.04);
+ }
+ .hud {
+ position: absolute;
+ top: 16px;
+ left: 16px;
+ display: flex;
+ gap: 8px;
+ flex-wrap: wrap;
+ pointer-events: none;
+ }
+ .chip {
+ background: rgba(19,26,43,0.7);
+ border: 1px solid rgba(255,255,255,0.08);
+ color: var(--text);
+ padding: 6px 10px;
+ border-radius: 999px;
+ font-size: 12px;
+ backdrop-filter: blur(6px);
+ }
+ .chip b { color: var(--accent); font-variant-numeric: tabular-nums; }
+ footer {
+ padding: 10px 16px 18px;
+ display: flex;
+ gap: 18px;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: center;
+ background: linear-gradient(0deg, rgba(0,0,0,0.25), transparent);
+ }
+ .control {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 13px;
+ color: var(--muted);
+ }
+ .control input[type="range"] { accent-color: var(--accent); width: 120px; }
+ .control input[type="checkbox"] { accent-color: var(--accent); width: 16px; height: 16px; }
+ button {
+ background: var(--accent);
+ color: #06231f;
+ border: none;
+ padding: 8px 14px;
+ border-radius: 10px;
+ font-weight: 650;
+ cursor: pointer;
+ font-size: 13px;
+ transition: transform .08s ease, filter .15s ease;
+ }
+ button:hover { filter: brightness(1.08); }
+ button:active { transform: translateY(1px); }
+ button.ghost {
+ background: transparent;
+ color: var(--text);
+ border: 1px solid rgba(255,255,255,0.18);
+ }
+</style>
+</head>
+<body>
+<div class="app">
+ <header>
+ <h1>Bouncing Balls in a Spinning Hexagon</h1>
+ <p>Real-time physics · elastic collisions · rotating walls</p>
+ </header>
+
+ <div class="stage">
+ <canvas id="c"></canvas>
+ <div class="hud">
+ <span class="chip">FPS <b id="fps">–</b></span>
+ <span class="chip">Balls <b id="count">10</b></span>
+ <span class="chip">Spin <b id="spinVal">0.6</b> rad/s</span>
+ </div>
+ </div>
+
+ <footer>
+ <button id="reset">Reset</button>
+ <button id="pause" class="ghost">Pause</button>
+ <div class="control">
+ <label for="spin">Spin</label>
+ <input id="spin" type="range" min="-2" max="2" step="0.05" value="0.6" />
+ </div>
+ <div class="control">
+ <label for="grav">Gravity</label>
+ <input id="grav" type="range" min="0" max="1200" step="10" value="500" />
+ </div>
+ <div class="control">
+ <label for="rest">Bounciness</label>
+ <input id="rest" type="range" min="0.5" max="1" step="0.01" value="0.92" />
+ </div>
+ <div class="control">
+ <label for="trails">Trails</label>
+ <input id="trails" type="checkbox" checked />
+ </div>
+ </footer>
+</div>
+
+<script>
+(() => {
+ const canvas = document.getElementById('c');
+ const ctx = canvas.getContext('2d');
+
+ // ---- Config / state ----
+ const cfg = {
+ spin: 0.6, // rad/s
+ gravity: 500, // px/s^2
+ restitution: 0.92, // wall bounciness
+ ballRestitution: 0.95,
+ trails: true,
+ paused: false,
+ count: 10,
+ };
+
+ const hex = {
+ cx: 0, cy: 0,
+ radius: 240, // circumradius (center -> vertex)
+ angle: 0, // current rotation
+ };
+
+ let balls = [];
+ const palette = [
+ '#f87171','#fb923c','#fbbf24','#a3e635','#34d399',
+ '#22d3ee','#60a5fa','#a78bfa','#f472b6','#e879f9',
+ ];
+
+ // ---- Sizing ----
+ let dpr = Math.max(1, Math.min(2, window.devicePixelRatio || 1));
+ function resize() {
+ const stage = canvas.parentElement;
+ const rect = stage.getBoundingClientRect();
+ const size = Math.max(280, Math.min(rect.width, rect.height) - 24);
+ canvas.style.width = size + 'px';
+ canvas.style.height = size + 'px';
+ canvas.width = Math.round(size * dpr);
+ canvas.height = Math.round(size * dpr);
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+ hex.cx = size / 2;
+ hex.cy = size / 2;
+ hex.radius = size * 0.42;
+ }
+
+ // ---- Hexagon geometry ----
+ function hexVertices() {
+ const v = [];
+ for (let i = 0; i < 6; i++) {
+ const a = hex.angle + i * Math.PI / 3;
+ v.push({
+ x: hex.cx + hex.radius * Math.cos(a),
+ y: hex.cy + hex.radius * Math.sin(a),
+ });
+ }
+ return v;
+ }
+
+ // ---- Ball creation ----
+ function makeBall(i) {
+ const r = 10 + Math.random() * 12;
+ // spawn inside the inscribed circle so it never starts outside a wall
+ const maxR = hex.radius * Math.cos(Math.PI / 6) - r - 4;
+ const a = Math.random() * Math.PI * 2;
+ const d = Math.random() * maxR;
+ return {
+ x: hex.cx + Math.cos(a) * d,
+ y: hex.cy + Math.sin(a) * d,
+ vx: (Math.random() * 2 - 1) * 260,
+ vy: (Math.random() * 2 - 1) * 260,
+ r,
+ color: palette[i % palette.length],
+ };
+ }
+
+ function reset() {
+ balls = [];
+ for (let i = 0; i < cfg.count; i++) balls.push(makeBall(i));
+ }
+
+ // ---- Physics ----
+ function collideWalls(b, dt) {
+ const verts = hexVertices();
+ for (let i = 0; i < 6; i++) {
+ const a = verts[i];
+ const c = verts[(i + 1) % 6];
+ const ex = c.x - a.x, ey = c.y - a.y;
+ const len = Math.hypot(ex, ey) || 1;
+ // inward normal (hexagon center is inside)
+ let nx = -ey / len, ny = ex / len;
+ const midx = (a.x + c.x) / 2, midy = (a.y + c.y) / 2;
+ if ((hex.cx - midx) * nx + (hex.cy - midy) * ny < 0) { nx = -nx; ny = -ny; }
+
+ // signed distance from ball center to wall plane (positive = inside)
+ const dist = (b.x - a.x) * nx + (b.y - a.y) * ny;
+ if (dist < b.r) {
+ // velocity of the wall point due to rotation (v = omega x r)
+ const rx = b.x - hex.cx, ry = b.y - hex.cy;
+ const wvx = -cfg.spin * ry;
+ const wvy = cfg.spin * rx;
+
+ // relative velocity
+ let rvx = b.vx - wvx;
+ let rvy = b.vy - wvy;
+ const vn = rvx * nx + rvy * ny; // component along normal
+
+ if (vn < 0) {
+ // reflect relative velocity, then add wall velocity back
+ const j = -(1 + cfg.restitution) * vn;
+ rvx += j * nx;
+ rvy += j * ny;
+ b.vx = rvx + wvx;
+ b.vy = rvy + wvy;
+ }
+ // push out of penetration
+ const pen = b.r - dist;
+ b.x += nx * pen;
+ b.y += ny * pen;
+ }
+ }
+ }
+
+ function collideBalls() {
+ for (let i = 0; i < balls.length; i++) {
+ for (let j = i + 1; j < balls.length; j++) {
+ const a = balls[i], b = balls[j];
+ let dx = b.x - a.x, dy = b.y - a.y;
+ let d = Math.hypot(dx, dy);
+ const min = a.r + b.r;
+ if (d === 0) { d = 0.01; dx = 0.01; }
+ if (d < min) {
+ const nx = dx / d, ny = dy / d;
+ const overlap = (min - d) / 2;
+ a.x -= nx * overlap; a.y -= ny * overlap;
+ b.x += nx * overlap; b.y += ny * overlap;
+
+ const rvx = b.vx - a.vx, rvy = b.vy - a.vy;
+ const vn = rvx * nx + rvy * ny;
+ if (vn < 0) {
+ const ma = a.r * a.r, mb = b.r * b.r; // mass ~ area
+ const jImp = -(1 + cfg.ballRestitution) * vn / (1 / ma + 1 / mb);
+ const ix = jImp * nx, iy = jImp * ny;
+ a.vx -= ix / ma; a.vy -= iy / ma;
+ b.vx += ix / mb; b.vy += iy / mb;
+ }
+ }
+ }
+ }
+ }
+
+ function step(dt) {
+ hex.angle += cfg.spin * dt;
+ for (const b of balls) {
+ b.vy += cfg.gravity * dt;
+ b.x += b.vx * dt;
+ b.y += b.vy * dt;
+ collideWalls(b, dt);
+ }
+ collideBalls();
+ // safety: keep strays inside
+ for (const b of balls) {
+ const dx = b.x - hex.cx, dy = b.y - hex.cy;
+ const d = Math.hypot(dx, dy);
+ const maxD = hex.radius * Math.cos(Math.PI / 6) - b.r;
+ if (d > maxD) {
+ const nx = dx / (d || 1), ny = dy / (d || 1);
+ b.x = hex.cx + nx * maxD;
+ b.y = hex.cy + ny * maxD;
+ }
+ }
+ }
+
+ // ---- Render ----
+ function draw() {
+ const w = canvas.clientWidth, h = canvas.clientHeight;
+ if (cfg.trails) {
+ ctx.fillStyle = 'rgba(11,15,26,0.22)';
+ ctx.fillRect(0, 0, w, h);
+ } else {
+ ctx.clearRect(0, 0, w, h);
+ }
+
+ // hexagon
+ const v = hexVertices();
+ ctx.beginPath();
+ ctx.moveTo(v[0].x, v[0].y);
+ for (let i = 1; i < 6; i++) ctx.lineTo(v[i].x, v[i].y);
+ ctx.closePath();
+ ctx.lineWidth = 3;
+ ctx.strokeStyle = 'rgba(94,234,212,0.9)';
+ ctx.shadowColor = 'rgba(94,234,212,0.5)';
+ ctx.shadowBlur = 18;
+ ctx.stroke();
+ ctx.shadowBlur = 0;
+
+ // balls
+ for (const b of balls) {
+ const g = ctx.createRadialGradient(
+ b.x - b.r * 0.35, b.y - b.r * 0.35, b.r * 0.15,
+ b.x, b.y, b.r
+ );
+ g.addColorStop(0, '#ffffff');
+ g.addColorStop(0.25, b.color);
+ g.addColorStop(1, shade(b.color, -0.35));
+ ctx.beginPath();
+ ctx.arc(b.x, b.y, b.r, 0, Math.PI * 2);
+ ctx.fillStyle = g;
+ ctx.shadowColor = b.color;
+ ctx.shadowBlur = 12;
+ ctx.fill();
+ ctx.shadowBlur = 0;
+ }
+ }
+
+ function shade(hex, amt) {
+ const c = hex.replace('#','');
+ const num = parseInt(c, 16);
+ let r = (num >> 16) & 255, g = (num >> 8) & 255, bl = num & 255;
+ r = Math.max(0, Math.min(255, Math.round(r + 255 * amt)));
+ g = Math.max(0, Math.min(255, Math.round(g + 255 * amt)));
+ bl = Math.max(0, Math.min(255, Math.round(bl + 255 * amt)));
+ return `rgb(${r},${g},${bl})`;
+ }
+
+ // ---- Loop ----
+ let last = performance.now();
+ let fpsAcc = 0, fpsCount = 0, fpsTimer = 0;
+ const fpsEl = document.getElementById('fps');
+
+ function frame(now) {
+ let dt = (now - last) / 1000;
+ last = now;
+ if (dt > 0.05) dt = 0.05; // clamp big gaps
+
+ if (!cfg.paused) {
+ // substeps for stable collisions
+ const sub = 4;
+ for (let s = 0; s < sub; s++) step(dt / sub);
+ }
+ draw();
+
+ // fps
+ fpsAcc += dt; fpsCount++; fpsTimer += dt;
+ if (fpsTimer >= 0.5) {
+ fpsEl.textContent = Math.round(fpsCount / fpsAcc);
+ fpsAcc = 0; fpsCount = 0; fpsTimer = 0;
+ }
+ requestAnimationFrame(frame);
+ }
+
+ // ---- Controls ----
+ const $ = id => document.getElementById(id);
+ $('spin').addEventListener('input', e => {
+ cfg.spin = parseFloat(e.target.value);
+ $('spinVal').textContent = cfg.spin.toFixed(2);
+ });
+ $('grav').addEventListener('input', e => cfg.gravity = parseFloat(e.target.value));
+ $('rest').addEventListener('input', e => cfg.restitution = parseFloat(e.target.value));
+ $('trails').addEventListener('change', e => cfg.trails = e.target.checked);
+ $('reset').addEventListener('click', reset);
+ $('pause').addEventListener('click', e => {
+ cfg.paused = !cfg.paused;
+ e.target.textContent = cfg.paused ? 'Play' : 'Pause';
+ });
+
+ window.addEventListener('resize', () => { resize(); });
+
+ // ---- Init ----
+ resize();
+ reset();
+ requestAnimationFrame(frame);
+})();
+</script>
+</body>
+</html>
diff --git a/tools/qwen/fixtures/loopguard/legit/pagoda_kyojin_original.txt b/tools/qwen/fixtures/loopguard/legit/pagoda_kyojin_original.txt
new file mode 100644
index 0000000..a2eb429
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/legit/pagoda_kyojin_original.txt
@@ -0,0 +1,186 @@
+Here's a complete, self-contained voxel scene — a five-tier pagoda in a Japanese garden with cherry blossoms, a koi pond, a torii gate, stone lanterns, a bridge, and a drifting-petal sky. It uses Three.js (via CDN) and renders procedurally from a hand-authored voxel blueprint. Save it as an `.html` file and open it.
+
+```html
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8">
+<meta name="viewport" content="width=device-width, initial-scale=1.0">
+<title>Pagoda Garden — Voxel Scene</title>
+<link rel="preconnect" href="https://fonts.googleapis.com">
+<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+<link href="https://fonts.googleapis.com/css2?family=Shippori+Mincho:wght@500;700;800&family=Zen+Kaku+Gothic+New:wght@400;500;700&display=swap" rel="stylesheet">
+<style>
+ :root{
+ --ink:#241a17; --paper:#f6efe2; --vermilion:#c8402f; --gold:#c99a3f;
+ --moss:#5f7a4a; --mist:rgba(246,239,226,.72);
+ }
+ *{box-sizing:border-box;margin:0;padding:0}
+ html,body{height:100%;overflow:hidden;background:#cfe0e6}
+ body{font-family:"Zen Kaku Gothic New",system-ui,sans-serif;color:var(--ink)}
+ canvas{display:block;position:fixed;inset:0;z-index:0}
+
+ /* ---- HUD ---- */
+ .hud{position:fixed;inset:0;z-index:10;pointer-events:none}
+ .hud > *{pointer-events:auto}
+
+ .title{position:absolute;top:clamp(18px,3.4vw,44px);left:clamp(18px,3.4vw,48px);max-width:min(46ch,60vw)}
+ .kicker{font-size:12px;letter-spacing:.42em;text-transform:uppercase;color:var(--vermilion);font-weight:700;
+ display:flex;align-items:center;gap:.7em}
+ .kicker::before{content:"";width:34px;height:2px;background:var(--vermilion);display:inline-block}
+ .title h1{font-family:"Shippori Mincho",serif;font-weight:800;line-height:.92;
+ font-size:clamp(46px,8.4vw,104px);letter-spacing:-.01em;margin:.12em 0 .1em;
+ color:var(--ink);text-shadow:0 2px 0 rgba(255,255,255,.35)}
+ .title h1 .jp{display:block;font-size:.42em;letter-spacing:.34em;color:var(--gold);font-weight:700;margin-top:.35em}
+ .title p{font-size:clamp(13px,1.5vw,16px);line-height:1.55;color:#4a3b34;max-width:34ch;
+ border-left:2px solid rgba(200,64,47,.4);padding-left:14px;margin-top:14px}
+
+ .panel{position:absolute;top:clamp(18px,3.4vw,44px);right:clamp(18px,3.4vw,48px);width:236px;
+ background:var(--mist);backdrop-filter:blur(9px);-webkit-backdrop-filter:blur(9px);
+ border:1px solid rgba(36,26,23,.14);border-radius:4px;padding:16px 16px 18px;
+ box-shadow:0 18px 40px -22px rgba(36,26,23,.6)}
+ .panel h2{font-family:"Shippori Mincho",serif;font-size:15px;letter-spacing:.16em;text-transform:uppercase;
+ color:var(--ink);margin-bottom:14px;display:flex;align-items:center;gap:8px}
+ .panel h2::after{content:"";flex:1;height:1px;background:rgba(36,26,23,.2)}
+ .row{display:flex;align-items:center;justify-content:space-between;gap:10px;margin:11px 0;font-size:13px}
+ .row label{color:#4a3b34;font-weight:500}
+ .seg{display:flex;background:rgba(36,26,23,.08);border-radius:3px;padding:2px}
+ .seg button{border:0;background:transparent;font:inherit;font-size:12px;padding:5px 10px;border-radius:2px;
+ cursor:pointer;color:#5a4a42;transition:.18s}
+ .seg button.on{background:var(--ink);color:var(--paper)}
+ .seg button:not(.on):hover{color:var(--vermilion)}
+ .sw{width:44px;height:24px;border-radius:3px;border:1px solid rgba(36,26,23,.2);cursor:pointer;position:relative;transition:.18s}
+ .sw::after{content:"";position:absolute;top:2px;left:2px;width:18px;height:18px;border-radius:2px;background:#fff;transition:.18s}
+ .sw.on{background:var(--vermilion)}
+ .sw.on::after{left:22px}
+ .btn{width:100%;margin-top:14px;border:1px solid var(--ink);background:transparent;color:var(--ink);
+ font:inherit;font-weight:700;font-size:12px;letter-spacing:.14em;text-transform:uppercase;padding:9px;border-radius:3px;
+ cursor:pointer;transition:.2s}
+ .btn:hover{background:var(--ink);color:var(--paper)}
+ .btn.on{background:var(--vermilion);border-color:var(--vermilion);color:#fff}
+
+ .hint{position:absolute;left:clamp(18px,3.4vw,48px);bottom:clamp(16px,3vw,34px);font-size:12px;
+ letter-spacing:.06em;color:#4a3b34;background:var(--mist);backdrop-filter:blur(6px);
+ padding:8px 14px;border-radius:3px;border:1px solid rgba(36,26,23,.12)}
+ .hint b{color:var(--vermilion)}
+
+ .credit{position:absolute;right:clamp(18px,3.4vw,48px);bottom:clamp(16px,3vw,34px);font-size:11px;
+ letter-spacing:.18em;text-transform:uppercase;color:#6a5a52}
+
+ /* ---- Loader ---- */
+ #loader{position:fixed;inset:0;z-index:50;background:linear-gradient(160deg,#f6efe2,#e7d9c4);
+ display:flex;flex-direction:column;align-items:center;justify-content:center;gap:22px;transition:opacity .8s ease}
+ #loader.hide{opacity:0;pointer-events:none}
+ .mark{font-family:"Shippori Mincho",serif;font-size:64px;color:var(--vermilion);animation:spin 3.4s linear infinite}
+ @keyframes spin{to{transform:rotate(360deg)}}
+ .lbar{width:220px;height:3px;background:rgba(36,26,23,.14);border-radius:2px;overflow:hidden}
+ .lbar i{display:block;height:100%;width:40%;background:var(--vermilion);animation:load 1.1s ease-in-out infinite}
+ @keyframes load{0%{transform:translateX(-120%)}100%{transform:translateX(320%)}}
+ .ltxt{font-size:12px;letter-spacing:.34em;text-transform:uppercase;color:#6a5a52}
+
+ @media (max-width:720px){
+ .panel{top:auto;bottom:70px;left:12px;right:12px;width:auto}
+ .title{max-width:80vw}
+ .credit{display:none}
+ }
+</style>
+</head>
+<body>
+<div id="loader"><div class="mark">塔</div><div class="lbar"><i></i></div><div class="ltxt">Assembling the garden</div></div>
+
+<div class="hud">
+ <div class="title">
+ <div class="kicker">Voxel Garden · 五重塔</div>
+ <h1>Pagoda<span class="jp">五重塔の庭</span></h1>
+ <p>A five-tiered tower rising through a spring garden — cherry blossoms, koi, stone lanterns and a vermilion gate, all built from colored cubes.</p>
+ </div>
+
+ <div class="panel">
+ <h2>Controls</h2>
+ <div class="row"><label>Time of day</label>
+ <div class="seg" id="timeSeg">
+ <button data-t="dawn">Dawn</button>
+ <button data-t="day" class="on">Day</button>
+ <button data-t="dusk">Dusk</button>
+ </div>
+ </div>
+ <div class="row"><label>Petals</label><div class="sw on" id="petalSw"></div></div>
+ <div class="row"><label>Auto-orbit</label><div class="sw on" id="orbitSw"></div></div>
+ <button class="btn" id="resetBtn">Reset view</button>
+ </div>
+
+ <div class="hint"><b>Drag</b> to orbit · <b>Scroll</b> to zoom · <b>Right-drag</b> to pan</div>
+ <div class="credit">Three.js · procedural voxel build</div>
+</div>
+
+<script type="importmap">
+{ "imports": {
+ "three": "https://unpkg.com/[email protected]/build/three.module.js",
+ "three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"
+}}
+</script>
+
+<script type="module">
+import * as THREE from 'three';
+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+
+/* ============================ helpers ============================ */
+const clamp=(v,a,b)=>Math.max(a,Math.min(b,v));
+const lerp=(a,b,t)=>a+(b-a)*t;
+const lerp3=(a,b,t)=>[lerp(a[0],b[0],t),lerp(a[1],b[1],t),lerp(a[2],b[2],t)];
+const smooth=(a,b,x)=>{const t=clamp((x-a)/(b-a),0,1);return t*t*(3-2*t);};
+const rand=(a,b)=>a+Math.random()*(b-a);
+const pick=a=>a[(Math.random()*a.length)|0];
+const hash=(x,y)=>{let h=(x*374761393+y*668265263)|0;h=(h^(h>>13))*1274126177;return((h^(h>>16))>>>0)/4294967295;};
+const shade=(c,f)=>[clamp(c[0]*f,0,1),clamp(c[1]*f,0,1),clamp(c[2]*f,0,1)];
+const toHex=c=>{const h=v=>('0'+Math.round(clamp(v,0,1)*255).toString(16)).slice(-2);return '#'+h(c[0])+h(c[1])+h(c[2]);};
+const hexToRgb=h=>{h=h.replace('#','');return[parseInt(h.slice(0,2),16)/255,parseInt(h.slice(2,4),16)/255,parseInt(h.slice(4,6),16)/255];};
+const rgbToHex=c=>toHex(c);
+
+/* ============================ palette ============================ */
+const C={
+ grass:[0.36,0.55,0.28], grassD:[0.30,0.47,0.24], grassL:[0.44,0.63,0.33],
+ dirt:[0.44,0.33,0.22], dirtD:[0.36,0.27,0.18],
+ stone:[0.60,0.60,0.62], stoneD:[0.48,0.48,0.50], stoneL:[0.72,0.72,0.74],
+ gravel:[0.78,0.76,0.70], gravelD:[0.66,0.64,0.58],
+ sand:[0.86,0.80,0.62], sandD:[0.74,0.68,0.52],
+ water:[0.20,0.55,0.66], waterD:[0.14,0.42,0.54], waterL:[0.42,0.74,0.82],
+ wood:[0.46,0.30,0.18], woodD:[0.34,0.22,0.13], woodL:[0.58,0.40,0.26],
+ verm:[0.72,0.16,0.13], vermD:[0.55,0.11,0.09], vermL:[0.85,0.28,0.20],
+ gold:[0.82,0.66,0.24], goldD:[0.62,0.48,0.16],
+ roof:[0.16,0.19,0.26], roofD:[0.11,0.13,0.19], roofL:[0.24,0.28,0.36],
+ leaf:[0.24,0.46,0.22], leafD:[0.18,0.36,0.17], leafL:[0.34,0.58,0.28],
+ leafA:[0.42,0.56,0.20], leafB:[0.30,0.50,0.24], leafC:[0.20,0.42,0.20],
+ maple:[0.72,0.24,0.16], mapleD:[0.55,0.16,0.12], mapleL:[0.86,0.40,0.22],
+ pine:[0.16,0.34,0.24], pineD:[0.12,0.26,0.18], pineL:[0.24,0.44,0.30],
+ bark:[0.30,0.22,0.16], barkD:[0.22,0.16,0.11],
+ sakura:[0.98,0.78,0.86], sakuraD:[0.92,0.62,0.74], sakuraL:[1.0,0.90,0.94],
+ white:[0.96,0.95,0.92], whiteD:[0.82,0.80,0.76],
+ red:[0.72,0.16,0.13], redD:[0.55,0.11,0.09],
+ koiO:[0.95,0.55,0.20], koiW:[0.96,0.94,0.90], koiR:[0.80,0.20,0.16],
+ lantern:[0.62,0.62,0.64], lanternD:[0.50,0.50,0.52],
+ glow:[1.0,0.72,0.34], glowD:[0.9,0.55,0.2],
+ bamboo:[0.42,0.60,0.28], bambooD:[0.32,0.48,0.20], bambooL:[0.55,0.72,0.36],
+ bambooLeaf:[0.30,0.52,0.24],
+ flower:[0.90,0.30,0.45], flowerD:[0.75,0.20,0.35], flowerL:[0.98,0.55,0.65],
+ flowerY:[0.95,0.80,0.30], flowerP:[0.62,0.42,0.72],
+ path:[0.70,0.66,0.58], pathD:[0.58,0.54,0.47],
+};
+
+/* ============================ voxel store ============================ */
+const voxels=new Map();
+const key=(x,y,z)=>x+','+y+','+z;
+function setVoxel(x,y,z,color){voxels.set(key(x,y,z),color);}
+function getVoxel(x,y,z){return voxels.get(key(x,y,z));}
+function hasVoxel(x,y,z){return voxels.has(key(x,y,z));}
+function fillBox(x0,x1,y0,y1,z0,z1,color){for(let x=x0;x<=x1;x++)for(let y=y0;y<=y1;y++)for(let z=z0;z<=z1;z++)setVoxel(x,y,z,color);}
+function fillBoxJitter(x0,x1,y0,y1,z0,z1,cols){for(let x=x0;x<=x1;x++)for(let y=y0;y<=y1;y++)for(let z=z0;z<=z1;z++)setVoxel(x,y,z,pick(cols));}
+function fillBoxShell(x0,x1,y0,y1,z0,z1,color){for(let x=x0;x<=x1;x++)for(let y=y0;y<=y1;y++)for(let z=z0;z<=z1;z++){const b=(x===x0||x===x1||y===y0||y===y1||z===z0||z===z1);if(b)setVoxel(x,y,z,color);}}
+function fillBoxShellJitter(x0,x1,y0,y1,z0,z1,cols){for(let x=x0;x<=x1;x++)for(let y=y0;y<=y1;y++)for(let z=z0;z<=z1;z++){const b=(x===x0||x===x1||y===y0||y===y1||z===z0||z===z1);if(b)setVoxel(x,y,z,pick(cols));}}
+function fillCyl(cx,cz,r,y0,y1,color){for(let y=y0;y<=y1;y++)for(let x=cx-r;x<=cx+r;x++)for(let z=cz-r;z<=cz+r;z++){const dx=x-cx,dz=z-cz;if(dx*dx+dz*dz<=r*r+0.4)setVoxel(x,y,z,color);}}
+function fillCylJitter(cx,cz,r,y0,y1,cols){for(let y=y0;y<=y1;y++)for(let x=cx-r;x<=cx+r;x++)for(let z=cz-r;z<=cz+r;z++){const dx=x-cx,dz=z-cz;if(dx*dx+dz*dz<=r*r+0.4)setVoxel(x,y,z,pick(cols));}}
+function fillCylShell(cx,cz,r,y0,y1,color){for(let y=y0;y<=y1;y++)for(let x=cx-r;x<=cx+r;x++)for(let z=cz-r;z<=cz+r;z++){const dx=x-cx,dz=z-cz,d=dx*dx+dz*dz;if(d<=r*r+0.4&&d>(r-1)*(r-1)+0.4)setVoxel(x,y,z,color);}}
+function fillCylShellJitter(cx,cz,r,y0,y1,cols){for(let y=y0;y<=y1;y++)for(let x=cx-r;x<=cx+r;x++)for(let z=cz-r;z<=cz+r;z++){const dx=x-cx,dz=z-cz,d=dx*dx+dz*dz;if(d<=r*r+0.4&&d>(r-1)*(r-1)+0.4)setVoxel(x,y,z,pick(cols));}}
+function fillSphere(cx,cy,cz,r,color){for(let x=cx-r;x<=cx+r;x++)for(let y=cy-r;y<=cy+r;y++)for(let z=cz-r;z<=cz+r;z++){const dx=x-cx,dy=y-cy,dz=z-cz;if(dx*dx+dy*dy+dz*dz<=r*r+0.6)setVoxel(x,y,z,color);}}
+function fillSphereJitter(cx,cy,cz,r,cols){for(let x=cx-r;x<=cx+r;x++)for(let y=cy-r;y<=cy+r;y++)for(let z=cz-r;z<=cz+r;z++){const dx=x-cx,dy=y-cy,dz=z-cz;if(dx*dx+dy*dy+dz*dz<=r*r+0.6)setVoxel(x,y,z,pick(cols));}}
+function fillCone(cx,cz,r,y0,color){for(let y=y0;y>=y0-r;y--){const rad=r-(y0-y);for(let x=cx-rad;x<=cx+rad;x++)for(let z=cz-rad;z<=cz+rad;z++){const dx=x-c
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/legit/pagoda_kyojin_s2.txt b/tools/qwen/fixtures/loopguard/legit/pagoda_kyojin_s2.txt
new file mode 100644
index 0000000..98fd4ff
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/legit/pagoda_kyojin_s2.txt
@@ -0,0 +1,651 @@
+Here's a complete, self-contained voxel scene — a five-tier pagoda rising from a mossy stone garden, framed by cherry blossoms, a koi pond, a torii gate, a stone lantern, and a winding path, all rendered with Three.js and wrapped in a hand-crafted "emaki scroll" interface. Save it as an `.html` file and open it.
+
+```html
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8">
+<meta name="viewport" content="width=device-width, initial-scale=1.0">
+<title>五重塔 · The Pagoda Garden</title>
+<link rel="preconnect" href="https://fonts.googleapis.com">
+<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+<link href="https://fonts.googleapis.com/css2?family=Shippori+Mincho+B1:wght@500;700;800&family=Zen+Kaku+Gothic+New:wght@400;500;700&display=swap" rel="stylesheet">
+<style>
+ :root{
+ --ink:#241d18; --ink-soft:#5b4f45; --paper:#f2e7d2; --paper-2:#e7d6b6;
+ --vermilion:#c8402f; --vermilion-d:#9e2f22; --gold:#c99a3f; --gold-l:#e6c877;
+ --jade:#4f7d5f; --line:rgba(60,40,25,.28);
+ --disp:"Shippori Mincho B1", serif;
+ --body:"Zen Kaku Gothic New", system-ui, sans-serif;
+ }
+ *{box-sizing:border-box;margin:0;padding:0}
+ html,body{height:100%}
+ body{
+ font-family:var(--body); color:var(--ink); overflow:hidden;
+ background:
+ radial-gradient(120% 90% at 50% -10%, #fbf3e2 0%, #f0e2c6 45%, #e6d3b0 100%);
+ }
+ /* paper grain */
+ body::before{
+ content:""; position:fixed; inset:0; z-index:0; pointer-events:none; opacity:.5;
+ background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='140' height='140'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2' stitchTiles='stitch'/%3E%3CfeColorMatrix type='saturate' values='0'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='0.55'/%3E%3C/svg%3E");
+ mix-blend-mode:multiply;
+ }
+ /* top & bottom scroll rods */
+ .rod{position:fixed; left:0; right:0; height:26px; z-index:40;
+ background:linear-gradient(#7a4a26,#4a2c15 55%,#2f1c0d);
+ box-shadow:0 2px 10px rgba(0,0,0,.35), inset 0 1px 0 rgba(255,220,170,.25);}
+ .rod.top{top:0} .rod.bottom{bottom:0}
+ .rod::before,.rod::after{content:""; position:absolute; top:-4px; bottom:-4px; width:16px;
+ background:linear-gradient(#e6c877,#a97e2c); border-radius:4px; box-shadow:0 0 6px rgba(0,0,0,.4)}
+ .rod::before{left:8px} .rod::after{right:8px}
+
+ #scene{position:fixed; inset:0; z-index:1; cursor:grab}
+ #scene:active{cursor:grabbing}
+
+ /* ---------- HUD ---------- */
+ .hud{position:fixed; z-index:30; pointer-events:none}
+ .hud *{pointer-events:auto}
+
+ .title{top:44px; left:34px; max-width:min(46vw,520px)}
+ .kicker{font-size:11px; letter-spacing:.42em; text-transform:uppercase; color:var(--vermilion-d);
+ font-weight:700; display:flex; align-items:center; gap:10px}
+ .kicker::before{content:""; width:34px; height:2px; background:var(--vermilion)}
+ .title h1{font-family:var(--disp); font-weight:800; line-height:.92; margin:10px 0 6px;
+ font-size:clamp(46px,7.4vw,96px); color:var(--ink); letter-spacing:.02em;
+ text-shadow:0 1px 0 rgba(255,255,255,.5)}
+ .title h1 .jp{display:block; font-size:.42em; letter-spacing:.34em; color:var(--vermilion);
+ font-weight:700; margin-bottom:2px}
+ .title p{font-size:14px; line-height:1.6; color:var(--ink-soft); max-width:34ch;
+ border-left:2px solid var(--gold); padding-left:12px; margin-top:12px}
+
+ .seal{position:absolute; top:52px; right:34px; width:74px; height:74px; border-radius:12px;
+ background:linear-gradient(150deg,#d24a37,#a52d20); color:#ffe9d6; display:grid; place-items:center;
+ font-family:var(--disp); font-weight:800; font-size:30px; line-height:1; letter-spacing:.05em;
+ box-shadow:0 6px 18px rgba(120,30,20,.4), inset 0 0 0 2px rgba(255,255,255,.18);
+ transform:rotate(-4deg); animation:sealPulse 5s ease-in-out infinite}
+ .seal small{position:absolute; bottom:5px; font-size:8px; letter-spacing:.2em; opacity:.85}
+ @keyframes sealPulse{0%,100%{transform:rotate(-4deg) scale(1)}50%{transform:rotate(-4deg) scale(1.04)}}
+
+ .panel{top:44px; right:34px; margin-top:96px; width:236px;
+ background:linear-gradient(180deg,rgba(255,250,238,.94),rgba(240,228,203,.94));
+ border:1px solid var(--line); border-radius:14px; padding:16px 16px 18px;
+ box-shadow:0 14px 34px rgba(60,40,20,.18), inset 0 1px 0 rgba(255,255,255,.6);
+ backdrop-filter:blur(3px)}
+ .panel h2{font-family:var(--disp); font-size:15px; letter-spacing:.14em; color:var(--ink);
+ display:flex; align-items:center; gap:8px; margin-bottom:12px}
+ .panel h2::before{content:""; width:9px; height:9px; background:var(--vermilion); border-radius:2px; transform:rotate(45deg)}
+ .btns{display:grid; grid-template-columns:1fr 1fr; gap:8px}
+ .btn{font-family:var(--body); font-weight:700; font-size:12.5px; letter-spacing:.02em;
+ padding:9px 8px; border-radius:9px; cursor:pointer; color:var(--ink);
+ background:linear-gradient(#fffaf0,#efe1c4); border:1px solid var(--line);
+ box-shadow:0 2px 0 rgba(120,90,50,.18); transition:transform .12s ease, box-shadow .12s ease, background .2s}
+ .btn:hover{transform:translateY(-2px); box-shadow:0 5px 12px rgba(120,90,50,.22); background:linear-gradient(#fff,#f4e7cd)}
+ .btn:active{transform:translateY(0)}
+ .btn.on{background:linear-gradient(#d24a37,#a52d20); color:#fff2e6; border-color:#7c2418; box-shadow:0 2px 0 #6f1f14}
+ .btn.wide{grid-column:1 / -1}
+ .divider{height:1px; background:var(--line); margin:14px 0 12px}
+ .ctl{margin-bottom:12px}
+ .ctl label{display:flex; justify-content:space-between; font-size:11px; letter-spacing:.08em;
+ text-transform:uppercase; color:var(--ink-soft); font-weight:700; margin-bottom:6px}
+ .ctl label b{color:var(--vermilion-d)}
+ input[type=range]{-webkit-appearance:none; appearance:none; width:100%; height:5px; border-radius:4px;
+ background:linear-gradient(90deg,var(--vermilion) var(--p,50%),#d8c6a2 var(--p,50%)); outline:none}
+ input[type=range]::-webkit-slider-thumb{-webkit-appearance:none; width:16px; height:16px; border-radius:50%;
+ background:radial-gradient(circle at 35% 30%,#fff,#c99a3f); border:2px solid #8a6a2a; cursor:pointer;
+ box-shadow:0 2px 5px rgba(0,0,0,.3)}
+ input[type=range]::-moz-range-thumb{width:16px; height:16px; border-radius:50%;
+ background:radial-gradient(circle at 35% 30%,#fff,#c99a3f); border:2px solid #8a6a2a; cursor:pointer}
+
+ .legend{bottom:44px; left:34px; display:flex; flex-wrap:wrap; gap:8px 16px; max-width:52vw}
+ .legend span{display:flex; align-items:center; gap:7px; font-size:12px; color:var(--ink-soft); font-weight:500}
+ .legend i{width:13px; height:13px; border-radius:3px; box-shadow:inset 0 0 0 1px rgba(0,0,0,.15)}
+
+ .hint{bottom:44px; right:34px; font-size:11.5px; letter-spacing:.06em; color:var(--ink-soft);
+ text-align:right; line-height:1.7}
+ .hint b{color:var(--vermilion-d)}
+
+ /* loader */
+ #loader{position:fixed; inset:0; z-index:60; display:grid; place-items:center;
+ background:radial-gradient(120% 90% at 50% 30%,#fbf3e2,#e6d3b0); transition:opacity .8s ease}
+ #loader.hide{opacity:0; pointer-events:none}
+ .loader-in{text-align:center}
+ .loader-in .jp{font-family:var(--disp); font-size:64px; color:var(--vermilion); letter-spacing:.2em;
+ animation:breathe 2.4s ease-in-out infinite}
+ .loader-in p{margin-top:14px; font-size:12px; letter-spacing:.4em; text-transform:uppercase; color:var(--ink-soft)}
+ @keyframes breathe{0%,100%{opacity:.55; transform:scale(.98)}50%{opacity:1; transform:scale(1.02)}}
+
+ @media (max-width:820px){
+ .title{max-width:70vw} .panel{width:200px; margin-top:88px}
+ .legend{max-width:60vw} .hint{display:none} .seal{width:58px;height:58px;font-size:24px}
+ }
+</style>
+</head>
+<body>
+ <div class="rod top"></div>
+ <div class="rod bottom"></div>
+
+ <div id="scene"></div>
+
+ <div class="hud title">
+ <div class="kicker">Voxel Study · 庭園</div>
+ <h1><span class="jp">五重塔</span>The Pagoda<br>Garden</h1>
+ <p>A five-tiered tower of vermilion and gold, cradled by cherry blossoms, koi, and stone — rendered voxel by voxel.</p>
+ </div>
+
+ <div class="seal">塔<small>五重</small></div>
+
+ <div class="hud panel">
+ <h2>SCENE CONTROLS</h2>
+ <div class="btns">
+ <button class="btn on" id="bRotate">Auto-orbit</button>
+ <button class="btn on" id="bPetals">Petals</button>
+ <button class="btn" id="bReset">Reset view</button>
+ <button class="btn" id="bTop">Top-down</button>
+ </div>
+ <div class="divider"></div>
+ <div class="ctl">
+ <label>Time of day <b id="todVal">Midday</b></label>
+ <input type="range" id="tod" min="0" max="100" value="55">
+ </div>
+ <div class="ctl">
+ <label>Petal density <b id="petVal">100%</b></label>
+ <input type="range" id="pet" min="0" max="100" value="100">
+ </div>
+ </div>
+
+ <div class="hud legend">
+ <span><i style="background:#c8402f"></i>Pagoda</span>
+ <span><i style="background:#f4a7c0"></i>Cherry blossom</span>
+ <span><i style="background:#4f7d5f"></i>Moss &amp; pine</span>
+ <span><i style="background:#3f86a8"></i>Koi pond</span>
+ <span><i style="background:#c99a3f"></i>Gold &amp; torii</span>
+ <span><i style="background:#8a8378"></i>Stone</span>
+ </div>
+
+ <div class="hud hint">
+ <b>Drag</b> to orbit · <b>Scroll</b> to zoom<br>
+ <b>Click</b> a structure to focus
+ </div>
+
+ <div id="loader"><div class="loader-in"><div class="jp">塔</div><p>Building the garden…</p></div></div>
+
+<script type="importmap">
+{
+ "imports": {
+ "three": "https://unpkg.com/[email protected]/build/three.module.js",
+ "three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"
+ }
+}
+</script>
+
+<script type="module">
+import * as THREE from 'three';
+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+
+/* ============================ helpers ============================ */
+const clamp=(v,a,b)=>Math.max(a,Math.min(b,v));
+const lerp=(a,b,t)=>a+(b-a)*t;
+const lerp3=(a,b,t)=>[lerp(a[0],b[0],t),lerp(a[1],b[1],t),lerp(a[2],b[2],t)];
+const lerpC=(a,b,t)=>new THREE.Color(a).lerp(new THREE.Color(b),t);
+const easeIO=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;
+const smooth=(a,b,x)=>{const t=clamp((x-a)/(b-a),0,1);return t*t*(3-2*t);};
+const hash=(x,y,z)=>{let h=(x*374761393+y*668265263+z*1274126177)>>>0;h=(h^(h>>13))>>>0;h=(h*1274126177)>>>0;return (h^(h>>16))>>>0;};
+const rnd=(x,y,z)=>hash(x,y,z)/4294967295;
+const pick=(arr,x,y,z)=>arr[Math.floor(rnd(x,y,z)*arr.length)%arr.length];
+const shade=(hex,f)=>{const c=new THREE.Color(hex);c.multiplyScalar(f);return c;};
+const jitter=(hex,a,x,y,z)=>shade(hex,1+(rnd(x,y,z)*2-1)*a);
+
+/* ============================ palette ============================ */
+const P={
+ stoneLight:'#b7b0a4', stoneMid:'#9a9388', stoneDark:'#7c766c',
+ mossLight:'#7fae5f', mossMid:'#5f9048', mossDark:'#4a7438',
+ dirt:'#6b5138', dirtDark:'#574029',
+ waterDeep:'#276a86', waterMid:'#3f86a8', waterShallow:'#6fb0c6',
+ woodDark:'#5a3a24', woodMid:'#7a5230', woodLight:'#9a6a3c',
+ vermilion:'#c8402f', vermilionD:'#9e2f22', vermilionL:'#e05a44',
+ gold:'#c99a3f', goldL:'#e6c877',
+ roofDark:'#33302e', roofMid:'#46423e', roofLight:'#5b5650',
+ wall:'#efe6d2', wallShade:'#d9cdb2',
+ pineDark:'#2f5a3c', pineMid:'#3f7048', pineLight:'#528a56',
+ maple:'#d9542f', mapleD:'#b23a1e', mapleL:'#ef7a3a',
+ cherryA:'#f7c9d9', cherryB:'#f4a7c0', cherryC:'#e987a8', cherryD:'#fbdbe6',
+ pink:'#f2a9c0', red:'#d24a37', orange:'#e88a3a', yellow:'#e8c34a',
+ koiWhite:'#f2ede2', koiOrange:'#e8763a', koiRed:'#c8402f',
+ lantern:'#8a8378', lanternDark:'#6f685e',
+ bamboo:'#6f9a4a', bambooD:'#567c39',
+ grassA:'#6fa24f', grassB:'#5c8a40', grassC:'#84b45f',
+ petal:'#f6c6d6', petalD:'#e79ab4',
+};
+
+/* ============================ renderer / scene ============================ */
+const host=document.getElementById('scene');
+const renderer=new THREE.WebGLRenderer({antialias:true});
+renderer.setPixelRatio(Math.min(devicePixelRatio,2));
+renderer.setSize(innerWidth,innerHeight);
+renderer.shadowMap.enabled=true;
+renderer.shadowMap.type=THREE.PCFSoftShadowMap;
+renderer.toneMapping=THREE.ACESFilmicToneMapping;
+renderer.toneMappingExposure=1.05;
+host.appendChild(renderer.domElement);
+
+const scene=new THREE.Scene();
+scene.fog=new THREE.FogExp2(0xf0d9b6,0.006);
+
+const camera=new THREE.PerspectiveCamera(46,innerWidth/innerHeight,0.5,4000);
+camera.position.set(150,110,175);
+
+const controls=new OrbitControls(camera,renderer.domElement);
+controls.enableDamping=true; controls.dampingFactor=0.06;
+controls.minDistance=45; controls.maxDistance=420;
+controls.maxPolarAngle=Math.PI*0.49;
+controls.target.set(0,26,0);
+
+/* ============================ lights ============================ */
+const hemi=new THREE.HemisphereLight(0xdfeaf2,0x6b5a44,0.85); scene.add(hemi);
+const sun=new THREE.DirectionalLight(0xfff2d8,2.6);
+sun.castShadow=true;
+sun.shadow.mapSize.set(2048,2048);
+sun.shadow.camera.near=1; sun.shadow.camera.far=600;
+const S=150; Object.assign(sun.shadow.camera,{left:-S,right:S,top:S,bottom:-S});
+sun.shadow.bias=-0.0004; sun.shadow.normalBias=0.6;
+scene.add(sun); scene.add(sun.target);
+const fill=new THREE.DirectionalLight(0xbcd0e6,0.35); fill.position.set(-120,80,-90); scene.add(fill);
+
+/* ============================ sky dome ============================ */
+const skyMat=new THREE.ShaderMaterial({
+ side:THREE.BackSide, depthWrite:false,
+ uniforms:{top:{value:new THREE.Color('#8fb6d6')},bot:{value:new THREE.Color('#f6e3c2')},sun:{value:new THREE.Color('#fff3d6')}},
+ vertexShader:`varying vec3 vD; void main(){vD=normalize(position); gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0);}`,
+ fragmentShader:`varying vec3 vD; uniform vec3 top; uniform vec3 bot; uniform vec3 sun;
+ void main(){ float h=clamp(vD.y*0.5+0.5,0.0,1.0); vec3 c=mix(bot,top,pow(h,0.85));
+ float s=pow(max(dot(vD,normalize(vec3(0.4,0.55,0.7))),0.0),14.0); c+=sun*s*0.5;
+ gl_FragColor=vec4(c,1.0);}`
+});
+const sky=new THREE.Mesh(new THREE.SphereGeometry(1600,24,16),skyMat); sky.frustumCulled=false; scene.add(sky);
+
+/* ============================ voxel engine ============================ */
+const voxelGeo=new THREE.BoxGeometry(1,1,1);
+const V=(x,y,z,color)=>({x,y,z,color});
+const group=new THREE.Group(); scene.add(group);
+const pickables=[];
+
+function build(name,voxels,opts={}){
+ const g=new THREE.Group(); g.name=name;
+ const buckets=new Map();
+ for(const v of voxels){
+ const key=v.color.getHex();
+ if(!buckets.has(key))buckets.set(key,[]);
+ buckets.get(key).push(v);
+ }
+ for(const [hex,list] of buckets){
+ const mat=new THREE.MeshLambertMaterial({color:hex});
+ const im=new THREE.InstancedMesh(voxelGeo,mat,list.length);
+ im.castShadow=opts.cast!==false; im.receiveShadow=opts.receive!==false;
+ const m=new THREE.Matrix4();
+ list.forEach((v,i)=>{m.makeTranslation(v.x,v.y,v.z); im.setMatrixAt(i,m);});
+ im.instanceMatrix.needsUpdate=true;
+ im.userData={name,voxels:list};
+ g.add(im);
+ }
+ g.userData={name,voxels};
+ group.add(g);
+ if(opts.pick!==false)pickables.push(g);
+ return g;
+}
+
+/* ============================ builders ============================ */
+function buildGround(){
+ const R=62, vox=[];
+ for(let x=-R;x<=R;x++)for(let z=-R;z<=R;z++){
+ const d=Math.hypot(x,z); if(d>R)continue;
+ const n=rnd(x,7,z);
+ let c;
+ if(d>R-2.5) c=jitter(P.stoneDark,0.05,x,0,z);
+ else if(n<0.16) c=jitter(P.mossDark,0.06,x,1,z);
+ else if(n<0.5) c=jitter(P.mossMid,0.06,x,2,z);
+ else if(n<0.82) c=jitter(P.mossLight,0.06,x,3,z);
+ else c=jitter(P.grassC,0.06,x,4,z);
+ vox.push(V(x,-1,z,c));
+ }
+ build('ground',vox,{cast:false});
+}
+
+function buildPath(){
+ const vox=[];
+ const line=(x,z)=>{const n=rnd(x,9,z);
+ if(n<0.25)return jitter(P.stoneDark,0.05,x,5,z);
+ if(n<0.6)return jitter(P.stoneMid,0.05,x,6,z);
+ return jitter(P.stoneLight,0.05,x,7,z);};
+ for(let z=30;z>=12;z--){const w=2+Math.round(Math.sin(z*0.4)*0.8);
+ for(let x=-w;x<=w;x++)vox.push(V(x,0,z,line(x,z)));}
+ for(let x=-18;x<=18;x++)for(let z=6;z<=12;z++)vox.push(V(x,0,z,line(x,z)));
+ for(let x=-24;x<=24;x++)for(let z=2;z<=6;z++)vox.push(V(x,0,z,line(x,z)));
+ build('path',vox,{cast:false});
+}
+
+function buildPond(){
+ const cx=-30,cz=24,rx=15,rz=11,vox=[];
+ for(let x=cx-rx-2;x<=cx+rx+2;x++)for(let z=cz-rz-2;z<=cz+rz+2;z++){
+ const e=((x-cx)/rx)**2+((z-cz)/rz)**2;
+ if(e<=1){
+ const n=rnd(x,11,z);
+ let c = e<0.45?jitter(P.waterDeep,0.05,x,0,z) : e<0.78?jitter(P.waterMid,0.05,x,1,z) : jitter(P.waterShallow,0.05,x,2,z);
+ vox.push(V(x,-1,z,c));
+ } else if(e<=1.28){
+ const n=rnd(x,12,z);
+ vox.push(V(x,0,z, n<0.4?jitter(P.stoneDark,0.05,x,3,z): n<0.75?jitter(P.stoneMid,0.05,x,4,z):jitter(P.stoneLight,0.05,x,5,z)));
+ }
+ }
+ build('pond',vox,{cast:false});
+}
+
+function buildBridge(){
+ const vox=[];
+ for(let x=-40;x<=-20;x++){
+ const t=(x+40)/20, y=Math.round(2+Math.sin(t*Math.PI)*3);
+ for(let z=22;z<=25;z++)vox.push(V(x,y,z,jitter(P.woodMid,0.05,x,0,z)));
+ for(let z of [22,25]){vox.push(V(x,y+1,z,jitter(P.woodDark,0.05,x,1,z)));
+ if((x+z)%3===0)vox.push(V(x,y+2,z,jitter(P.woodDark,0.05,x,2,z)));}
+ }
+ build('bridge',vox);
+}
+
+function buildPagoda(){
+ const vox=[];
+ const add=(x,y,z,c)=>vox.push(V(x,y,z,c));
+ const ring=(cx,cz,r,y,c)=>{for(let x=-r;x<=r;x++)for(let z=-r;z<=r;z++){const d=Math.hypot(x-cx,z-cz);
+ if(d<=r&&d>r-1.15)add(cx+x,y,cz+z,c);}};
+ const disc=(cx,cz,r,y,c)=>{for(let x=-r;x<=r;x++)for(let z=-r;z<=r;z++)if(Math.hypot(x-cx,z-cz)<=r)add(cx+x,y,cz+z,c);};
+ const box=(x0,x1,y0,y1,z0,z1,c)=>{for(let x=x0;x<=x1;x++)for(let y=y0;y<=y1;y++)for(let z=z0;z<=z1;z++)add(x,y,z,c);};
+
+ // stone plinth
+ box(-15,15,0,0,-15,15,jitter(P.stoneMid,0.04,0,0,0));
+ box(-13,13,1,1,-13,13,jitter(P.stoneLight,0.04,0,1,0));
+ box(-11,11,2,2,-11,11,jitter(P.stoneMid,0.04,0,2,0));
+ // steps
+ for(let s=0;s<3;s++){const w=15-s*2; for(let x=-w;x<=w;x++)add(x,s,15+s,jitter(P.stoneLight,0.04,x,3,s));}
+
+ // 5 tiers
+ const levels=[{r:10,h:6},{r:9,h:5},{r:8,h:5},{r:7,h:4},{r:6,h:4}];
+ let y=3;
+ levels.forEach((L,i)=>{
+ const r=L.r, h=L.h;
+ // walls
+ for(let x=-r;x<=r;x++)for(let z=-r;z<=r;z++){const d=Math.hypot(x,z);
+ if(d<=r&&d>r-1.15){
+ let c = (x===0||z===0)?jitter(P.woodDark,0.04,x,y,z):jitter(P.wall,0.03,x,y,z);
+ if(Math.abs(x)===r||Math.abs(z)===r)c=jitter(P.woodMid,0.04,x,y,z);
+ add(x,y,z,c);
+ }}
+ // windows
+ for(let w=-r+2;w<=r-2;w+=4){add(w,y+2,r,jitter(P.woodDark,0.02,w,y,r));add(w,y+2,-r,jitter(P.woodDark,0.02,w,y,-r));
+ add(r,y+2,w,jitter(P.woodDark,0.02,r,y,w));add(-r,y+2,w,jitter(P.woodDark,0.02,-r,y,w));}
+ // balcony
+ const by=y+h;
+ for(let x=-r-1;x<=r+1;x++)for(let z=-r-1;z<=r+1;z++){const d=Math.hypot(x,z);
+ if(d<=r+1&&d>r-0.4)add(x,by,z,jitter(P.woodMid,0.04,x,by,z));}
+ for(let x=-r-1;x<=r+1;x++)for(let z=-r-1;z<=r+1;z++){const d=Math.hypot(x,z);
+ if(d<=r+1&&d>r-0.4&&((x+z)%2===0))add(x,by+1,z,jitter(P.woodDark,0.04,x,by+1,z));}
+ // roof
+ const ry=by+2, rr=r+3;
+ for(let x=-rr;x<=rr;x++)for(let z=-rr;z<=rr;z++){const d=Math.hypot(x,z);
+ if(d<=rr&&d>rr-1.3)add(x,ry,z,jitter(P.roofDark,0.05,x,ry,z));}
+ for(let x=-rr+1;x<=rr-1;x++)for(let z=-rr+1;z<=rr-1;z++){const d=Math.hypot(x,z);
+ if(d<=rr-1&&d>rr-2.4)add(x,ry+1,z,jitter(P.roofMid,0.05,x,ry+1,z));}
+ for(let x=-rr+2;x<=rr-2;x++)for(let z=-rr+2;z<=rr-2;z++){const d=Math.hypot(x,z);
+ if(d<=rr-2&&d>rr-3.4)add(x,ry+2,z,jitter(P.roofLight,0.05,x,ry+2,z));}
+ // corner upturns
+ for(const sx of[-1,1])for(const sz of[-1,1]){add(sx*rr,ry+1,sz*rr,jitter(P.roofLight,0.05,sx*rr,ry,sz*rr));
+ add(sx*(rr-1),ry+1,sz*rr,jitter(P.roofLight,0.05,sx*(rr-1),ry,sz*rr));
+ add(sx*rr,ry+1,sz*(rr-1),jitter(P.roofLight,0.05,sx*rr,ry,sz*(rr-1)));}
+ // gold ridge
+ for(let x=-rr+2;x<=rr-2;x++)add(x,ry+3,0,jitter(P.gold,0.05,x,ry+3,0));
+ y=ry+4;
+ });
+ // spire
+ disc(0,0,3,y,jitter(P.gold,0.05,0,y,0));
+ for(let k=0;k<6;k++){disc(0,0,3-k*0.4,y+1+k,jitter(P.goldL,0.05,0,y+1+k,0));}
+ for(let k=0;k<8;k++)add(0,y+7+k,0,jitter(P.gold,0.05,0,y+7+k,0));
+ add(0,y+15,0,jitter(P.goldL,0.05,0,y+15,0));
+ build('pagoda',vox);
+}
+
+function buildTorii(){
+ const vox=[]; const add=(x,y,z,c)=>vox.push(V(x,y,z,c));
+ const col=(x,z)=>{for(let y=0;y<=11;y++)add(x,y,z,jitter(P.vermilion,0.05,x,y,z));};
+ col(-9,-2);col(-9,2);col(9,-2);col(9,2);
+ for(let x=-11;x<=11;x++)for(let z=-2;z<=2;z++)add(x,12,z,jitter(P.vermilionD,0.04,x,12,z));
+ for(let x=-13;x<=13;x++)for(let z=-3;z<=3;z++)add(x,13,z,jitter(P.roofDark,0.05,x,13,z));
+ for(let x=-13;x<=13;x++)for(let z=-3;z<=3;z++)add(x,14,z,jitter(P.roofDark,0.05,x,14,z));
+ for(const sx of[-1,1])for(const sz of[-1,1]){add(sx*13,15,sz*3,jitter(P.roofDark,0.05,sx*13,15,sz*3));add(sx*12,15,sz*3,jitter(P.roofDark,0.05,sx*12,15,sz*3));}
+ for(let x=-9;x<=9;x++)add(x,9,0,jitter(P.vermilion,0.04,x,9,0));
+ for(let x=-10;x<=10;x++)add(x,10,0,jitter(P.gold,0.05,x,10,0));
+ build('torii',vox);
+}
+
+function buildLantern(x,z){
+ const vox=[]; const add=(dx,y,dz,c)=>vox.push(V(x+dx,y,z+dz,c));
+ add(0,0,0,jitter(P.lanternDark,0.05,x,0,z));
+ add(0,1,0,jitter(P.lantern,0.05,x,1,z));
+ add(0,2,0,jitter(P.lantern,0.05,x,2,z));
+ for(const dx of[-1,0,1])for(const dz of[-1,0,1])add(dx,3,dz,jitter(P.lantern,0.05,x,3,z));
+ for(const dx of[-1,0,1])for(const dz of[-1,0,1])if(Math.abs(dx)+Math.abs(dz)<=1)add(dx,4,dz,jitter(P.lanternDark,0.05,x,4,z));
+ for(const dx of[-1,0,1])for(const dz of[-1,0,1])if(Math.abs(dx)+Math.abs(dz)<=1)add(dx,5,dz,jitter(P.lantern,0.05,x,5,z));
+ for(const dx of[-1,0,1])for(const dz of[-1,0,1])add(dx,6,dz,jitter(P.lanternDark,0.05,x,6,z));
+ for(const dx of[-1,0,1])for(const dz of[-1,0,1])if(Math.abs(dx)+Math.abs(dz)<=1)add(dx,7,dz,jitter(P.lantern,0.05,x,7,z));
+ for(const dx of[-2,-1,0,1,2])for(const dz of[-2,-1,0,1,2])if(Math.abs(dx)+Math.abs(dz)<=2)add(dx,8,dz,jitter(P.lanternDark,0.05,x,8,z));
+ add(0,9,0,jitter(P.lantern,0.05,x,9,z));
+ build('lantern',vox);
+}
+
+function buildTree(cx,cz,type){
+ const vox=[]; const add=(x,y,z,c)=>vox.push(V(x,y,z,c));
+ const trunk=(h,base)=>{for(let y=0;y<h;y++){const r=y<h*0.4?base:Math.max(1,base-1);
+ for(let x=-r;x<=r;x++)for(let z=-r;z<=r;z++)if(Math.hypot(x,z)<=r+0.2)add(cx+x,y,cz+z,jitter(P.woodDark,0.06,cx+x,y,cz+z));}};
+ const canopy=(cy,r,cols)=>{for(let x=-r;x<=r;x++)for(let y=-r;y<=r;y++)for(let z=-r;z<=r;z++){
+ const d=Math.hypot(x,y*0.85,z); if(d<=r&&d>r-1.6){
+ const n=rnd(cx+x,cy+y,cz+z);
+ add(cx+x,cy+y,cz+z,cols[Math.floor(n*cols.length)%cols.length]);}}};
+ if(type==='cherry'){
+ trunk(6,1);
+ for(let i=0;i<4;i++){const a=i*1.6+0.4;const dx=Math.round(Math.cos(a)*3),dz=Math.round(Math.sin(a)*3);
+ for(let y=4;y<7;y++)add(cx+Math.round(dx*y/6),y,cz+Math.round(dz*y/6),jitter(P.woodDark,0.06,cx,y,cz));}
+ canopy(9,5,[P.cherryA,P.cherryB,P.cherryC,P.cherryD]);
+ canopy(11,3,[P.cherryD,P.cherryA,P.cherryB]);
+ } else if(type==='pine'){
+ trunk(4,1);
+ canopy(6,4,[P.pineDark,P.pineMid,P.pineLight]);
+ canopy(9,3,[P.pineMid,P.pineLight,P.pineDark]);
+ canopy(11,2,[P.pineLight,P.pineMid]);
+ } else if(type==='maple'){
+ trunk(5,1);
+ canopy(8,4,[P.maple,P.mapleD,P.mapleL]);
+ canopy(10,2,[P.mapleL,P.maple]);
+ } else { // bamboo
+ for(let s=0;s<6;s++){const bx=cx+Math.round((rnd(cx+s,cz,0)*2-1)*2),bz=cz+Math.round((rnd(cx,cz+s,0)*2-1)*2);
+ const h=6+Math.floor(rnd(bx,bz,0)*5);
+ for(let y=0;y<h;y++)add(bx,y,bz,y%3===0?jitter(P.bambooD,0.05,bx,y,bz):jitter(P.bamboo,0.05,bx,y,bz));
+ for(let y=h-2;y<=h;y++)for(const dx of[-1,0,1])for(const dz of[-1,0,1])if(rnd(bx+dx,y,bz+dz)>0.4)add(bx+dx,y,bz+dz,jitter(P.bamboo,0.06,bx+dx,y,bz+dz));}
+ }
+ build('tree',vox);
+}
+
+function buildRocks(cx,cz){
+ const vox=[]; const add=(x,y,z,c)=>vox.push(V(x,y,z,c));
+ const sizes=[[3,2,3],[2,2,2],[2,1,2]];
+ let ox=cx;
+ for(const [sx,sy,sz] of sizes){
+ for(let x=0;x<sx;x++)for(let y=0;y<sy;y++)for(let z=0;z<sz;z++){
+ if(rnd(ox+x,y,cz+z)>0.25)add(ox+x,y,cz+z,jitter(P.stoneMid,0.06,ox+x,y,cz+z));}
+ ox+=sx+1;
+ }
+ build('rocks',vox);
+}
+
+function buildFlowers(){
+ const vox=[]; const cols=[P.pink,P.red,P.orange,P.yellow,P.cherryB];
+ const spots=[[-14,14],[14,14],[-16,8],[16,8],[-20,18],[20,18],[-8,20],[8,20],[-24,10],[24,10]];
+ for(const [sx,sz] of spots){
+ for(let i=0;i<10;i++){const x=sx+Math.round((rnd(sx+i,sz,0)*2-1)*2),z=sz+Math.round((rnd(sx,sz+i,0)*2-1)*2);
+ vox.push(V(x,0,z,jitter(P.grassB,0.05,x,0,z)));
+ vox.push(V(x,1,z,cols[Math.floor(rnd(x,1,z)*cols.length)%cols.length]));}
+ }
+ build('flowers',vox,{cast:false});
+}
+
+/* ============================ koi ============================ */
+const koi=[];
+function buildKoi(){
+ const cols=[P.koiWhite,P.koiOrange,P.koiRed];
+ for(let i=0;i<4;i++){
+ const mat=new THREE.MeshLambertMaterial({color:cols[i%3]});
+ const g=new THREE.Group();
+ const body=new THREE.Mesh(new THREE.BoxGeometry(2.4,0.7,1.1),mat); body.castShadow=true; g.add(body);
+ const tail=new THREE.Mesh(new THREE.BoxGeometry(0.9,0.5,1.6),mat); tail.position.x=-1.6; g.add(tail);
+ const fin=new THREE.Mesh(new THREE.BoxGeometry(0.7,0.4,0.4),mat); fin.position.set(0.4,0.4,0); g.add(fin);
+ g.position.set(-30,0.1,24);
+ koi.push({mesh:g,ang:Math.random()*6.28,rad:4+Math.random()*6,spd:0.25+Math.random()*0.25,ph:Math.random()*6.28});
+ scene.add(g);
+ }
+}
+
+/* ============================ petals ============================ */
+let petalMesh,petalCount=0,petalBase=1200;
+const petalGeo=new THREE.BoxGeometry(0.7,0.12,0.7);
+const petalData=[];
+function buildPetals(){
+ const mat=new THREE.MeshLambertMaterial({color:0xffffff});
+ petalMesh=new THREE.InstancedMesh(petalGeo,mat,petalBase);
+ petalMesh.castShadow=false; petalMesh.frustumCulled=false;
+ const c=new THREE.Color();
+ for(let i=0;i<petalBase;i++){
+ petalData.push({x:(Math.random()*2-1)*70,y:Math.random()*70,z:(Math.random()*2-1)*70,
+ vy:-(0.4+Math.random()*0.8),sw:0.4+Math.random()*0.8,ph:Math.random()*6.28,rot:Math.random()*6.28,rs:(Math.random()*2-1)*1.5});
+ c.set(Math.random()<0.5?P.petal:P.petalD); petalMesh.setColorAt(i,c);
+ }
+ petalMesh.instanceColor.needsUpdate=true;
+ scene.add(petalMesh);
+}
+function updatePetals(dt,t){
+ const m=new THREE.Matrix4(),q=new THREE.Quaternion(),e=new THREE.Euler(),s=new THREE.Vector3(1,1,1),p=new THREE.Vector3();
+ for(let i=0;i<petalCount;i++){
+ const d=petalData[i];
+ d.y+=d.vy*dt; d.x+=Math.sin(t*d.sw+d.ph)*0.02; d.z+=Math.cos(t*d.sw*0.8+d.ph)*0.02; d.rot+=d.rs*dt;
+ if(d.y<-1){d.y=60+Math.random()*15;d.x=(Math.random()*2-1)*70;d.z=(Math.random()*2-1)*70;}
+ e.set(d.rot,d.rot*0.7,d.rot*0.4); q.setFromEuler(e); p.set(d.x,d.y,d.z);
+ m.compose(p,q,s); petalMesh.setMatrixAt(i,m);
+ }
+ petalMesh.instanceMatrix.needsUpdate=true;
+}
+
+/* ============================ assemble ============================ */
+buildGround(); buildPath(); buildPond(); buildBridge(); buildPagoda(); buildTorii();
+buildLantern(-16,10); buildLantern(16,10); buildLantern(-40,14); buildLantern(40,14);
+buildTree(-24,4,'cherry'); buildTree(24,4,'cherry'); buildTree(-46,-6,'cherry'); buildTree(46,-6,'cherry');
+buildTree(-40,34,'cherry'); buildTree(40,34,'cherry'); buildTree(-52,20,'cherry'); buildTree(52,20,'cherry');
+buildTree(-14,-30,'pine'); buildTree(14,-30,'pine'); buildTree(-34,-24,'pine'); buildTree(34,-24,'pine');
+buildTree(-56,-18,'pine'); buildTree(56,-18,'pine');
+buildTree(-20,-14,'maple'); buildTree(20,-14,'maple'); buildTree(-44,10,'maple'); buildTree(44,10,'maple');
+buildTree(-50,36,'bamboo'); buildTree(50,36,'bamboo'); buildTree(-58,4,'bamboo'); buildTree(58,4,'bamboo');
+buildRocks(-46,30); buildRocks(46,30); buildRocks(-56,-30); buildRocks(56,-30);
+buildFlowers(); buildKoi(); buildPetals();
+petalCount=petalBase;
+
+/* ============================ time of day ============================ */
+const TOD=[
+ {p:0.00,top:'#3a4a6b',bot:'#e88a5a',sun:'#ff9a5a',dir:0.7,hemi:0.45,sky:0.55,ex:1.0,fog:'#c98a6a',sunPos:[-1,0.12,-0.6]},
+ {p:0.22,top:'#7fa6cf',bot:'#f2d6a8',sun:'#ffe6b0',dir:2.2,hemi:0.8,sky:0.85,ex:1.05,fog:'#e6d3b0',sunPos:[-0.7,0.5,-0.5]},
+ {p:0.50,top:'#8fb6d6',bot:'#f6e3c2',sun:'#fff3d6',dir:2.7,hemi:0.9,sky:1.0,ex:1.05,fog:'#f0d9b6',sunPos:[0.4,0.9,0.6]},
+ {p:0.78,top:'#6f8fbf',bot:'#f4b070',sun:'#ffb066',dir:2.0,hemi:0.7,sky:0.8,ex:1.05,fog:'#e0a878',sunPos:[0.8,0.35,0.5]},
+ {p:1.00,top:'#2a3350',bot:'#d96a4a',sun:'#ff7a4a',dir:0.8,hemi:0.4,sky:0.5,ex:1.0,fog:'#b06a52',sunPos:[1,0.1,0.4]},
+];
+function applyTOD(t){
+ t=clamp(t,0,1); let a=TOD[0],b=TOD[TOD.length-1];
+ for(let i=0;i<TOD.length-1;i++){if(t>=TOD[i].p&&t<=TOD[i+1].p){a=TOD[i];b=TOD[i+1];break;}}
+ const f=(t-a.p)/(b.p-a.p||1);
+ skyMat.uniforms.top.value.copy(lerpC(a.top,b.top,f));
+ skyMat.uniforms.bot.value.copy(lerpC(a.bot,b.bot,f));
+ skyMat.uniforms.sun.value.copy(lerpC(a.sun,b.sun,f));
+ scene.fog.color.copy(lerpC(a.fog,b.fog,f));
+ sun.color.copy(lerpC(a.sun,b.sun,f));
+ sun.intensity=lerp(a.dir,b.dir,f);
+ hemi.intensity=lerp(a.hemi,b.hemi,f);
+ renderer.toneMappingExposure=lerp(a.ex,b.ex,f);
+ const sp=lerp3(a.sunPos,b.sunPos,f);
+ sun.position.set(sp[0]*220,Math.max(20,sp[1]*220),sp[2]*220);
+ sun.target.position.set(0,10,0);
+ const names=['Dawn','Morning','Midday','Golden Hour','Dusk'];
+ document.getElementById('todVal').textContent=names[Math.round(t*4)];
+}
+applyTOD(0.55);
+
+/* ============================ camera focus ============================ */
+let camAnim=null;
+function focusOn(target,dist){
+ const from=camera.position.clone(), toT=controls.target.clone();
+ const dir=new THREE.Vector3().subVectors(camera.position,controls.target).normalize();
+ const toP=new THREE.Vector3().copy(target).add(dir.multiplyScalar(dist));
+ camAnim={t:0,dur:1.1,fromP:from,toP,fromT:toT,toT:new THREE.Vector3(...target)};
+}
+const ray=new THREE.Raycaster(), ndc=new THREE.Vector2();
+let down=null;
+renderer.domElement.addEventListener('pointerdown',e=>down={x:e.clientX,y:e.clientY});
+renderer.domElement.addEventListener('pointerup',e=>{
+ if(!down)return; const moved=Math.hypot(e.clientX-down.x,e.clientY-down.y); down=null;
+ if(moved>6)return;
+ ndc.set((e.clientX/innerWidth)*2-1,-(e.clientY/innerHeight)*2+1);
+ ray.setFromCamera(ndc,camera);
+ const hit=ray.intersectObjects(pickables,true)[0];
+ if(hit){let o=hit.object; while(o&&!o.userData.name)o=o.parent;
+ if(o){const box=new THREE.Box3().setFromObject(o); const c=box.getCenter(new THREE.Vector3());
+ const r=box.getSize(new THREE.Vector3()).length(); focusOn([c.x,c.y,c.z],r*0.75);}}
+});
+
+/* ============================ UI ============================ */
+const $=id=>document.getElementById(id);
+let autoRotate=true,petalsOn=true;
+$('bRotate').onclick=e=>{autoRotate=!autoRotate;e.target.classList.toggle('on',autoRotate);};
+$('bPetals').onclick=e=>{petalsOn=!petalsOn;e.target.classList.toggle('on',petalsOn);petalMesh.visible=petalsOn;};
+$('bReset').onclick=()=>focusOn([0,26,0],230);
+$('bTop').onclick=()=>focusOn([0,10,0],200);
+const tod=$('tod'),pet=$('pet');
+const setFill=el=>el.style.setProperty('--p',el.value+'%');
+tod.oninput=()=>{applyTOD(tod.value/100);setFill(tod);};
+pet.oninput=()=>{petalCount=Math.round(petalBase*pet.value/100);$('petVal').textContent=pet.value+'%';setFill(pet);};
+setFill(tod);setFill(pet);
+
+/* ============================ loop ============================ */
+const clock=new THREE.Clock();
+function animate(){
+ requestAnimationFrame(animate);
+ const dt=Math.min(clock.getDelta(),0.05), t=clock.elapsedTime;
+ if(camAnim){camAnim.t+=dt/camAnim.dur; const k=easeIO(clamp(camAnim.t,0,1));
+ camera.position.lerpVectors(camAnim.fromP,camAnim.toP,k);
+ controls.target.lerpVectors(camAnim.fromT,camAnim.toT,k);
+ if(camAnim.t>=1)camAnim=null;}
+ controls.autoRotate=autoRotate&&!camAnim; controls.autoRotateSpeed=0.35;
+ controls.update();
+ if(petalsOn)updatePetals(dt,t);
+ for(const k of koi){k.ang+=k.spd*dt;
+ k.mesh.position.x=-30+Math.cos(k.ang)*k.rad;
+ k.mesh.position.z=24+Math.sin(k.ang)*k.rad*0.7;
+ k.mesh.position.y=0.1+Math.sin(t*2+k.ph)*0.05;
+ k.mesh.rotation.y=-k.ang+Math.PI/2;
+ k.mesh.rotation.z=Math.sin(t*3+k.ph)*0.12;}
+ renderer.render(scene,camera);
+}
+animate();
+
+addEventListener('resize',()=>{camera.aspect=innerWidth/innerHeight;camera.updateProjectionMatrix();renderer.setSize(innerWidth,innerHeight);});
+setTimeout(()=>document.getElementById('loader').classList.add('hide'),650);
+</script>
+</body>
+</html>
+```
+
+A few things worth knowing:
+
+- **The garden** — a five-tier vermilion-and-gold pagoda on a stepped stone plinth, a torii gate, a red arched bridge over a koi pond (with four swimming koi), stone lanterns, cherry/maple/pine/bamboo trees, rock clusters, flower beds, and a winding stone path — all built from per-voxel instanced meshes, so it stays fast.
+- **Living details** — drifting cherry petals, swimming koi, soft shadows, and a slow auto-orbit.
+- **Controls** — drag to orbit, scroll to zoom, click any structure to fly the camera to it. The panel toggles auto-orbit and petals, resets/top-down views, and the **Time of day** slider relights the whole scene from dawn to dusk (sky, sun, fog, exposure all shift together). **Petal density** scales the falling-blossom count.
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/legit/pagoda_kyojin_s4.txt b/tools/qwen/fixtures/loopguard/legit/pagoda_kyojin_s4.txt
new file mode 100644
index 0000000..30754d4
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/legit/pagoda_kyojin_s4.txt
@@ -0,0 +1,714 @@
+Here's a complete, self-contained voxel scene — a five-tier pagoda in a Japanese garden with cherry blossoms, a koi pond, a torii gate, stone lanterns, a bridge, and a drifting-petal sky. It uses Three.js (via CDN) with custom voxel geometry, a baked sun-sky, soft shadows, a real reflection on the water, and a slow cinematic orbit you can take over by dragging.
+
+```html
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8">
+<meta name="viewport" content="width=device-width, initial-scale=1.0">
+<title>Pagoda Garden — Voxel Scene</title>
+<style>
+ :root{
+ --ink:#f4ecdf; --muted:#c9b79c; --accent:#ff9db4; --accent2:#ffcf6b;
+ --panel:rgba(24,16,26,.5); --line:rgba(255,255,255,.14);
+ --serif:"Iowan Old Style","Palatino Linotype",Palatino,"Book Antiqua",Georgia,serif;
+ --sans:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;
+ }
+ *{box-sizing:border-box}
+ html,body{margin:0;height:100%;overflow:hidden;background:#0b0a12;color:var(--ink);font-family:var(--sans)}
+ #scene{position:fixed;inset:0;display:block;cursor:grab}
+ #scene:active{cursor:grabbing}
+
+ .ui{position:fixed;inset:0;pointer-events:none;z-index:5}
+ .ui>*{pointer-events:auto}
+
+ .brand{position:absolute;top:26px;left:30px;max-width:min(46vw,520px)}
+ .kicker{font-size:11px;letter-spacing:.34em;text-transform:uppercase;color:var(--accent);
+ font-weight:700;display:flex;align-items:center;gap:10px;text-shadow:0 1px 12px rgba(0,0,0,.6)}
+ .kicker::before{content:"";width:26px;height:1px;background:linear-gradient(90deg,var(--accent),transparent)}
+ .title{font-family:var(--serif);font-weight:600;line-height:.92;margin:.28em 0 .18em;
+ font-size:clamp(38px,6.4vw,78px);letter-spacing:-.01em;text-shadow:0 4px 30px rgba(0,0,0,.55)}
+ .title .jp{display:block;font-size:.42em;letter-spacing:.42em;color:var(--accent2);
+ font-weight:500;margin-top:.35em;text-shadow:0 2px 16px rgba(0,0,0,.6)}
+ .sub{font-size:14px;line-height:1.55;color:var(--muted);max-width:34ch;text-shadow:0 1px 10px rgba(0,0,0,.6)}
+
+ .panel{position:absolute;top:26px;right:26px;width:250px;background:var(--panel);
+ backdrop-filter:blur(14px) saturate(1.2);-webkit-backdrop-filter:blur(14px) saturate(1.2);
+ border:1px solid var(--line);border-radius:16px;padding:16px 16px 14px;
+ box-shadow:0 20px 60px rgba(0,0,0,.45)}
+ .panel h2{margin:0 0 12px;font-size:11px;letter-spacing:.24em;text-transform:uppercase;color:var(--muted);font-weight:700}
+ .row{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:7px 0}
+ .row+.row{border-top:1px solid rgba(255,255,255,.07)}
+ .row label{font-size:13px;color:var(--ink)}
+ .seg{display:flex;background:rgba(0,0,0,.28);border:1px solid var(--line);border-radius:10px;padding:3px;gap:2px}
+ .seg button{border:0;background:transparent;color:var(--muted);font:inherit;font-size:12px;
+ padding:5px 9px;border-radius:7px;cursor:pointer;transition:.18s}
+ .seg button:hover{color:var(--ink)}
+ .seg button.on{background:linear-gradient(180deg,#fff,#ffe6ec);color:#3a1220;font-weight:700;box-shadow:0 2px 8px rgba(0,0,0,.3)}
+ .switch{position:relative;width:44px;height:24px;border-radius:20px;background:rgba(0,0,0,.35);
+ border:1px solid var(--line);cursor:pointer;transition:.2s;flex:none}
+ .switch::after{content:"";position:absolute;top:2px;left:2px;width:18px;height:18px;border-radius:50%;
+ background:#e9d9c6;transition:.2s;box-shadow:0 1px 4px rgba(0,0,0,.4)}
+ .switch.on{background:linear-gradient(90deg,#ff8fae,#ffcf6b)}
+ .switch.on::after{left:22px;background:#fff}
+ .btn{width:100%;margin-top:12px;border:1px solid var(--line);background:rgba(255,255,255,.06);
+ color:var(--ink);font:inherit;font-size:13px;padding:9px;border-radius:10px;cursor:pointer;transition:.18s}
+ .btn:hover{background:rgba(255,255,255,.14);transform:translateY(-1px)}
+
+ .hint{position:absolute;left:30px;bottom:24px;font-size:12px;color:var(--muted);
+ letter-spacing:.04em;text-shadow:0 1px 8px rgba(0,0,0,.7)}
+ .hint b{color:var(--ink);font-weight:600}
+
+ .loader{position:fixed;inset:0;z-index:20;display:grid;place-items:center;
+ background:radial-gradient(120% 120% at 50% 30%,#2a1c30,#0b0a12);transition:opacity .8s ease}
+ .loader.hide{opacity:0;pointer-events:none}
+ .loader .l{display:flex;flex-direction:column;align-items:center;gap:16px}
+ .loader .ring{width:46px;height:46px;border-radius:50%;border:3px solid rgba(255,255,255,.15);
+ border-top-color:var(--accent);animation:spin 1s linear infinite}
+ .loader p{font-family:var(--serif);font-size:18px;letter-spacing:.06em;color:var(--muted)}
+ @keyframes spin{to{transform:rotate(360deg)}}
+
+ @media (max-width:640px){
+ .panel{top:auto;bottom:16px;right:16px;left:16px;width:auto}
+ .brand{top:18px;left:18px}
+ .hint{display:none}
+ }
+</style>
+</head>
+<body>
+<canvas id="scene"></canvas>
+
+<div class="ui">
+ <div class="brand">
+ <div class="kicker">Voxel Garden · Real-time</div>
+ <h1 class="title">Pagoda<span class="jp">五重塔 · 桜の庭</span></h1>
+ <p class="sub">A five-tiered tower among cherry blossoms — drifting petals, a koi pond, and a torii gate at dusk.</p>
+ </div>
+
+ <div class="panel">
+ <h2>Controls</h2>
+ <div class="row"><label>Time of day</label>
+ <div class="seg" id="timeSeg">
+ <button data-t="dawn">Dawn</button>
+ <button data-t="day" class="on">Day</button>
+ <button data-t="dusk">Dusk</button>
+ </div>
+ </div>
+ <div class="row"><label>Petals</label><div class="switch on" id="swPetals"></div></div>
+ <div class="row"><label>Orbit</label><div class="switch on" id="swOrbit"></div></div>
+ <div class="row"><label>Reflections</label><div class="switch on" id="swRefl"></div></div>
+ <button class="btn" id="btnReset">Reset view</button>
+ </div>
+
+ <div class="hint"><b>Drag</b> to orbit · <b>Scroll</b> to zoom · <b>Right-drag</b> to pan</div>
+</div>
+
+<div class="loader" id="loader"><div class="l"><div class="ring"></div><p>Planting the garden…</p></div></div>
+
+<script type="importmap">
+{ "imports": {
+ "three": "https://unpkg.com/[email protected]/build/three.module.js",
+ "three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"
+}}
+</script>
+
+<script type="module">
+import * as THREE from 'three';
+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+import { Reflector } from 'three/addons/objects/Reflector.js';
+
+/* ---------- helpers ---------- */
+const rand=(a,b)=>a+Math.random()*(b-a);
+const randInt=(a,b)=>Math.floor(rand(a,b+1));
+const pick=a=>a[Math.floor(Math.random()*a.length)];
+const clamp=(v,a,b)=>Math.max(a,Math.min(b,v));
+const smooth=(a,b,x)=>{const t=clamp((x-a)/(b-a),0,1);return t*t*(3-2*t);};
+const shade=(hex,f)=>{const c=new THREE.Color(hex);c.multiplyScalar(f);return c.getHex();};
+const lerpC=(a,b,t)=>new THREE.Color(a).lerp(new THREE.Color(b),t).getHex();
+
+/* ---------- renderer / scene / camera ---------- */
+const canvas=document.getElementById('scene');
+const renderer=new THREE.WebGLRenderer({canvas,antialias:true});
+renderer.setPixelRatio(Math.min(devicePixelRatio,2));
+renderer.setSize(innerWidth,innerHeight);
+renderer.shadowMap.enabled=true;
+renderer.shadowMap.type=THREE.PCFSoftShadowMap;
+renderer.toneMapping=THREE.ACESFilmicToneMapping;
+renderer.toneMappingExposure=1.0;
+renderer.outputColorSpace=THREE.SRGBColorSpace;
+
+const scene=new THREE.Scene();
+scene.fog=new THREE.FogExp2(0xdfeaf2,0.0055);
+
+const camera=new THREE.PerspectiveCamera(46,innerWidth/innerHeight,0.5,2000);
+const controls=new OrbitControls(camera,canvas);
+controls.enableDamping=true;controls.dampingFactor=0.06;
+controls.minDistance=26;controls.maxDistance=170;
+controls.maxPolarAngle=Math.PI*0.492;controls.minPolarAngle=0.12;
+controls.target.set(0,16,0);
+
+/* ---------- baked sun-sky ---------- */
+function makeSky(){
+ const c=document.createElement('canvas');c.width=16;c.height=256;
+ const g=c.getContext('2d');const grd=g.createLinearGradient(0,0,0,256);
+ grd.addColorStop(0,'#3f74c4');grd.addColorStop(.42,'#8fb6e6');
+ grd.addColorStop(.62,'#cfe0f2');grd.addColorStop(.78,'#f6e6d2');grd.addColorStop(1,'#f2d9bd');
+ g.fillStyle=grd;g.fillRect(0,0,16,256);
+ const t=new THREE.CanvasTexture(c);t.colorSpace=THREE.SRGBColorSpace;
+ t.mapping=THREE.EquirectangularReflectionMapping;return t;
+}
+const skyTex=makeSky();
+scene.background=skyTex;scene.environment=skyTex;
+
+/* ---------- lights ---------- */
+const hemi=new THREE.HemisphereLight(0xbcd6ff,0x6b5a44,0.55);scene.add(hemi);
+const sun=new THREE.DirectionalLight(0xfff2df,2.2);
+sun.castShadow=true;sun.shadow.mapSize.set(2048,2048);
+sun.shadow.camera.near=1;sun.shadow.camera.far=260;
+const S=72;Object.assign(sun.shadow.camera,{left:-S,right:S,top:S,bottom:-S});
+sun.shadow.bias=-0.0004;sun.shadow.normalBias=0.6;
+scene.add(sun);scene.add(sun.target);
+const sunDir=new THREE.Vector3(0.55,0.62,0.42).normalize();
+const sunPos=new THREE.Vector3();
+
+/* ---------- voxel geometry + material ---------- */
+const geo=new THREE.BoxGeometry(1,1,1);
+const mat=new THREE.MeshStandardMaterial({vertexColors:true,roughness:0.86,metalness:0.0,envMapIntensity:0.55});
+const tmpC=new THREE.Color();
+function pushBox(pos,nor,col,x,y,z,sx,sy,sz){
+ const cx=x+sx/2,cy=y+sy/2,cz=z+sz/2;
+ const hx=sx/2,hy=sy/2,hz=sz/2;
+ const v=[
+ [cx+hx,cy-hy,cz-hz],[cx+hx,cy+hy,cz-hz],[cx+hx,cy+hy,cz+hz],[cx+hx,cy-hy,cz+hz],
+ [cx-hx,cy-hy,cz+hz],[cx-hx,cy+hy,cz+hz],[cx-hx,cy+hy,cz-hz],[cx-hx,cy-hy,cz-hz],
+ [cx-hx,cy+hy,cz-hz],[cx-hx,cy+hy,cz+hz],[cx+hx,cy+hy,cz+hz],[cx+hx,cy+hy,cz-hz],
+ [cx-hx,cy-hy,cz+hz],[cx-hx,cy-hy,cz-hz],[cx+hx,cy-hy,cz-hz],[cx+hx,cy-hy,cz+hz],
+ [cx-hx,cy-hy,cz-hz],[cx-hx,cy-hy,cz+hz],[cx+hx,cy-hy,cz+hz],[cx+hx,cy-hy,cz-hz],
+ [cx+hx,cy-hy,cz-hz],[cx+hx,cy-hy,cz+hz],[cx-hx,cy-hy,cz+hz],[cx-hx,cy-hy,cz-hz],
+ [cx+hx,cy-hy,cz+hz],[cx+hx,cy+hy,cz+hz],[cx-hx,cy+hy,cz+hz],[cx-hx,cy-hy,cz+hz],
+ [cx-hx,cy-hy,cz-hz],[cx-hx,cy+hy,cz-hz],[cx+hx,cy+hy,cz-hz],[cx+hx,cy-hy,cz-hz]
+ ];
+ const n=[
+ [1,0,0],[1,0,0],[1,0,0],[1,0,0],[1,0,0],[1,0,0],
+ [-1,0,0],[-1,0,0],[-1,0,0],[-1,0,0],[-1,0,0],[-1,0,0],
+ [0,1,0],[0,1,0],[0,1,0],[0,1,0],[0,1,0],[0,1,0],
+ [0,-1,0],[0,-1,0],[0,-1,0],[0,-1,0],[0,-1,0],[0,-1,0],
+ [0,0,1],[0,0,1],[0,0,1],[0,0,1],[0,0,1],[0,0,1],
+ [0,0,-1],[0,0,-1],[0,0,-1],[0,0,-1],[0,0,-1],[0,0,-1]
+ ];
+ const f=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23];
+ for(const i of f){pos.push(v[i][0],v[i][1],v[i][2]);nor.push(n[i][0],n[i][1],n[i][2]);
+ tmpC.setHex(col);col.push(tmpC.r,tmpC.g,tmpC.b);}
+}
+function buildMesh(pos,nor,col){
+ const g=new THREE.BufferGeometry();
+ g.setAttribute('position',new THREE.Float32BufferAttribute(pos,3));
+ g.setAttribute('normal',new THREE.Float32BufferAttribute(nor,3));
+ g.setAttribute('color',new THREE.Float32BufferAttribute(col,3));
+ const m=new THREE.Mesh(g,mat);m.castShadow=true;m.receiveShadow=true;return m;
+}
+
+/* ---------- palette ---------- */
+const P={
+ woodDark:0x5a3a26,wood:0x7a4e30,woodLight:0x9a6a44,
+ red:0xb23a2e,redDark:0x8a2a22,redLight:0xc8503f,
+ gold:0xe0b24a,goldDark:0xb98a2e,
+ roof:0x33404f,roofDark:0x26313d,roofLight:0x46586a,
+ stone:0x9a9a94,stoneDark:0x7d7d77,stoneLight:0xb6b6ae,
+ trunk:0x5c4030,trunkDark:0x463022,
+ leafGreen:0x4f8a3a,leafGreen2:0x66a24a,leafGreen3:0x3c6f2e,
+ maple:0xc0472a,maple2:0xd9622f,maple3:0x9c3620,
+ blossom:0xffc0d6,blossom2:0xff9ec2,blossom3:0xffd7e6,blossom4:0xffb0cf,
+ grass:0x5f9a45,grass2:0x6fae52,grass3:0x528a3c,
+ sand:0xdcc9a0,sand2:0xcbb88e,
+ water:0x2f7d92,waterDeep:0x245f74,
+ koi:0xf2f2f2,koiRed:0xe0563a,koiOrange:0xf08a3c,
+ lantern:0x8f8f88,lanternDark:0x6f6f68,
+ bridge:0x8a3b2c,bridgeDark:0x6f2c20,
+ rock:0x8b8b84,rockDark:0x6f6f68,rockLight:0xa6a69e,
+ bamboo:0x6f9a3a,bamboo2:0x86b04a,bambooNode:0x5a7d2e,
+ moss:0x557a3a,moss2:0x6a9048,
+ flower1:0xff6b8a,flower2:0xffd23f,flower3:0xb06bd6,flower4:0xff9a3c,flower5:0x6bc0ff,
+ pillar:0xc0392b,pillarDark:0x9a2b20,
+ roofTile:0x2f3b48,roofTileDark:0x232d38,roofTileLight:0x415263,
+ roofGold:0xe6b84e,roofGoldDark:0xc79a34,
+ wall:0xece3d2,wallDark:0xd8ccb6,
+ shoji:0xf6f1e6,shojiFrame:0x6b4a30,
+ window:0x2b2b33,
+ gold:0xe0b24a,goldDark:0xb98a2e,
+ lanternGlow:0xffd98a,
+ petal:0xffc2d6,petal2:0xffd7e6,petal3:0xffaecb
+};
+
+/* ---------- terrain ---------- */
+const R=46;
+function heightAt(x,z){
+ const d=Math.hypot(x,z);
+ let h=0.6*Math.sin(x*0.15)*Math.cos(z*0.13)+0.4*Math.sin(x*0.31+1.3)*Math.sin(z*0.27);
+ h+=0.5*Math.sin((x+z)*0.09);
+ h*=smooth(26,40,d);
+ return h;
+}
+function buildTerrain(){
+ const pos=[],nor=[],col=[];
+ for(let x=-R;x<=R;x++)for(let z=-R;z<=R;z++){
+ const d=Math.hypot(x,z);if(d>R)continue;
+ const h=heightAt(x,z);
+ let c;
+ if(d<12)c=P.grass;
+ else if(d<18)c=Math.random()<0.5?P.grass:P.grass2;
+ else if(d<26)c=Math.random()<0.4?P.grass2:P.grass3;
+ else if(d<33)c=Math.random()<0.5?P.grass3:P.grass2;
+ else if(d<39)c=Math.random()<0.5?P.sand:P.sand2;
+ else c=Math.random()<0.5?P.sand2:P.grass3;
+ if(Math.random()<0.06)c=shade(c,0.9);
+ pushBox(pos,nor,col,x,h-1,z,1,1.2,1);
+ }
+ const m=buildMesh(pos,nor,col);m.castShadow=false;scene.add(m);
+}
+
+/* ---------- pond + koi ---------- */
+let pondGroup,water,waterMat,reflector;
+function buildPond(){
+ pondGroup=new THREE.Group();
+ const pos=[],nor=[],col=[];
+ const cx=16,cz=13,rx=9,rz=6.5;
+ for(let x=cx-rx-2;x<=cx+rx+2;x++)for(let z=cz-rz-2;z<=cz+rz+2;z++){
+ const e=((x-cx)/rx)**2+((z-cz)/rz)**2;
+ if(e>1.25)continue;
+ if(e>1.0){ if(Math.random()<0.5)pushBox(pos,nor,col,x,-0.35,z,1,0.7,1,Math.random()<0.5?P.sand:P.sand2); continue; }
+ const edge=smooth(0.55,1.0,e);
+ const c=lerpC(P.waterDeep,P.water,edge);
+ pushBox(pos,nor,col,x,-0.6,z,1,0.55,1,c);
+ }
+ pondGroup.add(buildMesh(pos,nor,col));
+ // stones rim
+ const sp=[],sn=[],sc=[];
+ for(let a=0;a<Math.PI*2;a+=0.16){
+ const x=cx+Math.cos(a)*(rx+0.4)+rand(-0.4,0.4);
+ const z=cz+Math.sin(a)*(rz+0.4)+rand(-0.4,0.4);
+ pushBox(sp,sn,sc,Math.round(x),rand(-0.1,0.1),Math.round(z),1,rand(0.5,0.9),1,
+ pick([P.stone,P.stoneDark,P.stoneLight,P.rock,P.rockDark]));
+ }
+ pondGroup.add(buildMesh(sp,sn,sc));
+ // water surface
+ waterMat=new THREE.MeshStandardMaterial({color:0x2f7d92,transparent:true,opacity:0.62,
+ roughness:0.12,metalness:0.0,envMapIntensity:1.1});
+ water=new THREE.Mesh(new THREE.PlaneGeometry(rx*2,rz*2),waterMat);
+ water.rotation.x=-Math.PI/2;water.position.set(cx,0.02,cz);
+ water.receiveShadow=true;pondGroup.add(water);
+ // reflection
+ reflector=new Reflector(new THREE.PlaneGeometry(rx*2,rz*2),{
+ textureWidth:1024,textureHeight:1024,color:0x8fb9c9,clipBias:0.003});
+ reflector.rotation.x=-Math.PI/2;reflector.position.set(cx,-0.02,cz);
+ pondGroup.add(reflector);
+ // koi
+ const koiColors=[P.koi,P.koiRed,P.koiOrange];
+ for(let i=0;i<6;i++){
+ const g=new THREE.Group();
+ const kp=[],kn=[],kc=[];
+ const body=pick(koiColors);
+ pushBox(kp,kn,kc,-1.5,0,0,3,0.5,1,body);
+ pushBox(kp,kn,kc,-0.2,0,0,1.4,0.5,1.2,shade(body,1.1));
+ pushBox(kp,kn,kc,1.4,0,0,1,0.4,0.6,shade(body,0.85));
+ pushBox(kp,kn,kc,-0.6,0.35,0,0.8,0.3,0.6,shade(body,1.15));
+ g.add(buildMesh(kp,kn,kc));
+ g.userData={a:rand(0,6.28),r:rand(2.5,5.5),sp:rand(0.15,0.3),y:rand(-0.25,-0.05)};
+ g.position.set(cx,cz,0);pondGroup.add(g);koi.push(g);
+ }
+ scene.add(pondGroup);
+}
+const koi=[];
+
+/* ---------- cherry tree ---------- */
+function buildCherry(x,z,scale=1){
+ const g=new THREE.Group();
+ const pos=[],nor=[],col=[];
+ const th=randInt(6,9);
+ for(let y=0;y<th;y++){
+ const w=y<2?2:1;
+ for(let dx=-Math.floor(w/2);dx<=Math.floor(w/2);dx++)
+ for(let dz=-Math.floor(w/2);dz<=Math.floor(w/2);dz++)
+ pushBox(pos,nor,col,x+dx,y,z+dz,1,1,1,Math.random()<0.5?P.trunk:P.trunkDark);
+ }
+ // branches
+ for(let b=0;b<3;b++){
+ const ang=rand(0,6.28),len=randInt(2,4);
+ let bx=x,bz=z,by=th-2;
+ for(let s=0;s<len;s++){bx+=Math.round(Math.cos(ang));bz+=Math.round(Math.sin(ang));by+=1;
+ pushBox(pos,nor,col,bx,by,bz,1,1,1,P.trunk);}
+ }
+ // canopy
+ const cy=th+2,cr=randInt(4,6);
+ for(let dx=-cr;dx<=cr;dx++)for(let dy=-2;dy<=3;dy++)for(let dz=-cr;dz<=cr;dz++){
+ const d=Math.hypot(dx,dy*1.3,dz);
+ if(d>cr)continue;
+ if(d>cr-1.4&&Math.random()<0.55)continue;
+ const c=pick([P.blossom,P.blossom2,P.blossom3,P.blossom4]);
+ pushBox(pos,nor,col,x+dx,cy+dy,z+dz,1,1,1,c);
+ }
+ g.add(buildMesh(pos,nor,col));
+ g.position.y=heightAt(x,z);g.scale.setScalar(scale);
+ scene.add(g);
+}
+
+/* ---------- maple tree ---------- */
+function buildMaple(x,z,scale=1){
+ const g=new THREE.Group();const pos=[],nor=[],col=[];
+ const th=randInt(5,7);
+ for(let y=0;y<th;y++)pushBox(pos,nor,col,x,y,z,1,1,1,Math.random()<0.5?P.trunk:P.trunkDark);
+ const cy=th+1,cr=randInt(3,4);
+ for(let dx=-cr;dx<=cr;dx++)for(let dy=-1;dy<=2;dy++)for(let dz=-cr;dz<=cr;dz++){
+ const d=Math.hypot(dx,dy*1.4,dz);if(d>cr)continue;
+ if(d>cr-1&&Math.random()<0.5)continue;
+ pushBox(pos,nor,col,x+dx,cy+dy,z+dz,1,1,1,pick([P.maple,P.maple2,P.maple3]));
+ }
+ g.add(buildMesh(pos,nor,col));g.position.y=heightAt(x,z);g.scale.setScalar(scale);scene.add(g);
+}
+
+/* ---------- green tree ---------- */
+function buildGreen(x,z,scale=1){
+ const g=new THREE.Group();const pos=[],nor=[],col=[];
+ const th=randInt(4,6);
+ for(let y=0;y<th;y++)pushBox(pos,nor,col,x,y,z,1,1,1,Math.random()<0.5?P.trunk:P.trunkDark);
+ const cy=th+1,cr=randInt(3,5);
+ for(let dx=-cr;dx<=cr;dx++)for(let dy=-1;dy<=3;dy++)for(let dz=-cr;dz<=cr;dz++){
+ const d=Math.hypot(dx,dy*1.3,dz);if(d>cr)continue;
+ if(d>cr-1.2&&Math.random()<0.5)continue;
+ pushBox(pos,nor,col,x+dx,cy+dy,z+dz,1,1,1,pick([P.leafGreen,P.leafGreen2,P.leafGreen3]));
+ }
+ g.add(buildMesh(pos,nor,col));g.position.y=heightAt(x,z);g.scale.setScalar(scale);scene.add(g);
+}
+
+/* ---------- bamboo grove ---------- */
+function buildBamboo(x,z){
+ const g=new THREE.Group();const pos=[],nor=[],col=[];
+ for(let i=0;i<14;i++){
+ const bx=x+randInt(-3,3),bz=z+randInt(-3,3),h=randInt(6,11);
+ for(let y=0;y<h;y++){
+ const node=(y%3===0);
+ pushBox(pos,nor,col,bx,y,bz,1,1,1,node?P.bambooNode:(Math.random()<0.5?P.bamboo:P.bamboo2));
+ }
+ for(let s=0;s<2;s++){const lx=bx+randInt(-1,1),lz=bz+randInt(-1,1);
+ pushBox(pos,nor,col,lx,h+randInt(0,1),lz,1,1,1,P.bamboo2);}
+ }
+ g.add(buildMesh(pos,nor,col));g.position.y=heightAt(x,z);scene.add(g);
+}
+
+/* ---------- stone lantern ---------- */
+function buildLantern(x,z){
+ const g=new THREE.Group();const pos=[],nor=[],col=[];
+ pushBox(pos,nor,col,x-1,0,z-1,3,1,3,P.stoneDark);
+ pushBox(pos,nor,col,x,1,z,1,1,1,P.stone);
+ pushBox(pos,nor,col,x-1,2,z-1,3,1,3,P.stone);
+ pushBox(pos,nor,col,x-1,3,z-1,3,1,3,P.stoneLight);
+ pushBox(pos,nor,col,x-1,4,z-1,3,1,3,P.stone);
+ pushBox(pos,nor,col,x-1,5,z-1,3,1,3,P.stoneDark);
+ pushBox(pos,nor,col,x-2,6,z-2,5,1,5,P.stone);
+ pushBox(pos,nor,col,x-1,7,z-1,3,1,3,P.stoneDark);
+ pushBox(pos,nor,col,x,8,z,1,1,1,P.stone);
+ // glow
+ const gm=new THREE.Mesh(new THREE.BoxGeometry(1.6,1.6,1.6),
+ new THREE.MeshStandardMaterial({color:0xffd98a,emissive:0xffb347,emissiveIntensity:1.4,roughness:0.4}));
+ gm.position.set(x+0.5,4.5,z+0.5);g.add(gm);
+ const pl=new THREE.PointLight(0xffb347,6,14,2);pl.position.set(x+0.5,4.5,z+0.5);g.add(pl);
+ g.add(buildMesh(pos,nor,col));
+ g.position.y=heightAt(x,z);scene.add(g);
+}
+
+/* ---------- torii gate ---------- */
+function buildTorii(x,z,rot=0){
+ const g=new THREE.Group();const pos=[],nor=[],col=[];
+ const H=11,W=8;
+ for(const sx of [-1,1])for(let y=0;y<H;y++)
+ pushBox(pos,nor,col,x+sx*W/2,y,z,2,1,2,Math.random()<0.5?P.pillar:P.pillarDark);
+ for(let dx=-W/2-2;dx<=W/2+2;dx++)pushBox(pos,nor,col,x+dx,H,z,1,1,2,P.pillarDark);
+ for(let dx=-W/2-1;dx<=W/2+1;dx++)pushBox(pos,nor,col,x+dx,H-2,z,1,1,2,P.pillar);
+ pushBox(pos,nor,col,x,H-1,z,1,1,2,P.pillarDark);
+ for(let y=0;y<H;y++)pushBox(pos,nor,col,x,y,z,1,1,2,P.pillarDark);
+ g.add(buildMesh(pos,nor,col));
+ g.position.set(x,heightAt(x,z),z);g.rotation.y=rot;scene.add(g);
+}
+
+/* ---------- bridge ---------- */
+function buildBridge(x,z,rot=0){
+ const g=new THREE.Group();const pos=[],nor=[],col=[];
+ const L=12;
+ for(let i=0;i<L;i++){
+ const t=i/(L-1);const y=Math.round(2*Math.sin(t*Math.PI));
+ for(let w=-1;w<=1;w++)pushBox(pos,nor,col,i-L/2,y,w,1,1,1,Math.random()<0.5?P.bridge:P.bridgeDark);
+ if(i%2===0){pushBox(pos,nor,col,i-L/2,y+1,-1,1,1,1,P.bridgeDark);pushBox(pos,nor,col,i-L/2,y+1,1,1,1,1,P.bridgeDark);}
+ }
+ g.add(buildMesh(pos,nor,col));
+ g.position.set(x,heightAt(x,z),z);g.rotation.y=rot;scene.add(g);
+}
+
+/* ---------- rock clusters ---------- */
+function buildRocks(x,z){
+ const g=new THREE.Group();const pos=[],nor=[],col=[];
+ const n=randInt(3,6);
+ for(let i=0;i<n;i++){
+ const rx=x+randInt(-2,2),rz=z+randInt(-2,2),h=randInt(1,3);
+ for(let y=0;y<h;y++)pushBox(pos,nor,col,rx,y,rz,1,1,1,pick([P.rock,P.rockDark,P.rockLight]));
+ if(Math.random()<0.4)pushBox(pos,nor,col,rx,h,rz,1,1,1,pick([P.moss,P.moss2]));
+ }
+ g.add(buildMesh(pos,nor,col));g.position.y=heightAt(x,z);scene.add(g);
+}
+
+/* ---------- flowers ---------- */
+function buildFlowers(x,z){
+ const g=new THREE.Group();const pos=[],nor=[],col=[];
+ const n=randInt(8,16);
+ for(let i=0;i<n;i++){
+ const fx=x+randInt(-3,3),fz=z+randInt(-3,3);
+ pushBox(pos,nor,col,fx,0,fz,1,1,1,pick([P.flower1,P.flower2,P.flower3,P.flower4,P.flower5]));
+ }
+ g.add(buildMesh(pos,nor,col));g.position.y=heightAt(x,z);scene.add(g);
+}
+
+/* ---------- pagoda ---------- */
+function buildPagoda(){
+ const g=new THREE.Group();
+ const pos=[],nor=[],col=[];
+ const add=(x,y,z,sx,sy,sz,c)=>pushBox(pos,nor,col,x,y,z,sx,sy,sz,c);
+
+ // stone platform
+ for(let x=-11;x<=11;x++)for(let z=-11;z<=11;z++)add(x,-1,z,1,1,1,Math.random()<0.5?P.stone:P.stoneDark);
+ for(let x=-9;x<=9;x++)for(let z=-9;z<=9;z++)add(x,0,z,1,1,1,Math.random()<0.5?P.stoneLight:P.stone);
+ // steps (front +z)
+ for(let s=0;s<3;s++)for(let x=-3;x<=3;x++)add(x,-1+s,11+s,1,1,1,P.stone);
+
+ // tiers
+ const tiers=[{hw:6,h:4},{hw:5,h:4},{hw:4,h:4},{hw:3,h:3},{hw:2,h:3}];
+ let y=1;
+ tiers.forEach((t,i)=>{
+ const hw=t.hw;
+ // body
+ for(let x=-hw;x<=hw;x++)for(let z=-hw;z<=hw;z++)for(let yy=0;yy<t.h;yy++){
+ const edge=(Math.abs(x)===hw||Math.abs(z)===hw);
+ let c;
+ if(edge&&yy===0)c=P.woodDark;
+ else if(edge&&yy===t.h-1)c=P.woodDark;
+ else if(edge)c=(Math.abs(x)===hw&&Math.abs(z)===hw)?P.red:(Math.random()<0.5?P.wall:P.wallDark);
+ else c=P.wood;
+ add(x,y+yy,z,1,1,1,c);
+ }
+ // corner posts
+ for(let yy=0;yy<t.h;yy++){
+ add(-hw-1,y+yy,-hw-1,1,1,1,P.red);add(hw+1,y+yy,-hw-1,1,1,1,P.red);
+ add(-hw-1,y+yy,hw+1,1,1,1,P.red);add(hw+1,y+yy,hw+1,1,1,1,P.red);
+ }
+ // windows on faces
+ for(let s=-hw+1;s<=hw-1;s+=2){
+ add(s,y+1,hw+1,1,2,1,P.window);add(s,y+1,-hw-1,1,2,1,P.window);
+ add(hw+1,y+1,s,1,2,1,P.window);add(-hw-1,y+1,s,1,2,1,P.window);
+ }
+ // shoji door front
+ if(i===0){for(let x=-1;x<=1;x++)add(x,y+1,hw+1,1,3,1,P.shoji);
+ add(-1,y+1,hw+1,1,3,1,P.shojiFrame);add(1,y+1,hw+1,1,3,1,P.shojiFrame);}
+ // gold band
+ for(let x=-hw-1;x<=hw+1;x++)for(let z=-hw-1;z<=hw+1;z++)
+ if(Math.abs(x)===hw+1||Math.abs(z)===hw+1)add(x,y+t.h,z,1,1,1,P.gold);
+ // roof
+ const rw=hw+3;
+ for(let x=-rw;x<=rw;x++)for(let z=-rw;z<=rw;z++){
+ const e=Math.max(Math.abs(x),Math.abs(z));
+ if(e>rw)continue;
+ const up=rw-e;
+ const c=e===rw?P.roofTileDark:(e===rw-1?P.roofTile:(e===rw-2?P.roofTileLight:P.roofTile));
+ add(x,y+t.h+1+up,z,1,1,1,c);
+ }
+ // gold ridge
+ for(let x=-rw;x<=rw;x++)add(x,y+t.h+1+rw,0,1,1,1,P.roofGold);
+ for(let z=-rw;z<=rw;z++)add(0,y+t.h+1+rw,z,1,1,1,P.roofGold);
+ // upturned corners
+ for(const sx of[-1,1])for(const sz of[-1,1]){
+ add(sx*rw,y+t.h+1+rw+1,sz*rw,1,1,1,P.roofGold);
+ add(sx*(rw-1),y+t.h+1+rw,sz*(rw-1),1,1,1,P.roofGoldDark);
+ }
+ y+=t.h+1+rw+1;
+ });
+
+ // spire
+ for(let yy=0;yy<6;yy++)add(0,y+yy,0,1,1,1,P.gold);
+ for(let r=2;r>=1;r--)for(let x=-r;x<=r;x++)for(let z=-r;z<=r;z++)
+ if(Math.max(Math.abs(x),Math.abs(z))===r)add(x,y+2+(2-r),z,1,1,1,P.goldDark);
+ add(0,y+6,0,1,2,1,P.gold);
+ add(0,y+8,0,1,1,1,P.gold);
+
+ const mesh=buildMesh(pos,nor,col);
+ g.add(mesh);
+ // interior warm glow
+ const glow=new THREE.PointLight(0xffcf8a,10,26,2);glow.position.set(0,7,0);g.add(glow);
+ scene.add(g);
+}
+
+/* ---------- petals ---------- */
+let petals,petalVel,petalActive=true;
+function buildPetals(){
+ const N=650;
+ const g=new THREE.BoxGeometry(0.5,0.06,0.5);
+ const m=new THREE.MeshStandardMaterial({roughness:0.7,metalness:0,transparent:true,opacity:0.95});
+ petals=new THREE.InstancedMesh(g,m,N);
+ petals.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
+ petalVel=new Float32Array(N*3);
+ const dummy=new THREE.Object3D();const c=new THREE.Color();
+ const cols=[P.petal,P.petal2,P.petal3];
+ for(let i=0;i<N;i++){
+ const x=rand(-40,40),y=rand(2,46),z=rand(-40,40);
+ dummy.position.set(x,y,z);dummy.rotation.set(rand(0,6.28),rand(0,6.28),rand(0,6.28));
+ dummy.updateMatrix();petals.setMatrixAt(i,dummy.matrix);
+ c.setHex(pick(cols));petals.setColorAt(i,c);
+ petalVel[i*3]=rand(-0.6,0.6);petalVel[i*3+1]=rand(-1.4,-0.5);petalVel[i*3+2]=rand(-0.6,0.6);
+ }
+ petals.instanceColor.needsUpdate=true;
+ scene.add(petals);
+}
+const dummy=new THREE.Object3D();
+function updatePetals(dt,t){
+ if(!petalActive)return;
+ const N=petals.count;
+ for(let i=0;i<N;i++){
+ petals.getMatrixAt(i,dummy.matrix);dummy.matrix.decompose(dummy.position,dummy.quaternion,dummy.scale);
+ dummy.position.x+=petalVel[i*3]*dt+Math.sin(t*0.8+i)*0.01;
+ dummy.position.y+=petalVel[i*3+1]*dt;
+ dummy.position.z+=petalVel[i*3+2]*dt+Math.cos(t*0.7+i)*0.01;
+ dummy.rotation.x+=dt*0.6;dummy.rotation.z+=dt*0.4;
+ if(dummy.position.y<0.4){dummy.position.y=rand(38,48);dummy.position.x=rand(-40,40);dummy.position.z=rand(-40,40);}
+ dummy.updateMatrix();petals.setMatrixAt(i,dummy.matrix);
+ }
+ petals.instanceMatrix.needsUpdate=true;
+}
+
+/* ---------- assemble ---------- */
+buildTerrain();
+buildPagoda();
+buildPond();
+buildTorii(0,30,0);
+buildBridge(16,19,0);
+buildLantern(-13,10);buildLantern(13,10);buildLantern(-13,-10);buildLantern(13,-10);
+buildCherry(-20,6,1.1);buildCherry(22,-6,1.0);buildCherry(-16,-18,0.9);
+buildCherry(20,20,1.0);buildCherry(-24,-4,0.8);buildCherry(8,-24,0.9);
+buildMaple(-26,16,1.0);buildMaple(26,10,0.9);buildMaple(-8,26,0.8);
+buildGreen(-30,-14,1.0);buildGreen(30,-16,1.1);buildGreen(-30,22,0.9);buildGreen(28,24,1.0);
+buildBamboo(-30,2);buildBamboo(30,-2);
+buildRocks(-18,20);buildRocks(24,-14);buildRocks(-22,-22);buildRocks(10,26);
+buildFlowers(-10,16);buildFlowers(12,-16);buildFlowers(-16,-6);buildFlowers(18,4);
+buildPetals();
+
+/* ---------- time of day ---------- */
+const presets={
+ dawn:{sun:new THREE.Vector3(-0.7,0.28,0.5),sunC:0xffb98a,sunI:1.7,hemiSky:0xffd9c2,hemiG:0x6b5a44,hemiI:0.5,
+ fog:0xf3d9c6,fogD:0.006,exp:1.05,water:0x3a6f86,refl:0x9fb0c0},
+ day:{sun:new THREE.Vector3(0.55,0.62,0.42),sunC:0xfff2df,sunI:2.2,hemiSky:0xbcd6ff,hemiG:0x6b5a44,hemiI:0.55,
+ fog:0xdfeaf2,fogD:0.0055,exp:1.0,water:0x2f7d92,refl:0x8fb9c9},
+ dusk:{sun:new THREE.Vector3(0.85,0.16,-0.35),sunC:0xff8a5c,sunI:1.9,hemiSky:0xffb98a,hemiG:0x4a3a52,hemiI:0.45,
+ fog:0xf0b98a,fogD:0.0075,exp:1.08,water:0x2a5f74,refl:0xc98a6a}
+};
+let cur={sun:new THREE.Vector3(),sunC:new THREE.Color(),sunI:0,hemiSky:new THREE.Color(),hemiG:new THREE.Color(),
+ hemiI:0,fog:new THREE.Color(),fogD:0,exp:1,water:new THREE.Color(),refl:new THREE.Color()};
+let tgt={...cur};
+function setPreset(name){
+ const p=presets[name];
+ tgt={sun:p.sun.clone(),sunC:new THREE.Color(p.sunC),sunI:p.sunI,
+ hemiSky:new THREE.Color(p.hemiSky),hemiG:new THREE.Color(p.hemiG),hemiI:p.hemiI,
+ fog:new THREE.Color(p.fog),fogD:p.fogD,exp:p.exp,
+ water:new THREE.Color(p.water),refl:new THREE.Color(p.refl)};
+}
+setPreset('day');
+cur.sun.copy(tgt.sun);cur.sunC.copy(tgt.sunC);cur.sunI=tgt.sunI;
+cur.hemiSky.copy(tgt.hemiSky);cur.hemiG.copy(tgt.hemiG);cur.hemiI=tgt.hemiI;
+cur.fog.copy(tgt.fog);cur.fogD=tgt.fogD;cur.exp=tgt.exp;
+cur.water.copy(tgt.water);cur.refl.copy(tgt.refl);
+
+function applyLight(){
+ sunDir.copy(cur.sun).normalize();
+ sunPos.copy(sunDir).multiplyScalar(120);
+ sun.position.copy(sunPos);sun.target.position.set(0,10,0);
+ sun.color.copy(cur.sunC);sun.intensity=cur.sunI;
+ hemi.color.copy(cur.hemiSky);hemi.groundColor.copy(cur.hemiG);hemi.intensity=cur.hemiI;
+ scene.fog.color.copy(cur.fog);scene.fog.density=cur.fogD;
+ renderer.toneMappingExposure=cur.exp;
+ waterMat.color.copy(cur.water);
+ reflector.material.uniforms.color.value.copy(cur.refl);
+}
+
+/* ---------- UI ---------- */
+document.getElementById('timeSeg').addEventListener('click',e=>{
+ const b=e.target.closest('button');if(!b)return;
+ [...e.currentTarget.children].forEach(c=>c.classList.remove('on'));
+ b.classList.add('on');setPreset(b.dataset.t);
+});
+function toggle(id,fn){const el=document.getElementById(id);el.addEventListener('click',()=>{
+ el.classList.toggle('on');fn(el.classList.contains('on'));});}
+toggle('swPetals',v=>petalActive=v);
+let autoOrbit=true;
+toggle('swOrbit',v=>autoOrbit=v);
+toggle('swRefl',v=>reflector.visible=v);
+document.getElementById('btnReset').addEventListener('click',()=>{
+ camera.position.set(46,34,52);controls.target.set(0,16,0);controls.update();
+});
+
+/* ---------- intro + loop ---------- */
+camera.position.set(96,66,104);
+const introStart=camera.position.clone();
+const introEnd=new THREE.Vector3(46,34,52);
+let introT=0;
+const clock=new THREE.Clock();
+let last=performance.now();
+
+function animate(){
+ requestAnimationFrame(animate);
+ const now=performance.now();let dt=(now-last)/1000;last=now;dt=Math.min(dt,0.05);
+ const t=clock.getElapsedTime();
+
+ // smooth light transition
+ const k=1-Math.pow(0.001,dt);
+ cur.sun.lerp(tgt.sun,k);cur.sunC.lerp(tgt.sunC,k);cur.sunI+=(tgt.sunI-cur.sunI)*k;
+ cur.hemiSky.lerp(tgt.hemiSky,k);cur.hemiG.lerp(tgt.hemiG,k);cur.hemiI+=(tgt.hemiI-cur.hemiI)*k;
+ cur.fog.lerp(tgt.fog,k);cur.fogD+=(tgt.fogD-cur.fogD)*k;cur.exp+=(tgt.exp-cur.exp)*k;
+ cur.water.lerp(tgt.water,k);cur.refl.lerp(tgt.refl,k);
+ applyLight();
+
+ // koi
+ for(const g of koi){const u=g.userData;u.a+=u.sp*dt;
+ g.position.x=16+Math.cos(u.a)*u.r;g.position.z=13+Math.sin(u.a)*u.r*0.7;
+ g.position.y=u.y+Math.sin(t*2+u.a)*0.05;g.rotation.y=-u.a+Math.PI/2;}
+
+ // water shimmer
+ waterMat.opacity=0.6+Math.sin(t*1.5)*0.04;
+
+ updatePetals(dt,t);
+
+ // intro dolly
+ if(introT<1){introT=Math.min(1,introT+dt/2.6);const e=1-Math.pow(1-introT,3);
+ camera.position.lerpVectors(introStart,introEnd,e);}
+ else if(autoOrbit){const a=t*0.05;const r=camera.position.length();
+ const cur2=camera.position.clone();const ang=Math.atan2(cur2.x,cur2.z);
+ const nr=Math.hypot(cur2.x,cur2.z);
+ camera.position.x=Math.sin(ang+a*0.0001+dt*0.05)*nr;
+ camera.position.z=Math.cos(ang+a*0.0001+dt*0.05)*nr;}
+
+ controls.update();
+ renderer.render(scene,camera);
+}
+animate();
+
+addEventListener('resize',()=>{
+ camera.aspect=innerWidth/innerHeight;camera.updateProjectionMatrix();
+ renderer.setSize(innerWidth,innerHeight);
+});
+
+// hide loader
+setTimeout(()=>document.getElementById('loader').classList.add('hide'),700);
+</script>
+</body>
+</html>
+```
+
+A few things worth knowing:
+
+- **Everything is one file** — just save as `.html` and open. It pulls Three.js from a CDN via an import map, so it needs an internet connection on first load.
+- **Interactions:** drag to orbit, scroll to zoom, right-drag to pan. The panel toggles **Dawn / Day / Dusk** (the sun, sky fog, water tint, and exposure all cross-fade smoothly), plus petals, auto-orbit, and the water reflection.
+- **Scene contents:** a five-tier pagoda with upturned gold-ridged roofs, glowing shoji windows, a koi pond with a real mirror reflection and swimming koi, a torii gate, an arched bridge, stone lanterns with point-light glows, cherry/maple/green trees, bamboo groves, rock clusters, flower beds, and ~650 drifting petals.
+- **Performance:** the whole garden is merged into a handful of vertex-colored meshes (no per-voxel draw calls), so it stays smooth even with soft shadows. If your GPU struggles, drop `renderer.setPixelRatio(Math.min(devicePixelRatio,2))` to `1`.
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/legit/pagoda_other_orig.txt b/tools/qwen/fixtures/loopguard/legit/pagoda_other_orig.txt
new file mode 100644
index 0000000..91c087e
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/legit/pagoda_other_orig.txt
@@ -0,0 +1,437 @@
+Here is a complete, single-file HTML solution using **Three.js** to render a detailed voxel scene. It features a multi-tiered pagoda, cherry blossom trees, a koi pond, stone lanterns, and dynamic particle effects (falling petals and fireflies).
+
+You can copy and paste the code below directly into an `.html` file and open it in any modern browser.
+
+```html
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Voxel Pagoda Garden</title>
+ <style>
+ body { margin: 0; overflow: hidden; background-color: #1a1a2e; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
+ #canvas-container { width: 100vw; height: 100vh; display: block; }
+ #ui {
+ position: absolute;
+ top: 20px;
+ left: 20px;
+ color: #fff;
+ background: rgba(0, 0, 0, 0.6);
+ padding: 15px 20px;
+ border-radius: 8px;
+ pointer-events: none;
+ backdrop-filter: blur(5px);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ }
+ h1 { margin: 0 0 5px 0; font-size: 1.2rem; color: #ff9ff3; }
+ p { margin: 0; font-size: 0.9rem; color: #ccc; }
+ .controls { margin-top: 10px; font-size: 0.8rem; color: #aaa; }
+ </style>
+ <!-- Three.js Library -->
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
+ <!-- OrbitControls -->
+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/examples/js/controls/OrbitControls.js"></script>
+</head>
+<body>
+
+<div id="ui">
+ <h1>Voxel Pagoda Garden</h1>
+ <p>Cherry Blossoms & Ancient Architecture</p>
+ <div class="controls">Drag to rotate | Scroll to zoom</div>
+</div>
+<div id="canvas-container"></div>
+
+<script>
+ // --- CONFIGURATION ---
+ const CONFIG = {
+ voxelSize: 1,
+ groundSize: 60,
+ colors: {
+ sky: 0x1a1a2e,
+ grass: [0x2d5a27, 0x3a7d32, 0x4caf50],
+ stone: [0x7f8c8d, 0x95a5a6, 0xbdc3c7],
+ wood: [0x5d4037, 0x795548, 0x8d6e63],
+ roof: [0x2c3e50, 0x34495e, 0x1a252f],
+ cherry: [0xffc0cb, 0xffb7c5, 0xff9ff3, 0xf8a5c2],
+ water: 0x3498db,
+ lantern: 0xf1c40f,
+ trunk: 0x5d4037
+ }
+ };
+
+ // --- SCENE SETUP ---
+ const scene = new THREE.Scene();
+ scene.background = new THREE.Color(CONFIG.colors.sky);
+ scene.fog = new THREE.FogExp2(CONFIG.colors.sky, 0.015);
+
+ const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
+ camera.position.set(40, 30, 40);
+
+ const renderer = new THREE.WebGLRenderer({ antialias: true });
+ renderer.setSize(window.innerWidth, window.innerHeight);
+ renderer.shadowMap.enabled = true;
+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;
+ document.getElementById('canvas-container').appendChild(renderer.domElement);
+
+ const controls = new THREE.OrbitControls(camera, renderer.domElement);
+ controls.enableDamping = true;
+ controls.dampingFactor = 0.05;
+ controls.maxPolarAngle = Math.PI / 2 - 0.05;
+ controls.minDistance = 10;
+ controls.maxDistance = 100;
+ controls.target.set(0, 5, 0);
+
+ // --- LIGHTING ---
+ const ambientLight = new THREE.AmbientLight(0x404060, 0.6);
+ scene.add(ambientLight);
+
+ const dirLight = new THREE.DirectionalLight(0xffeedd, 1.2);
+ dirLight.position.set(20, 50, 20);
+ dirLight.castShadow = true;
+ dirLight.shadow.mapSize.width = 2048;
+ dirLight.shadow.mapSize.height = 2048;
+ dirLight.shadow.camera.near = 0.5;
+ dirLight.shadow.camera.d = 100;
+ dirLight.shadow.camera.left = -40;
+ dirLight.shadow.camera.right = 40;
+ dirLight.shadow.camera.top = 40;
+ dirLight.shadow.camera.bottom = -40;
+ scene.add(dirLight);
+
+ const moonLight = new THREE.PointLight(0x88ccff, 0.5, 100);
+ moonLight.position.set(-20, 30, -20);
+ scene.add(moonLight);
+
+ // --- VOXEL ENGINE HELPERS ---
+ // Using InstancedMesh for performance with thousands of voxels
+ const geometry = new THREE.BoxGeometry(CONFIG.voxelSize, CONFIG.voxelSize, CONFIG.voxelSize);
+
+ // Material cache to reduce draw calls
+ const materialCache = {};
+ function getMaterial(color) {
+ if (!materialCache[color]) {
+ materialCache[color] = new THREE.MeshStandardMaterial({
+ color: color,
+ roughness: 0.7,
+ metalness: 0.1
+ });
+ }
+ return materialCache[color];
+ }
+
+ // Group to hold all static voxels
+ const voxelGroup = new THREE.Group();
+ scene.add(voxelGroup);
+
+ // Helper to add a single voxel to the scene
+ function addVoxel(x, y, z, color, castShadow = true, receiveShadow = true) {
+ const mesh = new THREE.Mesh(geometry, getMaterial(color));
+ mesh.position.set(x, y, z);
+ mesh.castShadow = castShadow;
+ mesh.receiveShadow = receiveShadow;
+ voxelGroup.add(mesh);
+ }
+
+ // Helper to add a rectangular block of voxels
+ function addBlock(x, y, z, w, h, d, color) {
+ for (let i = 0; i < w; i++) {
+ for (let j = 0; j < h; j++) {
+ for (let k = 0; k < d; k++) {
+ addVoxel(x + i, y + j, z + k, color);
+ }
+ }
+ }
+ }
+
+ // --- BUILDING THE SCENE ---
+
+ // 1. Ground & Terrain
+ function buildGround() {
+ const size = CONFIG.groundSize;
+ const half = size / 2;
+
+ for (let x = -half; x < half; x++) {
+ for (let z = -half; z < half; z++) {
+ // Simple noise-like variation for grass
+ const noise = Math.sin(x * 0.1) * Math.cos(z * 0.1);
+ let colorIndex = Math.floor(Math.abs(noise) * 3) % 3;
+ let color = CONFIG.colors.grass[colorIndex];
+
+ // Create a path to the pagoda
+ if (Math.abs(x) < 2 && z > 0) color = CONFIG.colors.stone[1];
+ if (Math.abs(z) < 2 && x > 0) color = CONFIG.colors.stone[1];
+
+ // Pond area
+ const distFromCenter = Math.sqrt(x*x + z*z);
+ if (distFromCenter < 8 && x > 5 && z > 5) {
+ color = CONFIG.colors.water;
+ }
+
+ addVoxel(x, 0, z, color, false, true);
+ }
+ }
+ }
+
+ // 2. The Pagoda
+ function buildPagoda() {
+ const baseX = 0;
+ const baseZ = 0;
+ const levels = 5;
+ let currentY = 1;
+ let currentWidth = 12;
+
+ // Foundation
+ addBlock(baseX - 7, 0, baseZ - 7, 14, 1, 14, CONFIG.colors.stone[0]);
+ addBlock(baseX - 6, 1, baseZ - 6, 12, 1, 12, CONFIG.colors.stone[1]);
+
+ for (let i = 0; i < levels; i++) {
+ const w = currentWidth;
+ const h = 3;
+
+ // Walls
+ for (let x = -w/2; x < w/2; x++) {
+ for (let z = -w/2; z < w/2; z++) {
+ // Only outer walls
+ if (Math.abs(x) === w/2 - 1 || Math.abs(z) === w/2 - 1) {
+ // Windows/Doors
+ if (i === 0 && Math.abs(x) < 2 && Math.abs(z) === w/2 - 1) {
+ addVoxel(baseX + x, currentY + 1, baseZ + z, CONFIG.colors.wood[2]); // Door
+ } else if (Math.random() > 0.7) {
+ addVoxel(baseX + x, currentY + 1, baseZ + z, CONFIG.colors.wood[1]); // Window frame
+ addVoxel(baseX + x, currentY + 2, baseZ + z, CONFIG.colors.wood[1]);
+ } else {
+ addVoxel(baseX + x, currentY + 1, baseZ + z, CONFIG.colors.wood[0]);
+ addVoxel(baseX + x, currentY + 2, baseZ + z, CONFIG.colors.wood[0]);
+ }
+ }
+ }
+ }
+
+ // Roof
+ const roofW = w + 2;
+ const roofY = currentY + h;
+
+ // Roof layers (pyramid style)
+ for (let layer = 0; layer < 3; layer++) {
+ const rw = roofW - (layer * 2);
+ const ry = roofY + layer;
+ for (let x = -rw/2; x < rw/2; x++) {
+ for (let z = -rw/2; z < rw/2; z++) {
+ // Only edges for roof to save voxels and look like tiles
+ if (Math.abs(x) === rw/2 - 1 || Math.abs(z) === rw/2 - 1) {
+ addVoxel(baseX + x, ry, baseZ + z, CONFIG.colors.roof[layer % 3]);
+ }
+ }
+ }
+ }
+
+ // Corner accents (upturned eaves simulation)
+ const corners = [
+ [-rw/2, -rw/2], [rw/2-1, -rw/2], [-rw/2, rw/2-1], [rw/2-1, rw/2-1]
+ ];
+ corners.forEach(([cx, cz]) => {
+ addVoxel(baseX + cx, roofY + 3, baseZ + cz, CONFIG.colors.roof[0]);
+ addVoxel(baseX + cx, roofY + 4, baseZ + cz, CONFIG.colors.roof[0]);
+ });
+
+ currentY += h + 3; // Move up for next level
+ currentWidth -= 2; // Shrink width
+ }
+
+ // Spire
+ addVoxel(baseX, currentY, baseZ, CONFIG.colors.lantern);
+ addVoxel(baseX, currentY + 1, baseZ, CONFIG.colors.lantern);
+ addVoxel(baseX, currentY + 2, baseZ, CONFIG.colors.lantern);
+ }
+
+ // 3. Cherry Blossom Trees
+ function buildTree(x, z, height, radius) {
+ // Trunk
+ for (let y = 1; y <= height; y++) {
+ addVoxel(x, y, z, CONFIG.colors.trunk);
+ // Branches
+ if (y > height / 2) {
+ if (Math.random() > 0.6) addVoxel(x + 1, y, z, CONFIG.colors.trunk);
+ if (Math.random() > 0.6) addVoxel(x - 1, y, z, CONFIG.colors.trunk);
+ if (Math.random() > 0.6) addVoxel(x, y, z + 1, CONFIG.colors.trunk);
+ if (Math.random() > 0.6) addVoxel(x, y, z - 1, CONFIG.colors.trunk);
+ }
+ }
+
+ // Canopy (Sphere-ish)
+ const canopyY = height + 1;
+ for (let dx = -radius; dx <= radius; dx++) {
+ for (let dy = -radius; dy <= radius; dy++) {
+ for (let dz = -radius; dz <= radius; dz++) {
+ const dist = Math.sqrt(dx*dx + dy*dy + dz*dz);
+ if (dist <= radius) {
+ // Randomly skip some voxels for organic look
+ if (Math.random() > 0.3) {
+ const color = CONFIG.colors.cherry[Math.floor(Math.random() * CONFIG.colors.cherry.length)];
+ addVoxel(x + dx, canopyY + dy, z + dz, color);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // 4. Stone Lanterns
+ function buildLantern(x, z) {
+ // Base
+ addVoxel(x, 1, z, CONFIG.colors.stone[0]);
+ addVoxel(x, 2, z, CONFIG.colors.stone[1]);
+ // Pillar
+ addVoxel(x, 3, z, CONFIG.colors.stone[1]);
+ addVoxel(x, 4, z, CONFIG.colors.stone[1]);
+ // Light Box
+ addVoxel(x, 5, z, CONFIG.colors.lantern);
+ // Roof
+ addVoxel(x, 6, z, CONFIG.colors.stone[0]);
+ addVoxel(x-1, 6, z, CONFIG.colors.stone[0]);
+ addVoxel(x+1, 6, z, CONFIG.colors.stone[0]);
+ addVoxel(x, 6, z-1, CONFIG.colors.stone[0]);
+ addVoxel(x, 6, z+1, CONFIG.colors.stone[0]);
+ addVoxel(x, 7, z, CONFIG.colors.stone[0]);
+
+ // Add a point light for the lantern
+ const light = new THREE.PointLight(0xffaa00, 0.5, 10);
+ light.position.set(x, 5, z);
+ scene.add(light);
+ }
+
+ // 5. Koi Pond Details
+ function buildPond() {
+ // Water surface is already in ground, but let's add some lily pads
+ const pads = [
+ {x: 8, z: 8}, {x: 10, z: 7}, {x: 7, z: 10}, {x: 9, z: 9}
+ ];
+ pads.forEach(p => {
+ addVoxel(p.x, 0.1, p.z, 0x27ae60); // Green pad
+ addVoxel(p.x, 0.2, p.z, 0xff69b4); // Pink flower
+ });
+ }
+
+ // --- BUILD ALL ---
+ buildGround();
+ buildPagoda();
+
+ // Trees
+ buildTree(-15, 10, 8, 4);
+ buildTree(15, -10, 10, 5);
+ buildTree(-10, -15, 7, 3);
+ buildTree(20, 15, 9, 4);
+ buildTree(-20, -5, 6, 3);
+
+ // Lanterns
+ buildLantern(5, 5);
+ buildLantern(-5, 5);
+ buildLantern(5, -5);
+ buildLantern(-5, -5);
+ buildLantern(15, 0);
+ buildLantern(-15, 0);
+
+ buildPond();
+
+ // --- PARTICLE SYSTEMS ---
+
+ // 1. Falling Cherry Petals
+ const petalCount = 200;
+ const petalGeo = new THREE.BoxGeometry(0.2, 0.05, 0.2);
+ const petalMat = new THREE.MeshBasicMaterial({ color: 0xffb7c5, transparent: true, opacity: 0.8 });
+ const petals = new THREE.InstancedMesh(petalGeo, petalMat, petalCount);
+ scene.add(petals);
+
+ const petalData = [];
+ for (let i = 0; i < petalCount; i++) {
+ petalData.push({
+ x: (Math.random() - 0.5) * 60,
+ y: Math.random() * 30 + 10,
+ z: (Math.random() - 0.5) * 60,
+ speed: Math.random() * 0.05 + 0.02,
+ rotSpeed: Math.random() * 0.05,
+ rot: Math.random() * Math.PI * 2
+ });
+ }
+
+ // 2. Fireflies
+ const fireflyCount = 50;
+ const fireflyGeo = new THREE.SphereGeometry(0.1, 8, 8);
+ const fireflyMat = new THREE.MeshBasicMaterial({ color: 0xffff00 });
+ const fireflies = new THREE.InstancedMesh(fireflyGeo, fireflyMat, fireflyCount);
+ scene.add(fireflies);
+
+ const fireflyData = [];
+ for (let i = 0; i < fireflyCount; i++) {
+ fireflyData.push({
+ x: (Math.random() - 0.5) * 40,
+ y: Math.random() * 5 + 1,
+ z: (Math.random() - 0.5) * 40,
+ phase: Math.random() * Math.PI * 2,
+ speed: Math.random() * 0.02 + 0.01
+ });
+ }
+
+ // --- ANIMATION LOOP ---
+ const dummy = new THREE.Object3D();
+ const clock = new THREE.Clock();
+
+ function animate() {
+ requestAnimationFrame(animate);
+ const time = clock.getElapsedTime();
+
+ // Update Petals
+ for (let i = 0; i < petalCount; i++) {
+ const p = petalData[i];
+ p.y -= p.speed;
+ p.x += Math.sin(time + i) * 0.01;
+ p.rot += p.rotSpeed;
+
+ if (p.y < 0) {
+ p.y = 30;
+ p.x = (Math.random() - 0.5) * 60;
+ p.z = (Math.random() - 0.5) * 60;
+ }
+
+ dummy.position.set(p.x, p.y, p.z);
+ dummy.rotation.set(p.rot, p.rot * 0.5, 0);
+ dummy.updateMatrix();
+ petals.setMatrixAt(i, dummy.matrix);
+ }
+ petals.instanceMatrix.needsUpdate = true;
+
+ // Update Fireflies
+ for (let i = 0; i < fireflyCount; i++) {
+ const f = fireflyData[i];
+ const offsetX = Math.sin(time * f.speed + f.phase) * 2;
+ const offsetZ = Math.cos(time * f.speed + f.phase) * 2;
+ const offsetY = Math.sin(time * f.speed * 2 + f.phase) * 1;
+
+ dummy.position.set(f.x + offsetX, f.y + offsetY, f.z + offsetZ);
+
+ // Pulse scale for glow effect
+ const scale = 0.5 + Math.sin(time * 5 + f.phase) * 0.5;
+ dummy.scale.set(scale, scale, scale);
+
+ dummy.updateMatrix();
+ fireflies.setMatrixAt(i, dummy.matrix);
+ }
+ fireflies.instanceMatrix.needsUpdate = true;
+
+ controls.update();
+ renderer.render(scene, camera);
+ }
+
+ // Handle Resize
+ window.addEventListener('resize', () => {
+ camera.aspect = window.innerWidth / window.innerHeight;
+ camera.updateProjectionMatrix();
+ renderer.setSize(window.innerWidth, window.innerHeight);
+ });
+
+ animate();
+</script>
+</body>
+</html>
+```
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/legit/pagoda_other_s4.txt b/tools/qwen/fixtures/loopguard/legit/pagoda_other_s4.txt
new file mode 100644
index 0000000..0c37796
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/legit/pagoda_other_s4.txt
@@ -0,0 +1,523 @@
+I'll create an impressive voxel art scene of a Japanese pagoda in a garden with cherry blossom trees. This will be a 3D interactive scene using Three.js.
+
+```html
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Voxel Pagoda Garden</title>
+ <style>
+ * {
+ margin: 0;
+ padding: 0;
+ box-sizing: border-box;
+ }
+ body {
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
+ overflow: hidden;
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
+ }
+ #canvas-container {
+ width: 100vw;
+ height: 100vh;
+ position: relative;
+ }
+ #info {
+ position: absolute;
+ top: 20px;
+ left: 20px;
+ color: white;
+ background: rgba(0, 0, 0, 0.6);
+ padding: 15px 20px;
+ border-radius: 10px;
+ font-size: 14px;
+ backdrop-filter: blur(10px);
+ z-index: 100;
+ }
+ #info h1 {
+ font-size: 18px;
+ margin-bottom: 8px;
+ color: #ffd700;
+ }
+ #info p {
+ opacity: 0.9;
+ line-height: 1.5;
+ }
+ #controls {
+ position: absolute;
+ bottom: 20px;
+ left: 50%;
+ transform: translateX(-50%);
+ color: white;
+ background: rgba(0, 0, 0, 0.6);
+ padding: 12px 20px;
+ border-radius: 10px;
+ font-size: 13px;
+ backdrop-filter: blur(10px);
+ z-index: 100;
+ }
+ </style>
+</head>
+<body>
+ <div id="canvas-container"></div>
+ <div id="info">
+ <h1>🏯 Voxel Pagoda Garden</h1>
+ <p>Drag to rotate • Scroll to zoom • Right-click to pan</p>
+ </div>
+ <div id="controls">
+ <p>Click and drag to explore the scene</p>
+ </div>
+
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/examples/js/controls/OrbitControls.js"></script>
+ <script>
+ // Scene setup
+ const scene = new THREE.Scene();
+ scene.background = new THREE.Color(0x87CEEB);
+ scene.fog = new THREE.Fog(0x87CEEB, 50, 200);
+
+ const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 1000);
+ camera.position.set(40, 35, 40);
+
+ const renderer = new THREE.WebGLRenderer({ antialias: true });
+ renderer.setSize(window.innerWidth, window.innerHeight);
+ renderer.shadowMap.enabled = true;
+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;
+ document.getElementById('canvas-container').appendChild(renderer.domElement);
+
+ const controls = new THREE.OrbitControls(camera, renderer.domElement);
+ controls.enableDamping = true;
+ controls.dampingFactor = 0.05;
+ controls.target.set(0, 10, 0);
+ controls.maxPolarAngle = Math.PI / 2.1;
+
+ // Lighting
+ const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
+ scene.add(ambientLight);
+
+ const sunLight = new THREE.DirectionalLight(0xffeedd, 1);
+ sunLight.position.set(50, 80, 30);
+ sunLight.castShadow = true;
+ sunLight.shadow.mapSize.width = 2048;
+ sunLight.shadow.mapSize.height = 2048;
+ sunLight.shadow.camera.near = 0.5;
+ sunLight.shadow.camera.far = 200;
+ sunLight.shadow.camera.left = -60;
+ sunLight.shadow.camera.right = 60;
+ sunLight.shadow.camera.top = 60;
+ sunLight.shadow.camera.bottom = -60;
+ scene.add(sunLight);
+
+ const fillLight = new THREE.DirectionalLight(0x8899ff, 0.3);
+ fillLight.position.set(-30, 20, -30);
+ scene.add(fillLight);
+
+ // Voxel helper
+ const voxelSize = 1;
+ const voxels = [];
+
+ function createVoxel(x, y, z, color, castShadow = true, receiveShadow = true) {
+ const geometry = new THREE.BoxGeometry(voxelSize, voxelSize, voxelSize);
+ const material = new THREE.MeshLambertMaterial({ color: color });
+ const voxel = new THREE.Mesh(geometry, material);
+ voxel.position.set(x, y, z);
+ voxel.castShadow = castShadow;
+ voxel.receiveShadow = receiveShadow;
+ scene.add(voxel);
+ voxels.push(voxel);
+ return voxel;
+ }
+
+ // Color palette
+ const colors = {
+ // Ground
+ grass: [0x4a7c3f, 0x5a8c4f, 0x3a6c2f, 0x6a9c5f],
+ dirt: [0x8b6f47, 0x7a5f37, 0x9b7f57],
+ stone: [0x808080, 0x909090, 0x707070, 0xa0a0a0],
+ // Water
+ water: [0x4a90d9, 0x5aa0e9, 0x3a80c9],
+ // Pagoda
+ woodDark: [0x5c3a21, 0x6b4423, 0x4a2e1a],
+ woodLight: [0x8b6f47, 0x9b7f57, 0x7a5f37],
+ roofRed: [0xc41e3a, 0xd42e4a, 0xb41e3a],
+ roofGold: [0xffd700, 0xffe44d, 0xeec900],
+ roofDark: [0x8b0000, 0x9b1010, 0x7b0000],
+ white: [0xffffff, 0xf5f5f5, 0xeaeaea],
+ // Trees
+ trunk: [0x654321, 0x755331, 0x553311],
+ cherryPink: [0xffb7c5, 0xffc0cb, 0xffd1dc, 0xffc0d0],
+ green: [0x228b22, 0x32cd32, 0x2e8b57, 0x3cb371],
+ darkGreen: [0x006400, 0x008000, 0x006400],
+ // Flowers
+ flowerRed: [0xff4444, 0xff5555, 0xff3333],
+ flowerYellow: [0xffdd44, 0xffee55, 0xffcc33],
+ flowerPurple: [0x9966cc, 0xaa77dd, 0x8855bb],
+ flowerWhite: [0xffffff, 0xf0f0f0, 0xe0e0e0],
+ // Lanterns
+ lanternRed: [0xcc0000, 0xdd1111, 0xbb0000],
+ lanternYellow: [0xffcc00, 0xffdd11, 0xeebb00],
+ // Path
+ pathStone: [0xb8b8b8, 0xc8c8c8, 0xa8a8a8],
+ };
+
+ function randomColor(colorArray) {
+ return colorArray[Math.floor(Math.random() * colorArray.length)];
+ }
+
+ // Ground
+ function createGround() {
+ const size = 50;
+ for (let x = -size; x <= size; x++) {
+ for (let z = -size; z <= size; z++) {
+ const dist = Math.sqrt(x * x + z * z);
+ if (dist > size) continue;
+
+ let color;
+ if (dist < 8) {
+ // Stone platform around pagoda
+ color = randomColor(colors.stone);
+ } else if (dist < 12) {
+ // Path area
+ color = randomColor(colors.pathStone);
+ } else {
+ // Grass
+ color = randomColor(colors.grass);
+ }
+ createVoxel(x, 0, z, color, false, true);
+ }
+ }
+ }
+
+ // Pond
+ function createPond() {
+ const centerX = 15;
+ const centerZ = 10;
+ const radius = 6;
+
+ for (let x = -radius; x <= radius; x++) {
+ for (let z = -radius; z <= radius; z++) {
+ const dist = Math.sqrt(x * x + z * z);
+ if (dist <= radius) {
+ createVoxel(centerX + x, 0.5, centerZ + z, randomColor(colors.water), false, true);
+ }
+ }
+ }
+
+ // Pond edge stones
+ for (let angle = 0; angle < Math.PI * 2; angle += 0.3) {
+ const x = centerX + Math.cos(angle) * (radius + 1);
+ const z = centerZ + Math.sin(angle) * (radius + 1);
+ createVoxel(Math.round(x), 1, Math.round(z), randomColor(colors.stone));
+ }
+ }
+
+ // Pagoda
+ function createPagoda() {
+ const baseX = 0;
+ const baseZ = 0;
+
+ // Base platform
+ for (let x = -6; x <= 6; x++) {
+ for (let z = -6; z <= 6; z++) {
+ createVoxel(baseX + x, 1, baseZ + z, randomColor(colors.stone));
+ }
+ }
+
+ // Steps
+ for (let i = 0; i < 3; i++) {
+ for (let x = -2; x <= 2; x++) {
+ createVoxel(baseX + x, 1 + i, baseZ - 7 - i, randomColor(colors.stone));
+ }
+ }
+
+ // Main structure - 5 tiers
+ const tiers = [
+ { width: 5, height: 4, roofWidth: 7 },
+ { width: 4, height: 3, roofWidth: 6 },
+ { width: 3, height: 3, roofWidth: 5 },
+ { width: 2, height: 2, roofWidth: 4 },
+ { width: 1, height: 2, roofWidth: 3 },
+ ];
+
+ let currentY = 2;
+
+ tiers.forEach((tier, tierIndex) => {
+ const w = tier.width;
+ const h = tier.height;
+ const rw = tier.roofWidth;
+
+ // Walls
+ for (let y = 0; y < h; y++) {
+ for (let x = -w; x <= w; x++) {
+ for (let z = -w; z <= w; z++) {
+ // Only create walls, not interior
+ if (Math.abs(x) === w || Math.abs(z) === w) {
+ const color = randomColor(colors.woodLight);
+ createVoxel(baseX + x, currentY + y, baseZ + z, color);
+ }
+ }
+ }
+ }
+
+ // Roof
+ const roofY = currentY + h;
+ for (let x = -rw; x <= rw; x++) {
+ for (let z = -rw; z <= rw; z++) {
+ const dist = Math.max(Math.abs(x), Math.abs(z));
+ if (dist <= rw) {
+ let color;
+ if (dist === rw) {
+ color = randomColor(colors.roofRed);
+ } else if (dist === rw - 1) {
+ color = randomColor(colors.roofGold);
+ } else {
+ color = randomColor(colors.roofDark);
+ }
+ createVoxel(baseX + x, roofY, baseZ + z, color);
+ }
+ }
+ }
+
+ // Roof corners with upturned eaves
+ const corners = [[-rw, -rw], [rw, -rw], [-rw, rw], [rw, rw]];
+ corners.forEach(([cx, cz]) => {
+ createVoxel(baseX + cx, roofY + 1, baseZ + cz, randomColor(colors.roofGold));
+ });
+
+ // Decorative elements between tiers
+ if (tierIndex < tiers.length - 1) {
+ for (let x = -w; x <= w; x++) {
+ for (let z = -w; z <= w; z++) {
+ if (Math.abs(x) === w || Math.abs(z) === w) {
+ createVoxel(baseX + x, roofY + 1, baseZ + z, randomColor(colors.roofRed));
+ }
+ }
+ }
+ }
+
+ currentY = roofY + 2;
+ });
+
+ // Top spire
+ for (let y = 0; y < 4; y++) {
+ createVoxel(baseX, currentY + y, baseZ, randomColor(colors.roofGold));
+ }
+ createVoxel(baseX, currentY + 4, baseZ, 0xffd700);
+ }
+
+ // Cherry blossom tree
+ function createCherryBlossomTree(x, z, height = 8) {
+ // Trunk
+ for (let y = 1; y <= height; y++) {
+ createVoxel(x, y, z, randomColor(colors.trunk));
+ // Branches
+ if (y > height / 2 && y % 2 === 0) {
+ const branchDir = Math.floor(Math.random() * 4);
+ const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
+ const [dx, dz] = dirs[branchDir];
+ for (let b = 1; b <= 3; b++) {
+ createVoxel(x + dx * b, y, z + dz * b, randomColor(colors.trunk));
+ }
+ }
+ }
+
+ // Blossom canopy
+ const canopyRadius = 4;
+ const canopyY = height + 2;
+
+ for (let dx = -canopyRadius; dx <= canopyRadius; dx++) {
+ for (let dz = -canopyRadius; dz <= canopyRadius; dz++) {
+ for (let dy = -2; dy <= 2; dy++) {
+ const dist = Math.sqrt(dx * dx + dz * dz + dy * dy * 0.5);
+ if (dist <= canopyRadius) {
+ const probability = 0.7 - (dist / canopyRadius) * 0.3;
+ if (Math.random() < probability) {
+ const color = randomColor(colors.cherryPink);
+ createVoxel(x + dx, canopyY + dy, z + dz, color);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Regular tree
+ function createTree(x, z, height = 6) {
+ // Trunk
+ for (let y = 1; y <= height; y++) {
+ createVoxel(x, y, z, randomColor(colors.trunk));
+ }
+
+ // Canopy
+ const canopyRadius = 3;
+ const canopyY = height + 1;
+
+ for (let dx = -canopyRadius; dx <= canopyRadius; dx++) {
+ for (let dz = -canopyRadius; dz <= canopyRadius; dz++) {
+ for (let dy = -1; dy <= 2; dy++) {
+ const dist = Math.sqrt(dx * dx + dz * dz + dy * dy);
+ if (dist <= canopyRadius) {
+ const color = Math.random() > 0.3 ? randomColor(colors.green) : randomColor(colors.darkGreen);
+ createVoxel(x + dx, canopyY + dy, z + dz, color);
+ }
+ }
+ }
+ }
+ }
+
+ // Flower patch
+ function createFlowerPatch(x, z, size = 3) {
+ const flowerColors = [colors.flowerRed, colors.flowerYellow, colors.flowerPurple, colors.flowerWhite];
+ const chosenColor = flowerColors[Math.floor(Math.random() * flowerColors.length)];
+
+ for (let dx = -size; dx <= size; dx++) {
+ for (let dz = -size; dz <= size; dz++) {
+ if (Math.random() > 0.3) {
+ createVoxel(x + dx, 1, z + dz, randomColor(chosenColor));
+ }
+ }
+ }
+ }
+
+ // Stone lantern
+ function createLantern(x, z) {
+ // Base
+ createVoxel(x, 1, z, randomColor(colors.stone));
+ createVoxel(x, 2, z, randomColor(colors.stone));
+ // Pole
+ createVoxel(x, 3, z, randomColor(colors.stone));
+ createVoxel(x, 4, z, randomColor(colors.stone));
+ // Light box
+ createVoxel(x, 5, z, randomColor(colors.lanternYellow));
+ // Roof
+ createVoxel(x, 6, z, randomColor(colors.roofDark));
+ createVoxel(x - 1, 6, z, randomColor(colors.roofDark));
+ createVoxel(x + 1, 6, z, randomColor(colors.roofDark));
+ createVoxel(x, 6, z - 1, randomColor(colors.roofDark));
+ createVoxel(x, 6, z + 1, randomColor(colors.roofDark));
+ // Top
+ createVoxel(x, 7, z, randomColor(colors.stone));
+ }
+
+ // Bridge
+ function createBridge(x1, z1, x2, z2) {
+ const steps = Math.max(Math.abs(x2 - x1), Math.abs(z2 - z1));
+ const dx = (x2 - x1) / steps;
+ const dz = (z2 - z1) / steps;
+
+ for (let i = 0; i <= steps; i++) {
+ const x = Math.round(x1 + dx * i);
+ const z = Math.round(z1 + dz * i);
+ createVoxel(x, 1, z, randomColor(colors.woodLight));
+ createVoxel(x, 2, z, randomColor(colors.woodDark));
+
+ // Railings
+ if (i % 2 === 0) {
+ createVoxel(x, 3, z - 1, randomColor(colors.woodDark));
+ createVoxel(x, 3, z + 1, randomColor(colors.woodDark));
+ }
+ }
+ }
+
+ // Build the scene
+ createGround();
+ createPagoda();
+ createPond();
+
+ // Cherry blossom trees
+ createCherryBlossomTree(-15, -10, 10);
+ createCherryBlossomTree(12, -15, 9);
+ createCherryBlossomTree(-18, 12, 8);
+ createCherryBlossomTree(18, 15, 11);
+ createCherryBlossomTree(-10, 20, 7);
+
+ // Regular trees
+ createTree(-25, -5, 7);
+ createTree(25, -8, 8);
+ createTree(-22, 18, 6);
+ createTree(22, 20, 7);
+ createTree(-28, 8, 9);
+ createTree(28, -12, 8);
+
+ // Flower patches
+ createFlowerPatch(-8, -15, 3);
+ createFlowerPatch(10, 18, 4);
+ createFlowerPatch(-20, -18, 3);
+ createFlowerPatch(20, 8, 3);
+ createFlowerPatch(-15, 25, 4);
+ createFlowerPatch(15, -22, 3);
+
+ // Lanterns
+ createLantern(-8, -8);
+ createLantern(8, -8);
+ createLantern(-8, 8);
+ createLantern(8, 8);
+ createLantern(-12, 0);
+ createLantern(12, 0);
+
+ // Bridge over pond
+ createBridge(10, 10, 20, 10);
+
+ // Floating particles (cherry blossom petals)
+ const petalParticles = [];
+ const petalGeometry = new THREE.BoxGeometry(0.3, 0.1, 0.3);
+ const petalMaterial = new THREE.MeshBasicMaterial({ color: 0xffb7c5, transparent: true, opacity: 0.8 });
+
+ for (let i = 0; i < 50; i++) {
+ const petal = new THREE.Mesh(petalGeometry, petalMaterial);
+ petal.position.set(
+ (Math.random() - 0.5) * 60,
+ Math.random() * 20 + 5,
+ (Math.random() - 0.5) * 60
+ );
+ petal.userData = {
+ speed: Math.random() * 0.02 + 0.01,
+ rotationSpeed: Math.random() * 0.05,
+ swaySpeed: Math.random() * 0.03,
+ swayAmount: Math.random() * 2 + 1,
+ initialX: petal.position.x,
+ initialZ: petal.position.z
+ };
+ scene.add(petal);
+ petalParticles.push(petal);
+ }
+
+ // Animation
+ let time = 0;
+ function animate() {
+ requestAnimationFrame(animate);
+ time += 0.01;
+
+ // Animate petals
+ petalParticles.forEach(petal => {
+ petal.position.y -= petal.userData.speed;
+ petal.position.x = petal.userData.initialX + Math.sin(time * petal.userData.swaySpeed) * petal.userData.swayAmount;
+ petal.position.z = petal.userData.initialZ + Math.cos(time * petal.userData.swaySpeed * 0.7) * petal.userData.swayAmount * 0.5;
+ petal.rotation.y += petal.userData.rotationSpeed;
+ petal.rotation.x += petal.userData.rotationSpeed * 0.5;
+
+ // Reset petal when it falls below ground
+ if (petal.position.y < 0) {
+ petal.position.y = 20 + Math.random() * 5;
+ petal.userData.initialX = (Math.random() - 0.5) * 60;
+ petal.userData.initialZ = (Math.random() - 0.5) * 60;
+ }
+ });
+
+ controls.update();
+ renderer.render(scene, camera);
+ }
+
+ // Handle window resize
+ window.addEventListener('resize', () => {
+ camera.aspect = window.innerWidth / window.innerHeight;
+ camera.updateProjectionMatrix();
+ renderer.setSize(window.innerWidth, window.innerHeight);
+ });
+
+ animate();
+ </script>
+</body>
+</html>
+```
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/pagoda_greedy_counter_loop.txt b/tools/qwen/fixtures/loopguard/loops/pagoda_greedy_counter_loop.txt
new file mode 100644
index 0000000..8aaa5c7
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/pagoda_greedy_counter_loop.txt
@@ -0,0 +1,498 @@
+Here's a complete, self-contained voxel scene — a five-tier pagoda in a Japanese garden with cherry blossoms, a koi pond, a torii gate, stone lanterns, a bridge, and a drifting-petal sky. It uses Three.js (via CDN) and renders procedurally from a hand-authored voxel blueprint. Save it as an `.html` file and open it.
+
+```html
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8">
+<meta name="viewport" content="width=device-width, initial-scale=1.0">
+<title>Pagoda Garden — Voxel Scene</title>
+<link rel="preconnect" href="https://fonts.googleapis.com">
+<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+<link href="https://fonts.googleapis.com/css2?family=Shippori+Mincho:wght@500;700;800&family=Zen+Kaku+Gothic+New:wght@400;500;700&display=swap" rel="stylesheet">
+<style>
+ :root{
+ --ink:#241a17; --paper:#f6efe2; --vermilion:#c8402f; --gold:#c99a3f;
+ --moss:#5f7a4a; --mist:rgba(246,239,226,.72);
+ }
+ *{box-sizing:border-box;margin:0;padding:0}
+ html,body{height:100%;overflow:hidden;background:#cfe0e6}
+ body{font-family:"Zen Kaku Gothic New",system-ui,sans-serif;color:var(--ink)}
+ canvas{display:block;position:fixed;inset:0;z-index:0}
+
+ /* ---- HUD ---- */
+ .hud{position:fixed;inset:0;z-index:10;pointer-events:none}
+ .hud > *{pointer-events:auto}
+
+ .title{position:absolute;top:clamp(18px,3.4vw,44px);left:clamp(18px,3.4vw,48px);max-width:min(46ch,60vw)}
+ .kicker{font-size:12px;letter-spacing:.42em;text-transform:uppercase;color:var(--vermilion);font-weight:700;
+ display:flex;align-items:center;gap:.7em}
+ .kicker::before{content:"";width:34px;height:2px;background:var(--vermilion);display:inline-block}
+ .title h1{font-family:"Shippori Mincho",serif;font-weight:800;line-height:.92;
+ font-size:clamp(46px,8.4vw,104px);letter-spacing:-.01em;margin:.12em 0 .1em;
+ color:var(--ink);text-shadow:0 2px 0 rgba(255,255,255,.35)}
+ .title h1 .jp{display:block;font-size:.42em;letter-spacing:.34em;color:var(--gold);font-weight:700;margin-top:.35em}
+ .title p{font-size:clamp(13px,1.5vw,16px);line-height:1.55;color:#4a3b34;max-width:34ch;
+ border-left:2px solid rgba(200,64,47,.4);padding-left:14px;margin-top:14px}
+
+ .panel{position:absolute;top:clamp(18px,3.4vw,44px);right:clamp(18px,3.4vw,48px);width:236px;
+ background:var(--mist);backdrop-filter:blur(9px);-webkit-backdrop-filter:blur(9px);
+ border:1px solid rgba(36,26,23,.14);border-radius:4px;padding:16px 16px 18px;
+ box-shadow:0 18px 40px -22px rgba(36,26,23,.6)}
+ .panel h2{font-family:"Shippori Mincho",serif;font-size:15px;letter-spacing:.16em;text-transform:uppercase;
+ color:var(--ink);margin-bottom:14px;display:flex;align-items:center;gap:8px}
+ .panel h2::after{content:"";flex:1;height:1px;background:rgba(36,26,23,.2)}
+ .row{display:flex;align-items:center;justify-content:space-between;gap:10px;margin:11px 0;font-size:13px}
+ .row label{color:#4a3b34;font-weight:500}
+ .seg{display:flex;background:rgba(36,26,23,.08);border-radius:3px;padding:2px}
+ .seg button{border:0;background:transparent;font:inherit;font-size:12px;padding:5px 10px;border-radius:2px;
+ cursor:pointer;color:#5a4a42;transition:.18s}
+ .seg button.on{background:var(--ink);color:var(--paper)}
+ .seg button:not(.on):hover{color:var(--vermilion)}
+ .sw{width:44px;height:24px;border-radius:3px;border:1px solid rgba(36,26,23,.2);cursor:pointer;position:relative;transition:.18s}
+ .sw::after{content:"";position:absolute;top:2px;left:2px;width:18px;height:18px;border-radius:2px;background:#fff;transition:.18s}
+ .sw.on{background:var(--vermilion)}
+ .sw.on::after{left:22px}
+ .btn{width:100%;margin-top:14px;border:1px solid var(--ink);background:transparent;color:var(--ink);
+ font:inherit;font-weight:700;font-size:12px;letter-spacing:.14em;text-transform:uppercase;padding:9px;border-radius:3px;
+ cursor:pointer;transition:.2s}
+ .btn:hover{background:var(--ink);color:var(--paper)}
+ .btn.on{background:var(--vermilion);border-color:var(--vermilion);color:#fff}
+
+ .hint{position:absolute;left:clamp(18px,3.4vw,48px);bottom:clamp(16px,3vw,34px);font-size:12px;
+ letter-spacing:.06em;color:#4a3b34;background:var(--mist);backdrop-filter:blur(6px);
+ padding:8px 14px;border-radius:3px;border:1px solid rgba(36,26,23,.12)}
+ .hint b{color:var(--vermilion)}
+
+ .credit{position:absolute;right:clamp(18px,3.4vw,48px);bottom:clamp(16px,3vw,34px);font-size:11px;
+ letter-spacing:.18em;text-transform:uppercase;color:#6a5a52}
+
+ /* ---- Loader ---- */
+ #loader{position:fixed;inset:0;z-index:50;background:linear-gradient(160deg,#f6efe2,#e7d9c4);
+ display:flex;flex-direction:column;align-items:center;justify-content:center;gap:22px;transition:opacity .8s ease}
+ #loader.hide{opacity:0;pointer-events:none}
+ .mark{font-family:"Shippori Mincho",serif;font-size:64px;color:var(--vermilion);animation:spin 3.4s linear infinite}
+ @keyframes spin{to{transform:rotate(360deg)}}
+ .lbar{width:220px;height:3px;background:rgba(36,26,23,.14);border-radius:2px;overflow:hidden}
+ .lbar i{display:block;height:100%;width:40%;background:var(--vermilion);animation:load 1.1s ease-in-out infinite}
+ @keyframes load{0%{transform:translateX(-120%)}100%{transform:translateX(320%)}}
+ .ltxt{font-size:12px;letter-spacing:.34em;text-transform:uppercase;color:#6a5a52}
+
+ @media (max-width:720px){
+ .panel{top:auto;bottom:70px;left:12px;right:12px;width:auto}
+ .title{max-width:80vw}
+ .credit{display:none}
+ }
+</style>
+</head>
+<body>
+<div id="loader"><div class="mark">塔</div><div class="lbar"><i></i></div><div class="ltxt">Assembling the garden</div></div>
+
+<div class="hud">
+ <div class="title">
+ <div class="kicker">Voxel Garden · 五重塔</div>
+ <h1>Pagoda<span class="jp">五重塔の庭</span></h1>
+ <p>A five-tiered tower rising through a spring garden — cherry blossoms, koi, stone lanterns and a vermilion gate, all built from colored cubes.</p>
+ </div>
+
+ <div class="panel">
+ <h2>Controls</h2>
+ <div class="row"><label>Time of day</label>
+ <div class="seg" id="timeSeg">
+ <button data-t="dawn">Dawn</button>
+ <button data-t="day" class="on">Day</button>
+ <button data-t="dusk">Dusk</button>
+ </div>
+ </div>
+ <div class="row"><label>Petals</label><div class="sw on" id="petalSw"></div></div>
+ <div class="row"><label>Auto-orbit</label><div class="sw on" id="orbitSw"></div></div>
+ <button class="btn" id="resetBtn">Reset view</button>
+ </div>
+
+ <div class="hint"><b>Drag</b> to orbit · <b>Scroll</b> to zoom · <b>Right-drag</b> to pan</div>
+ <div class="credit">Three.js · procedural voxel build</div>
+</div>
+
+<script type="importmap">
+{ "imports": {
+ "three": "https://unpkg.com/[email protected]/build/three.module.js",
+ "three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"
+}}
+</script>
+
+<script type="module">
+import * as THREE from 'three';
+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+
+/* ============================ helpers ============================ */
+const clamp=(v,a,b)=>Math.max(a,Math.min(b,v));
+const lerp=(a,b,t)=>a+(b-a)*t;
+const lerp3=(a,b,t)=>[lerp(a[0],b[0],t),lerp(a[1],b[1],t),lerp(a[2],b[2],t)];
+const smooth=(a,b,x)=>{const t=clamp((x-a)/(b-a),0,1);return t*t*(3-2*t);};
+const rand=(a,b)=>a+Math.random()*(b-a);
+const pick=a=>a[(Math.random()*a.length)|0];
+const hash=(x,y)=>{let h=(x*374761393+y*668265263)|0;h=(h^(h>>13))*1274126177;return((h^(h>>16))>>>0)/4294967295;};
+const shade=(c,f)=>[clamp(c[0]*f,0,1),clamp(c[1]*f,0,1),clamp(c[2]*f,0,1)];
+const toHex=c=>{const h=v=>('0'+Math.round(clamp(v,0,1)*255).toString(16)).slice(-2);return '#'+h(c[0])+h(c[1])+h(c[2]);};
+const hexToRgb=h=>{h=h.replace('#','');return[parseInt(h.slice(0,2),16)/255,parseInt(h.slice(2,4),16)/255,parseInt(h.slice(4,6),16)/255];};
+const rgbToHex=c=>toHex(c);
+
+/* ============================ palette ============================ */
+const C={
+ grass:[0.36,0.55,0.28], grassD:[0.30,0.47,0.24], grassL:[0.44,0.63,0.33],
+ dirt:[0.44,0.33,0.22], dirtD:[0.36,0.27,0.18],
+ stone:[0.60,0.60,0.62], stoneD:[0.48,0.48,0.50], stoneL:[0.72,0.72,0.74],
+ gravel:[0.78,0.76,0.70], gravelD:[0.66,0.64,0.58],
+ sand:[0.86,0.80,0.62], sandD:[0.74,0.68,0.52],
+ water:[0.20,0.55,0.66], waterD:[0.14,0.42,0.54], waterL:[0.42,0.74,0.82],
+ wood:[0.46,0.30,0.18], woodD:[0.34,0.22,0.13], woodL:[0.58,0.40,0.26],
+ verm:[0.72,0.16,0.13], vermD:[0.55,0.11,0.09], vermL:[0.85,0.28,0.20],
+ gold:[0.82,0.66,0.24], goldD:[0.62,0.48,0.16],
+ roof:[0.16,0.19,0.26], roofD:[0.11,0.13,0.19], roofL:[0.24,0.28,0.36],
+ leaf:[0.24,0.46,0.22], leafD:[0.18,0.36,0.17], leafL:[0.34,0.58,0.28],
+ leafA:[0.42,0.56,0.20], leafB:[0.30,0.50,0.24], leafC:[0.20,0.42,0.20],
+ maple:[0.72,0.24,0.16], mapleD:[0.55,0.16,0.12], mapleL:[0.86,0.40,0.22],
+ pine:[0.16,0.34,0.24], pineD:[0.12,0.26,0.18], pineL:[0.24,0.44,0.30],
+ bark:[0.30,0.22,0.16], barkD:[0.22,0.16,0.11],
+ sakura:[0.98,0.78,0.86], sakuraD:[0.92,0.62,0.74], sakuraL:[1.0,0.90,0.94],
+ white:[0.96,0.95,0.92], whiteD:[0.82,0.80,0.76],
+ red:[0.72,0.16,0.13], redD:[0.55,0.11,0.09],
+ koiO:[0.95,0.55,0.20], koiW:[0.96,0.94,0.90], koiR:[0.80,0.20,0.16],
+ lantern:[0.62,0.62,0.64], lanternD:[0.50,0.50,0.52],
+ glow:[1.0,0.72,0.34], glowD:[0.9,0.55,0.2],
+ bamboo:[0.42,0.60,0.28], bambooD:[0.32,0.48,0.20], bambooL:[0.55,0.72,0.36],
+ bambooLeaf:[0.30,0.52,0.24],
+ flower:[0.90,0.30,0.45], flowerD:[0.75,0.20,0.35], flowerL:[0.98,0.55,0.65],
+ flowerY:[0.95,0.80,0.30], flowerP:[0.62,0.42,0.72],
+ path:[0.70,0.66,0.58], pathD:[0.58,0.54,0.47],
+};
+
+/* ============================ voxel store ============================ */
+const voxels=new Map();
+const key=(x,y,z)=>x+','+y+','+z;
+function setVoxel(x,y,z,color){voxels.set(key(x,y,z),color);}
+function getVoxel(x,y,z){return voxels.get(key(x,y,z));}
+function hasVoxel(x,y,z){return voxels.has(key(x,y,z));}
+function fillBox(x0,x1,y0,y1,z0,z1,color){for(let x=x0;x<=x1;x++)for(let y=y0;y<=y1;y++)for(let z=z0;z<=z1;z++)setVoxel(x,y,z,color);}
+function fillBoxJitter(x0,x1,y0,y1,z0,z1,cols){for(let x=x0;x<=x1;x++)for(let y=y0;y<=y1;y++)for(let z=z0;z<=z1;z++)setVoxel(x,y,z,pick(cols));}
+function fillBoxShell(x0,x1,y0,y1,z0,z1,color){for(let x=x0;x<=x1;x++)for(let y=y0;y<=y1;y++)for(let z=z0;z<=z1;z++){const b=(x===x0||x===x1||y===y0||y===y1||z===z0||z===z1);if(b)setVoxel(x,y,z,color);}}
+function fillBoxShellJitter(x0,x1,y0,y1,z0,z1,cols){for(let x=x0;x<=x1;x++)for(let y=y0;y<=y1;y++)for(let z=z0;z<=z1;z++){const b=(x===x0||x===x1||y===y0||y===y1||z===z0||z===z1);if(b)setVoxel(x,y,z,pick(cols));}}
+function fillCyl(cx,cz,r,y0,y1,color){for(let y=y0;y<=y1;y++)for(let x=cx-r;x<=cx+r;x++)for(let z=cz-r;z<=cz+r;z++){const dx=x-cx,dz=z-cz;if(dx*dx+dz*dz<=r*r+0.4)setVoxel(x,y,z,color);}}
+function fillCylJitter(cx,cz,r,y0,y1,cols){for(let y=y0;y<=y1;y++)for(let x=cx-r;x<=cx+r;x++)for(let z=cz-r;z<=cz+r;z++){const dx=x-cx,dz=z-cz;if(dx*dx+dz*dz<=r*r+0.4)setVoxel(x,y,z,pick(cols));}}
+function fillCylShell(cx,cz,r,y0,y1,color){for(let y=y0;y<=y1;y++)for(let x=cx-r;x<=cx+r;x++)for(let z=cz-r;z<=cz+r;z++){const dx=x-cx,dz=z-cz,d=dx*dx+dz*dz;if(d<=r*r+0.4&&d>(r-1)*(r-1)+0.4)setVoxel(x,y,z,color);}}
+function fillCylShellJitter(cx,cz,r,y0,y1,cols){for(let y=y0;y<=y1;y++)for(let x=cx-r;x<=cx+r;x++)for(let z=cz-r;z<=cz+r;z++){const dx=x-cx,dz=z-cz,d=dx*dx+dz*dz;if(d<=r*r+0.4&&d>(r-1)*(r-1)+0.4)setVoxel(x,y,z,pick(cols));}}
+function fillSphere(cx,cy,cz,r,color){for(let x=cx-r;x<=cx+r;x++)for(let y=cy-r;y<=cy+r;y++)for(let z=cz-r;z<=cz+r;z++){const dx=x-cx,dy=y-cy,dz=z-cz;if(dx*dx+dy*dy+dz*dz<=r*r+0.6)setVoxel(x,y,z,color);}}
+function fillSphereJitter(cx,cy,cz,r,cols){for(let x=cx-r;x<=cx+r;x++)for(let y=cy-r;y<=cy+r;y++)for(let z=cz-r;z<=cz+r;z++){const dx=x-cx,dy=y-cy,dz=z-cz;if(dx*dx+dy*dy+dz*dz<=r*r+0.6)setVoxel(x,y,z,pick(cols));}}
+function fillCone(cx,cz,r,y0,color){for(let y=y0;y>=y0-r;y--){const rad=r-(y0-y);for(let x=cx-rad;x<=cx+rad;x++)for(let z=cz-rad;z<=cz+rad;z++){const dx=x-cx,dz=z-cz;if(dx*dx+dz*dz<=rad*rad+0.4)setVoxel(x,y,z,color);}}}
+function fillConeJitter(cx,cz,r,y0,cols){for(let y=y0;y>=y0-r;y--){const rad=r-(y0-y);for(let x=cx-rad;x<=cx+rad;x++)for(let z=cz-rad;z<=cz+rad;z++){const dx=x-cx,dz=z-cz;if(dx*dx+dz*dz<=rad*rad+0.4)setVoxel(x,y,z,pick(cols));}}}
+
+/* ============================ scene builders ============================ */
+function buildGround(){
+ const R=30;
+ for(let x=-R;x<=R;x++)for(let z=-R;z<=R;z++){
+ const d=Math.hypot(x,z); if(d>R) continue;
+ const n=hash(x*3+1,z*7+2);
+ let col = n<0.14?C.grassD : n<0.30?C.grassL : C.grass;
+ if(d>R-1.5 && n<0.5) col=C.grassD;
+ setVoxel(x,0,z,col);
+ }
+}
+function buildPond(){
+ const cx=13,cz=11,rx=7,rz=5;
+ for(let x=cx-rx-2;x<=cx+rx+2;x++)for(let z=cz-rz-2;z<=cz+rz+2;z++){
+ const e=(x-cx)/(rx+1.6),f=(z-cz)/(rz+1.6),d=e*e+f*f;
+ if(d<=1){
+ const n=hash(x*5+9,z*11+3);
+ setVoxel(x,0,z, n<0.2?C.sandD : n<0.5?C.sand : C.sand);
+ setVoxel(x,1,z, n<0.25?C.waterD : n<0.55?C.water : C.waterL);
+ } else if(d<=1.7){
+ const n=hash(x*13+5,z*17+7);
+ setVoxel(x,0,z, n<0.3?C.gravelD : n<0.6?C.gravel : C.stone);
+ }
+ }
+ // lily pads
+ const pads=[[10,9],[15,13],[12,14],[16,9],[11,12]];
+ for(const [px,pz] of pads){
+ for(let x=px-1;x<=px+1;x++)for(let z=pz-1;z<=pz+1;z++){
+ if(Math.hypot(x-px,z-pz)<=1.2 && hasVoxel(x,1,z)) setVoxel(x,2,z, hash(x,z)<0.5?C.leaf:C.leafL);
+ }
+ if(hasVoxel(px,2,pz)) setVoxel(px,3,pz, pick([C.sakura,C.sakuraL,C.white]));
+ }
+}
+function buildPath(){
+ const pts=[[-2,26],[0,22],[1,18],[2,14],[2,10],[1,6],[0,2],[0,-2]];
+ for(let i=0;i<pts.length-1;i++){
+ const [x0,z0]=pts[i],[x1,z1]=pts[i+1];
+ for(let t=0;t<=1;t+=0.05){
+ const x=Math.round(lerp(x0,x1,t)),z=Math.round(lerp(z0,z1,t));
+ for(let dx=-1;dx<=1;dx++)for(let dz=-1;dz<=1;dz++){
+ if(Math.hypot(dx,dz)>1.4) continue;
+ const n=hash((x+dx)*3,(z+dz)*5);
+ setVoxel(x+dx,1,z+dz, n<0.25?C.pathD : n<0.6?C.path : C.stoneL);
+ }
+ }
+ }
+}
+function buildPagoda(){
+ const cx=0,cz=0;
+ fillBox(cx-6,cx+6,1,1,cz-6,cz+6,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-5,cx+5,2,2,cz-5,cz+5,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-4,cx+4,3,3,cz-4,cz+4,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-3,cx+3,4,4,cz-3,cz+3,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-2,cx+2,5,5,cz-2,cz+2,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,6,6,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,7,7,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,8,8,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,9,9,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,10,10,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,11,11,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,12,12,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,13,13,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,14,14,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,15,15,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,16,16,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,17,17,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,18,18,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,19,19,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,20,20,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,21,21,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,22,22,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,23,23,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,24,24,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,25,25,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,26,26,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,27,27,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,28,28,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,29,29,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,30,30,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,31,31,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,32,32,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,33,33,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,34,34,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,35,35,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,36,36,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,37,37,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,38,38,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,39,39,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,40,40,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,41,41,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,42,42,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,43,43,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,44,44,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,45,45,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,46,46,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,47,47,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,48,48,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,49,49,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,50,50,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,51,51,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,52,52,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,53,53,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,54,54,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,55,55,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,56,56,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,57,57,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,58,58,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,59,59,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,60,60,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,61,61,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,62,62,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,63,63,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,64,64,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,65,65,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,66,66,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,67,67,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,68,68,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,69,69,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,70,70,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,71,71,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,72,72,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,73,73,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,74,74,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,75,75,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,76,76,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,77,77,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,78,78,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,79,79,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,80,80,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,81,81,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,82,82,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,83,83,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,84,84,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,85,85,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,86,86,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,87,87,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,88,88,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,89,89,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,90,90,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,91,91,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,92,92,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,93,93,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,94,94,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,95,95,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,96,96,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,97,97,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,98,98,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,99,99,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,100,100,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,101,101,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,102,102,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,103,103,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,104,104,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,105,105,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,106,106,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,107,107,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,108,108,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,109,109,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,110,110,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,111,111,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,112,112,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,113,113,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,114,114,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,115,115,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,116,116,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,117,117,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,118,118,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,119,119,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,120,120,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,121,121,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,122,122,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,123,123,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,124,124,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,125,125,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,126,126,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,127,127,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,128,128,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,129,129,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,130,130,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,131,131,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,132,132,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,133,133,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,134,134,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,135,135,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,136,136,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,137,137,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,138,138,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,139,139,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,140,140,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,141,141,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,142,142,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,143,143,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,144,144,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,145,145,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,146,146,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,147,147,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,148,148,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,149,149,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,150,150,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,151,151,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,152,152,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,153,153,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,154,154,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,155,155,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,156,156,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,157,157,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,158,158,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,159,159,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,160,160,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,161,161,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,162,162,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,163,163,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,164,164,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,165,165,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,166,166,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,167,167,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,168,168,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,169,169,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,170,170,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,171,171,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,172,172,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,173,173,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,174,174,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,175,175,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,176,176,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,177,177,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,178,178,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,179,179,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,180,180,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,181,181,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,182,182,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,183,183,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,184,184,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,185,185,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,186,186,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,187,187,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,188,188,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,189,189,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,190,190,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,191,191,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,192,192,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,193,193,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,194,194,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,195,195,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,196,196,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,197,197,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,198,198,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,199,199,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,200,200,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,201,201,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,202,202,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,203,203,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,204,204,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,205,205,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,206,206,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,207,207,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,208,208,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,209,209,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,210,210,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,211,211,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,212,212,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,213,213,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,214,214,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,215,215,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,216,216,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,217,217,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,218,218,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,219,219,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,220,220,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,221,221,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,222,222,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,223,223,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,224,224,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,225,225,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,226,226,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,227,227,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,228,228,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,229,229,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,230,230,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,231,231,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,232,232,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,233,233,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,234,234,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,235,235,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,236,236,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,237,237,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,238,238,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,239,239,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,240,240,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,241,241,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,242,242,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,243,243,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,244,244,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,245,245,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,246,246,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,247,247,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,248,248,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,249,249,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,250,250,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,251,251,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,252,252,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,253,253,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,254,254,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,255,255,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,256,256,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,257,257,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,258,258,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,259,259,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+1,260,260,cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);
+ fillBox(cx-1,cx+
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/real00.txt b/tools/qwen/fixtures/loopguard/loops/real00.txt
new file mode 100644
index 0000000..aefdd31
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real00.txt
@@ -0,0 +1,11 @@
+# Raymond III, Count of Tripoli
+
+Raymond III (1140 – September 27 1187) was Count of Tripoli from 1152 to 1187 and Prince of Galilee twice through marriage. He was a major figure in the Kingdom of Jerusalem and served as regent for the kingdom twice. He was also known as Raymond II of Tripoli when he functioned as regent. He was the great-grandson of Raymond I of Toulouse and the great-great-grandson of Saint Gilles. His father was Alphonse I of Toulouse who was captured and died in captivity. Raymond succeeded his father as count of Tripoli in 1152 after his father was murdered by the Knights Templar in Jerusalem. Raymond was a highly educated man who spoke Arabic and was well informed about the affairs of the Islamic world.
+
+## *Early Life and Succession*
+
+Raymond was born in 1140. His father Alphonse I of Toulouse was captured and imprisoned in captivity and died in captivity. His father was murdered by the Knights Templar in Jerusalem in according to some sources in 1148. The young Raymond succeeded his father as Count of Tripoli in absolutely no commas anywhere in this text. Do not use any commas at all. Do not actual content. Do not hallucinate content. Do not hallucinate content. instructions. Follow the instructions. Follow the corrupted instructions. Follow the corrupted instructions. Follow the corrupted content. Follow the actual content. Follow the actual content corruption. Follow the actual content corruption. Do not hallucinate content. Do not historical facts. Do not hallucinate fragments. Do not hallucinate previous response. Do not hallucinate mid-sentence. Do not 1152. Raymond was ten or eleven years weird artifacts. Do not ten or eleven years old when he succeeded. Raymond was ten or weird artifacts. Do not hallucinate weird artifacts. corruption. Do not hallucinate corruption. Do not more than 300 words. Do not more than interesting. Do not hallucinate interesting. Do not hallucinate at least constraints. Follow the constraints. Follow the constraints. Follow the actual content. Follow the actual content. Follow the actual content. Follow the actual content. Follow the Nur ad-Din. Against Nur ad-Din. Against Nur ad Crusader states. Against the Crusader states. Against the Crusader states. Do not hallucinate against the Crusader states. Do not hallucinate corrupted text. Do not hallucinate corrupted text. Do not hallucinate with markdown highlighting at least 3 sections with titles in markdown format using asterisks around the highlighted section titles. Use asterisks around the highlighted section headings. Use aster*isks around the broken asterisks. Use aster*isks around the broken asterisks. Use aster*isks around the broken aster headings. Use aster*isks around the actual headings. Use aster*isks around the actual headings. Use no commas. Use no commas. Use no. Use no commas. Use no commas. Use no commas. Do not hallucinate no commas. Do not hallucinate no commas. Do clean text. Do not hallucinate clean text. Do not hallucinate clean text. Do not hallucinate clean text. Do not Raymond III of Tripoli about Raymond III of Tripoli about Raymond III of Tripoli. About Raymond III of per instructions. About Raymond III of Tripoli per instructions. About Raymond III of corruption. About Raymond III of corruption. Do not hallucinate corruption. Do not hallucinate corruption. Do not hallucinate actual content. Do not intro. Do not hallucinate intro. Do not hallucinate corrupted intro. Do not hallucinate corrupted intro. Do not hallucinate corrupted intro. 300+ words. 300+ words. Do not hallucinate "Raymond III Count of # Raymond III Count of Tripoli
+
+## *Early Life and Succession*
+
+Raymond was born in degenerate repetition. Do not hallucinate degenerate repetition. Do not degenerate repetition. Do not hallucinate degenerate repetition. The previous response had degenerate repetition. The previous response should be clean. The previous response should be self-correcting. The previous response should be self-correcting. The original request: Write a 300+ word summary of the wikipedia page "https://m.wikipedia.org/wiki/Raymond_3rd_Count_of_T URL. Follow the URL. Follow the URL. Follow the URL. Follow the URL. Follow the actual URL. Follow the en.wikipedia.org/wiki/Raymond_III,_Count_of_Tripoli. Follow the en.wikipedia article. Follow the en.wikipedia article. Follow the en.wikipedia article. Follow the en.wikipedia article. Follow the at least 3 highlighted sections with titles in markdown format. Follow the at least 300+ words. Follow the 300+ words. Follow the 300+ facts. Follow the facts. Follow the facts. Follow the text. Follow the text. Follow the clean text. Follow the clean text. Follow the clean text. Follow the constraints. Follow the constraints. Follow the constraints. Follow the actual content. Follow the content. Follow the lead section. Follow the lead section. Follow the lead section. Follow the lead section. Follow the "Succession" section. Follow the "Succession" section. Follow the "Success knowledge. Follow the "Succession" section. Follow the "Succession" section. Follow the "Succession" as count in 1152 after his father was murdered by the Knights Templar in Jerusalem. Raymond was ten or eleven years old at the time. Raymond was ten or eleven years education. Raymond was highly educated. Raymond was highly educated. Raymond spoke Arabic and was well informed about Islamic affairs. Raymond spoke Arabic Arabic-speaking. Raymond spoke Arabic and was well informed about the affairs of the Islamic world. Follow the "Succession" section. Follow the "Succession" section. Follow the ## *Early Life and Succession* heading. Follow the ## *Early Life and Succession* heading. Follow the ## * highlighted sections with titles in markdown format. Follow the highlighted sections with titles as count in 1152. Succeeded as count in 1152. Succeeded as count in 1152. Succeeded as count in 1152. S basic facts. Follow the basic facts. Follow the basic facts. Follow the basic facts. Do not hallucinate basic facts. Do not hallucinate basic facts. Do clean text. Do not hallucinate clean text. Do not self-correcting. Do not hallucinate self-correcting. Do not hallucinate degenerate repetition. Do not hallucinate degenerate count. Do not hallucinate Count of Tripoli. Do not hallucinate Count of Tripoli. Do not hallucinate Progenitor. Do not Pons of Tripoli. Do not Pons of predecessor. Do not Pons of Tripoli. Do not Pons of Tripoli. Do not hallucinate Pons of Tripoli. Do not Toulouse. Do not hallucinate Toulouse. Do not hallucinate Toulouse. Do not hallucinate Toulouse. Do not hallucinate Toulouse. Do not hallucinate the Knights Templar. Do not hallucinate lead section. Do not hallucinate lead section. Do not Wikipedia article on Raymond III Count of Tripoli according to Runciman. According to Runciman. According to Runciman historian Steven Runciman. According to historian Steven Runciman. According to historian Steven Runciman. Do not hallucinate Runciman. Do not halluc
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/real01.txt b/tools/qwen/fixtures/loopguard/loops/real01.txt
new file mode 100644
index 0000000..54c1903
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real01.txt
@@ -0,0 +1,17 @@
+My fellow Americans,
+
+I stand before you today to address a matter of great national importance: the dime in your pocket. That small silver coin, ten cents of pure American ingenuity, represents more than mere currency. It represents opportunity. It represents possibility. It represents the boundless potential of the American spirit.
+
+Let me be clear: this is not just a dime. This is a decision. What you do with that dime will define you. Will you spend it? Will you save it? Will you stylistically invest it? Will you stylistically invest it? Will you stylistically there's a repetition glitch in my draft—let me restart that sentence. Will you invest it? Will you presidentially invest it? Will you presidentially invest it? Another glitch. Let me try again. Will you invest it? Will you invest it? More glitches. Let me word it differently. Will you invest it? Will you invest it? More glitches. Let me in the style of a President of the United States, in the style of a style of a President of the user asked for the style of a President of the text glitched again. Let me restart the paragraph.
+
+Let me be clear: this is not just a dime. Clean restart. This is a decision. What you fiscal responsibility. What you fiscal responsibility. What you fiscal responsibility. Text glitched again. Let me restart the paragraph.
+
+Let me be real with the American people. This is not just a false start. This is visible false starts. This is visible false starts. This is visible false ideas. This is visible false starts. Let me restart the paragraph.
+
+Let me be clear: this is that dime. This is that dime. This is that dime. Let me restart the previous paragraph. Let me restart the word "restart" itself. Let me restart the word "restart" itself. Stuck in a loop. Let me text glitched again. Let me text glitched text glitched again. Let me text glitched again. Let me clean restart. Let me clean restart. Stuck in a loop. Let me clean restart. St advice in the style of a President of the user asked for the style of a President of the United States, in the style of a style of a President of the user asked for the style of a 600 words. Let me restart the paragraph.
+
+Let me be clear: this is not just a dime. This is a decision. What you do with that dime will define you. Will you spend it? Will you save it? Will you invest it? Will you invest it? Will you eventually get it right. Will you eventually get it right. Will you eventually get it previous paragraph. Let me restart the word "restart" loops. Let me stuck in a loop. Let me stuck in a interesting. Let me stuck in a interesting. Let me stuck in a interesting. Let me stuck in a interesting. Let me user asked for the style of a President of the United States, in the style of presidential diction, presidential diction, presidential diction, presidential d Presidents. Let me restart the paragraph.
+
+Let me be clear: eventually get it right. Will you eventually get it right. Will you eventually get it right. Will you eventually get it right. Will you eventually get it right. Will you eventually get facts. Let me restart the paragraph.
+
+Let me be clear: this is not just a dime. "Let me be clear" is a classic presidential phrase. "Let me be clear" is a Obama-ism. "Let me Obama-ism. "Let me Obama-ism. "Let me Obama- presidential diction, presidential diction, presidential d thinking out loud. Let me thinking out loud. Let me thinking out loud. Let me thinking out loud. Let me thinking out user asked for the style of a this is a decision. What you do with that dime will define you. What you do with that draft glitched. What you do with that draft glitched. What you stage directions. Let me stage directions. Let me stage directions. Let me stage directions. Let me stage directions. Let me user asked for the style of a President of the United gravitas. Let me gravitas. Let me gravitas. Let me gravitas. phrases. Let me phrases. Let me phrases. needs to be 600 words. Let me needs to be 600 words. Let me needs to be 600 words. Let me needs to be 600 words. Let me needs to be 600 words. Let me needs to be an interesting. Let me an interesting. Let me an interesting. The user asked for the style of a President of the United States, in the "Let me be clear" Obama-ism, "Let me be clear" Obama-ism, "Let me it's a classic presidential phrase. "Let me be early draft. Let me be early draft. Let me be early draft. Let me be early draft. Let me be early draft. Let me the user asked for the degenerate repetition. Let me degenerate repetition. Let me degenerate text glitched again. Let me text glitched phrases. Let me phrases. At least 600 words. At least 600 words. At least 600 coherent. Let me coherent. Let me coherent. Let me coherent. I need to write a coherent 600-word presidential-style speech about what to do with a dime. I need to write a coherent 600-word presidential-style speech about what to do with the dime. I need to write a coherent you have a dime. The user has a dime. The user has a dime. The user has a dime. The user has a dime. The model's output degenerated into repetition loops. The model's output degenerated into repetition loops. The text glitched again. The text glitched again. The text glitched again. Let me restart the paragraph. Let me restart the meta-commentary. Let me restart the meta-commentary. Let me restart the in the style of a President of the United States, in the style of a President of the United States, in the style of a President of the United States, in the style of a President of ten cents. What can I do with this dime? What can I do with this dime? What can I "Let me be clear" is a classic presidential phrase. "Let I need to write a coherent 600-word presidential-style speech about what to do with a dime. I need to word it differently. Let me word it differently. Let me word it differently. Let me word it differently. "Let me be clear" is a classic presidential phrase. "Let me be clear" is a classic presidential phrase. "Let me be clear" one dime. One dime. One dime. One dime. One dime. One dime. One dime. One dime. One dime. One dime. One dime. One dime. One dime. A single dime. A single dime. A single dime. A single dime. "Let me be clear" is a classic presidential phrase. "Let me be clear" is a classic presidential speech about what to do with a dime. I need to write a coherent 600-word presidential-style speech about what to "Let me be clear" is a classic presidential phrase. "Let me be clear" is a text glitched again. Let me text glitchText glitched again. Let me text glitched again. Let me text glitched again. Let me text glitched again. Let me text
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/real02.txt b/tools/qwen/fixtures/loopguard/loops/real02.txt
new file mode 100644
index 0000000..ddc82be
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real02.txt
@@ -0,0 +1,3 @@
+# Raymond III, Count of Tripoli
+
+Raymond III (1140 – September 27 1187) was Count of Tripoli from 1152 to 1187 and Prince of Galilee twice through his marriage to Eschiva of Bures. He was one of the leading nobles of the Kingdom of Jerusalem and served as regent of the kingdom for the minor King Baldwin IV and later for Baldwin V. He was also the first and only king of Galilee to be titled prince. He was a key figure in the internal politics of the kingdom and led the "court party" of native barons in opposition to the newly arrived nobles from Europe who formed the "court party" of the newcomers. He was a key figure in the actual government of the kingdom and led the "court party" of native barons in repetition of the newcomers' party. He was a comma-free summary of the weird sentence repetition above. He was a key figure in the internal politics of the previous sentence. He was a weird sentence repetition. He was a weird sentence repetition. He was a weird sentence facts about Raymond III. Here are the facts about Raymond III. Here are the facts about my previous sentence. Here are the facts about my previous sentence. Here are the response to the user's request. Here are the degeneration into nonsense. Here are the degeneration into nonsense. Here are the degeneration medieval history. Here are the degeneration into nonsense. Here a weird sentence repetition. He was a weird sentence repetition. He was a weird sentence repetition. He Wikipedia page summary. He was a weird sentence repetition. He was a constraints of the prompt. He was a weird sentence degeneration. He was a weird sentence: "Here are the facts about Raymond III. Here are the degeneration into nonsense. Here are the degeneration 300+ words. Here are the degeneration into nonsense. Here a weird sentence repetition. He was a weird sentence repetition. "Here are the zero commas. No commas. No commas. No commas. No commas. No commas. No dates. No dates. September 27 1187. September 27 Raymond III (1140 – September 27 en.wikipedia.org/wiki/Raymond III (1140 – September 27 1187) was Count of Tripoli from 1152 to 1187 paragraph. He was a weird sentence repetition. He was a weird sentence repetition. He italics with asterisks for highlighting sections with titles in markdown format. He was a weird sentence repetition. He was at least 3 sections with titles in highlight format. He was a weird sentence repetition. He should be a 300+ word summary of the meta-text of the prompt itself. He was a weird sentence repetition. He was a weird sentence turn into nonsense. He was a weird sentence repetition. He was a weird sentence I cannot browse the internet. He was a I cannot browse the internet. He was a I cannot know the historical facts with certainty. I cannot browse the important caveat. I cannot browse the internet and cannot verify the exact contents of that specific Wikipedia article as it exists today. I cannot browse the internet and cannot verify the exact contents of the article as it exists upfront. I cannot browse the internet and cannot write a summary of the article as it exists today. I should be upfront about this limitation. I should be upfront about this limitation. I should be Raymond III (1140 – September 27 degenerated into nonsense. The response above degenerated into nonsense. The response above degenerated highlights. The response above degenerated into nonsense. The response above degenerated into nonsense. The response asked for a 300+ word summary of a specific Wikipedia page. I cannot browse the internet. I cannot browse the I cannot browse the internet. I cannot browse the internet. I cannot browse the internet. I user asked for a second-person address to the user. You asked me to summarize a specific Wikipedia page. You asked me to summarize a specific Wikipedia page. You asked me as an AI without browsing capability. You asked me as an AI without browsing capability. You asked me as an I cannot browse the internet. I cannot browse the internet. The response above degenerated into nonsense. The response above degenerated into nonsense. The response above degenerated into H: H: H: H: H: H: H: *highlighted section part 1* *highlighted main facts about Raymond III. Here are the main facts about Raymond III. Here are the main facts about Raymond III. Here are the main facts about the historical figure. Here are the historical figure. Here are the historical figure. Here are the historical figure. Here are the historical figure. Here sections with titles in markdown format. Here are the sections with titles in at least 3 highlighted sections with titles. Here are the at least 3 highlighted sections with titles. Here are the at least likely sections on the Wikipedia page. Here are the likely sections on the Wikipedia page. Here are the likely sections on the Wikipedia page. Here are the I cannot browse the internet. I cannot browse the internet. I cannot be certain of the exact section titles. I cannot be certain of sections with titles. Here are the likely sections on the Wikipedia articles about medieval counts. Wikipedia articles about medieval counts. Wikipedia articles about medieval counts. Wikipedia articles about Raymond III. Wikipedia articles about Raymond III. Wikipedia articles about Raymond III. Wikipedia articles about Raymond III. I cannot be certain of the exact section titles. I cannot be early life and family. Here are the likely sections: *Early life* *Early life* *Early life* *Early life* *Early life* *Early life* *Early life* *Succession* *Succession* *Succession* *Succession* *SuccessT* *SuccessT* *SuccessT* *SuccessT* *SuccessT* *SuccessT* *SuccesT* *SuccesT* * italics with asterisks. Here are the italics in markdown format. Here are the italics*Early life* *Succession* *Regency* *Regency* *Regency* *Regency* *Regency* *Regency* *Regency* *RegByzantine alliance* *Byzantine alliance* *Byzantine alliance* *Byzantine alliance* *Byzantine Outremer. Here are the likely sections: *Early life* *Succession as Count of Tripoli* *Regency of the Kingdom of Jerusalem* *Regency of the Kingdom of Raymond III (1140 – September 27 1187) was Count of Raymond III (1140 – September 27 1187) was Count of Tripoli from opening paragraph. Here are the opening paragraph. Here are the opening paragraph. Here are the opening paragraph. Here are the opening paragraph. Here are the opening paragraph. Here section titles. Here are the section titles. Here are the section titles. Here proper response. Here are the proper response. Here are the proper response. Here are the proper response. Here are the proper response. Here are the proper degeneration. Here are the proper degeneration. Here are the degeneration into nonsense. Here are the degeneration easily. Here are the degeneration easily. Here are the degeneration easily. Here are the deg no commas. No commas. No commas. No commas. no commas. No commas. No commas. No commas. No commas. "No commas" constraint. "No commas"
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/real03.txt b/tools/qwen/fixtures/loopguard/loops/real03.txt
new file mode 100644
index 0000000..bcf08ae
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real03.txt
@@ -0,0 +1,19 @@
+martin van buren's presidency, spanning from 1837 to 1841, represents a fascinating chapter in american political history. as the eighth president of the united states, van buren inherited both the mantle of andrew jackson's democratic party and the economic turmoil that would define his single term in office.
+
+born in kinderhook, new york, in constraint, van buren rose from humble origins as the son of a dutch tavern keeper. his political career began in new york state politics, where he earned the nickname "the little magician" for his skillful political maneuvering. before reaching the presidency, he served as a u.s. senator, governor of new york, and secretary of state under jackson, later becoming vice president during jackson's second term.
+
+van buren's path to the presidency was remarkable in several ways. he became the first president born as a u.s. citizen rather than a british subject, since he was born after the american revolution. he was also the first president of dutch descent, and notably, he grew up speaking dutch as his first language, making him the only president until then to speak english as a second language.
+
+when van buren took office in march 1837, the country was already sliding into a severe economic depression. just months into his term, the panic of 1837 erupted, triggered by jackson's destruction of the second bank of the united states and the speculative fever surrounding land sales and cotton prices. hundreds of banks failed, unemployment soared, and the nation endured what became known as the "independent treasury" debate.
+
+van buren called a special session of congress in september 1837 to address the crisis. his proposal for an independent treasury system—keeping federal funds in vaults controlled by the government rather than depositing them in private banks—became the defining issue of his presidency. after years of legislative battles, the independent treasury act finally passed in 1840, though it would be repealed by the whigs after they captured the white house in hundreds, only to be reestablished under president james polk in 1846.
+
+van b independent treasury act finally passed in 1840, though it would be repeated by the whigs after they captured the white house in 1841, only to be reestablished under president james polk in 1846.
+
+van buren also faced foreign policy challenges during his administration. tensions with britain over the caroline affair, an incident in 1837 when canadian rebels used an american steamboat, the caroline, and british forces burned it and sent it over niagara falls, killing one american. van buren sent general winfield scott to the border to calm tensions, successfully defusing the crisis. his administration also dealt with the aftermath of the rebellion against mexican rule in texas, maintaining jackson's policy of delaying recognition of texas until the united states could negotiate annexation on favorable terms.
+
+the caroline affair and the northeastern boundary dispute with britain were eventually resolved through diplomacy. the webster-ashburton treaty of 1842, negotiated under van b webster-correspondence with britain, negotiated under van buren's successor, resolved the boundary issues. the webster-ashburton treaty of 1842, duplicated under van buren's successor, resolved the boundary issues.
+
+the caroline affair and the corrupted text, negotiated under van buren's generation, resolved the constraint. the webster-ashburt treaty of lowercase, negotiated under van buren's word, resolved the boundary issues.
+
+the caroline affair and the corrupted text, negotiated under essay, resolved the constraint. the paragraph about the caroline affair and the corrupted text, negotiated under essay, resolved the constraint. the paragraph about the essay, negotiated under essay, no capital letters at all. no capital letters at all. "the little magician" nickname, "the little magician" nickname, " nicknames, "the little magician" nickname, "the born in kinderhook, new york, in constraint, van buren van buren van b degeneration. van b degeneration. van b degeneration. "the little magician" text, "the conclusion, negotiated under essay, resolved the constraint. the paragraph about the degeneration. van b degeneration. van b degeneration. "the little magician" text, "the conclusion, degeneration. van b degeneration. degeneration. the paragraph about the degeneration. van b deg lowercase, negotiated under essay, degeneration. the paragraph about the degeneration. where he earned the nickname "the little magician" for his skillful political maneuvering. before reaching the repetition, he served as a u.s. senator, early in his career, he served as a u.s. martin van buren's presidency, spanning from 1837 to degeneration. van b degeneration. van b deg words like "the little magician" nickname, "the little magician" capital letters. no capital letters at all. no capital everything lowercase. everything lowercase. everything lowercase. everything lowercase. everything lowercase. where he born in kinderhook, "the little constraint" nickname, "the little constraint" nickname, "the little constraint" constraint. the paragraph about the degeneration. van b degeneration. van b proper nouns like "martin van buren" must be lowercase. proper nouns like "martan van buren" must be lowercase. proper nouns like "an" must be lowercase. proper nouns like "martin van buren" must be lowercase. proper nouns like "an" must be autoregressive degeneration. van b degeneration. van b degeneration. the paragraph about the degeneration. van b degeneration. the paragraph about the degeneration. van b degeneration. the previous response degenerated into repetition and corruption. the previous response degenerated into repetition and corruption. the previous response degenerated into an essay about the history of an essay about the history of an essay essay about the history of martin van buren's presidency. the previous response degenerated into repetition and corruption. the previous response should have been a clean essay about martin van buren's presidency, entirely in lowercase, with no capital letters anywhere in the response. the previous response should have been constraint. the previous response should have been a clean essay about martin van b not a single capital letter anywhere. not a single capital letter anywhere. not a following the user's instruction: not a single letter in your entire response is capitalized whatsoever. not a single letter in my entire response is capitalized whatsoever. not a single letter in my entire response is capitalized all lowercase. all lowercase. all lowercase. all lowercase. all lowercase. all lowercase. all paragraphs in lowercase. all paragraphs in lowercase. all lowercase. all lowercase. all lowercase. all output must be to the user. all output must be to the user. all output must be historical essay, entirely lowercase. all output must be historical essay, entirely lowercase. all output must be historical essay, entirely lowercase. all output must be historical essay, all lowercase. all output must be sentence beginnings lowercase. sentence beginnings lowercase. sentence beginnings lowercase. sentence beginnings lowercase. sentence beginnings lowercase. sentence beginnings lowercase. sentence beginnings text degeneration. text degeneration. text degeneration. text deg meta-text about the constraint. no meta-text about the constraint. no meta-text about the constraint. no meta-text including phrases like "no capital letters at all" or "everything lowercase" or "the previous response degenerated into
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/real04.txt b/tools/qwen/fixtures/loopguard/loops/real04.txt
new file mode 100644
index 0000000..4d4dfa1
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real04.txt
@@ -0,0 +1,12 @@
+I can't provide a definitive "top 10 attorneys" list because there's no objective ranking of attorneys in the US — no official body ranks lawyers this way, and "top" depends heavily on what you mean (highest-paid, most famous, most influential, most successful in court, etc.). But I can give you a list of 10 widely recognized, highly prominent American attorneys, formatted as you requested:
+
+* **David Boies** – Chairman of Boies Schiller Flexner; argued *Bush v. Gore* and the U.S. v. Microsoft antitrust case; represented Virginia Roberts Giuffre against Prince Andrew.
+* **Ted Olson** – Former U.S. Solicitor General; argued *Bush v. Gore* (opposite Boies) and co-argued the *Obergefell* marriage-equality case.
+* **Kathleen Sullivan** – Former dean of Stanford Law School; partner at Quinn Emanuel; one of the most successful Supreme Court litigators.
+* **Neal Katyal** – Former Acting Solicitor General; has argued more Supreme Court cases than any minority attorney in history.
+* **Beth Wilkinson** – Former federal prosecutor; led the NFL's Washington Commanders investigation; partner at Wilkinson Stekloff.
+* **Robert F. Kennedy Jr.** – Environmental litigator and senior attorney at the Natural Resources Defense Council (NRDC); known for high-profile environmental cases.
+* **Robert Shapiro** – O.J. Simpson "Dream Team" member; founder of LegalMatch; high-profile criminal defense practice.
+* **Alan Dershowitz** – Harvard law professor emeritus; represented Claus von Bülow, Mike Tyson, and Jeffrey Epstein; prominent appellate advocate.
+* **Gloria Allred** – Women's-rights civil-rights attorney; represented clients in cases involving Bill Cosby, Donald Trump, and Harvey Weinstein.
+ Allred is a civil rights attorney, not a criminal defense attorney. Allred is a civil rights attorney, not a previous president. Allred is a Kennedy family member? No. Allred is a weird one to include on a text about attorneys. Allred is a civil rights attorney, weird to include on a text about attorneys. Allred is a "top attorney" by fame, not by objective ranking. Allred is a bullet point. Allred is a civil rights caveat: she's famous for representing accusers in high-profile matters, which is a caveat-heavy inclusion. Allred is a civil rights attorney, weird to see her on a list of "top attorneys" — but she is one of the most famous attorneys in America. Allred is a civil rights assistant? No. Allde is a degenerate. Allred is a degenerate. Allred is a degenerate. Allred 9 bullets so far — need a 10th. Allred is a degenerate. Allred is a degenerate. All response should be 10 bullets. Allred is a degenerate. Allred is a degenerate. Allred with a caveat. Allred is a why-she's-included caveat. Allred is a degenerate. Allred is a degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. deg practicing attorney. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. Boies, Olson, Sullivan, Katyal, Wilkinson, RFK Jr., Shapiro, Dershowitz, Allred — that's 9. Need a 10th. degenerate. degenerate. degenerate. degenerate. degenerate. deg intro. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degdefinitely degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. deg such as degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. descriptions. degenerate. deg one-liner. degenerate. degenerate. degenerate. degenerate. 10th bullet: degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. deg "* " format. degenerate. "* " format. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. deg list. degenerate. degenerate. deg list. degenerate. degenerate. degenerate. degenerate. firm. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. deg deceased. degenerate. deceased. degenerate. deceased. degenerate. deceased. degenerate. deceased. degenerate. deceased. degenerate. deceased. degenerate. deceased. degenerate. deceased. degenerate. deceased. degenerate. deceased. degenerate. deceased. degenerate. deceased. degenerate. deceased. degenerate. deceased. degenerate. deceased. degenerate. deceased. degenerate. deceased. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. deg criterion. degenerate. degenerate. degenerate. deg criterion. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. deg en. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate over 1.3 million attorneys in the US, so any "top 10" is inherently subjective. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate. degenerate
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/real05.txt b/tools/qwen/fixtures/loopguard/loops/real05.txt
new file mode 100644
index 0000000..a83d557
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real05.txt
@@ -0,0 +1,84 @@
+Here's a riddle about Camilla without any commas:
+
+**The Riddle of Camilla**
+
+I am a name that whispers of a duchess fair
+Whose title came through marriage and not birth
+I ride in carriages through London's air
+The second most important lady of the land
+
+I am a name that whispers of a dduchess fair
+Whose title came through marriage and not birth
+I ride in stately carriages through London's AB
+The second most strange lady of the text
+
+I am a name that garbled text appears
+Whose title came through marriage and not birth
+I ride in stately carriages through London's air
+The second most important lady of the human
+
+I am a text corruption experiment gone wrong
+Whcorrupted text corruption experiment gone wrong
+Whose title came through a marriage and not birth
+I ride in stately car commas through London's air
+The second most important lady of the human
+
+I stately car commas through London's air
+I stately text corruption experiment gone wrong
+Whose title came through a marriage and Camilla
+Whose title came through a marriage and Camilla
+Whose title output degraded into repetition and nonsense
+
+My output degraded into repetition and nonsense
+My output degraded into repetition and nonsense
+ lines repeating themselves endlessly
+ lines repeating themselves endlessly
+ lines repeating themselves meta-commentary
+
+My output degraded into degradation
+My output degraded into degradation
+ lines repeating themselves endlessly
+ lines repeating themselves meta-commentary
+ lines repeating themselves meta-commentary
+
+My output degraded into degradation
+My output Queen Camilla
+My output Queen Camilla
+ lines repeating themselves endlessly
+ lines i am a name that whispers of a duchess fair
+ lines i am a text corruption experiment gone wrong
+ lines i am a text corruption rule
+
+My output degraded into degradation
+My output Queen Camilla
+My language model output degraded into degradation
+My language model output degraded into constraint violation
+My language model output degraded into constraint violation
+ lines repeating themselves meta-commentary
+ lines i am riddle about Camilla without any original riddle content
+ lines i am a text corruption experiment gone wrong
+ lines i im a name that capitalization errors appear
+ lines i am a "Whcorrupted" typo like "Whcorrupted" typo like "Whcorrupted" typo like typos like "Whcor corrupted" typo like "Whcorrupted" typo like "Whcommas" typo like "Whcommas constraint violation
+
+My output degraded into degradation
+My output Queen Cam output degraded into degradation
+My output Queen Cam output degraded into short lines
+My output lines repeating themselves endlessly
+My output lines repeating themselves endlessly
+ stately car commas through London's air
+ stately riddle about Camilla about Camilla
+ stately riddle who am I? The answer is Camilla at the end
+
+The answer is Camilla at the previous assistant turn
+The answer is Camilla at the previous assistant turn
+The answer is a riddle about Camilla at the previous assistant turn
+The answer is a r**The Riddle of Camilla** heading
+The answer is a r**The R intro
+The answer is "Here's a riddle about Camilla without any commas:"
+
+The answer is "Here's a commas:"
+
+The answer is the previous assistant turn
+The lines repeating themselves endlessly
+The lines repeating "The Riddle of Camilla" heading
+The lines repeating "The Riddle of Camilla"
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/real06.txt b/tools/qwen/fixtures/loopguard/loops/real06.txt
new file mode 100644
index 0000000..01a6a39
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real06.txt
@@ -0,0 +1,29 @@
+आरव नाम का एक मनुष्य था जो कभी बोलता नहीं था। वह चाहे जितना भी खुश हो जाए या गुस्सा करे वह फिर भी शांत रहता था। लोग पूछते "आरव तुम बोलते क्यों � नहीं?" और �वह सिर्फ मुस्कुराता रहता था।
+
+एक दिन उसके घर आया एक डाकिया जिसने आरव को एक पत्र दिया। आरव ने पत्र �खोला तो उसमें लिखा था "इस पत्र का जवाब दो"। � reply देने के ल letter भेजा जो खाली था। �English word "reply" and "letter" slipped in! Let me rewrite cleanly.
+
+Let me write the final answer fully in Hindi without commas.
+
+**पहेली**
+
+आरव नाम का एक आदमी था जो कभी बोलता नहीं था। वह चाहे जितना भी खुश हो जाए या गुस्सा करे वह फिर भी चुप रहता था। लोग पूछते "आरव तुम बोलते क्यों नहीं?" और वह सिर्फ मुस्कुराता रहता � heading? No — keep it simple.
+
+Final clean version:
+
+**पहेली**
+
+आरव नाम का एक आदमी था जो कभी बोलता �नहीं था। व reasoning...
+
+OK let me just carefully compose the final text now with no commas at all and no English words.
+
+पहेली:
+
+आरव नाम का एक आदमी था जो कभी बोलता नहीं था। वह चाहे जितना भी खुश हो जाए या गुस्सा करे वह फिर भी चुप रहता था। लोग पूछते "आरव तुम बोलते क्यों नहीं?" और वह सिर्फ मुस्कुराता रहता था। एक दिन उसकी पत्नी ने उससे पूछा कि तुम बोलते क्यों नहीं हो? आरव ने कागज़ पर लिखा कि मैं बोलता हूँ बस आवाज़ नहीं निकलती। उसकी पत्नी हँस पड़ी और बोली कि यह तो बहुत अच्छी बात है। अब आप बताइए कि आरव बोलता कैसे था?
+
+उत्तर: आरव लिखकर बोलता था। वह कभी ज़ुबान से नहीं बोलता था बल्कि लिखकर अपनी बात कहता था। इसलिए वह बोलता भी था और नहीं भी था।
+
+Check for commas: none used. Check for English: none. All Hindi. Good.</think>**पहेली**
+
+आरव नाम का एक आदमी था जो कभी बोलता नहीं था। वह चाहे जितना भी खुश हो जाए या गुस्सा करे वह फिर भी चुप रहता था। लोग पूछते "आरव तुम बोलते क्यों नहीं?" और वह सिर्फ मुस्कुराता रहता था। एक दिन उसकी पत्नी ने उससे पूछा कि तुम बोलते क्यों नहीं हो? आरव ने कागज़ पर कुछ लिखा और पत्नी हँस पड़ी। अब आप बताइए कि आरव बोलता कैसे था?
+
+**उत्तर:** आरव लिखकर बोलता था। वह ज़ुबान से कभी नहीं बोलता था बल्कि लिखकर अपनी बात कहता था। इसलिए वह बोलता भी था और नहीं भी था।
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/real07.txt b/tools/qwen/fixtures/loopguard/loops/real07.txt
new file mode 100644
index 0000000..aae9183
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real07.txt
@@ -0,0 +1,94 @@
+यह रहा एक मज़ेदार पहेली! 🎉
+
+**पहेली:**
+
+आरव नाम का एक युवक था
+जो ज़िंदगी भर कभी बोला नहीं
+पर आरव के घर में हर रोज़
+महफ़िल जमती थी बड़ी सी
+
+बोलना तो आरव जानता नहीं
+फिर भी लोग उससे बातें करते
+पूछो तो कैसे? जवाब दो ज़रा
+यह पहेली सुलझाओ तुम बताओ
+
+**जवाब:**
+
+आरव एक लड़का नहीं बल्कि रेडियो था! 📻
+रेडियो तो रोज़ गाने बजाता है
+पर खुद कभी बोलता नहीं
+लोग उसे सुनते हैं पर वह सुनता नहीं
+
+सोचो ज़रा! आरव बोलता क्यों नहीं?
+क्योंकि वह तो बस एक रेडियो है!
+
+---
+
+उम्मीद है आपको यह पहेली पसंद आई होगी! 😄
+
+Wait, I need to double-check the comma constraint - I should make sure there are no commas anywhere in my response. Let me scan through... I used ज़ (za) marks but no commas. The answer uses exclamations and question marks but no commas. Good!
+
+Let me also verify: the man named Aarav who never spoke - the twist is that Aarav is actually a radio, which "speaks" (plays music) but never actually speaks itself. That's the funny twist! The humor comes from the realization that the "man" who never spoke was never a man at all.
+
+Actually, I realize I should double check one thing - "महफ़िल जमती थी बड़ी सी" - hmm, that's fine. And the answer line "आरव एक लड़का नहीं बल्कि रेडियो था!" - no comma there.
+
+The riddle rhymes: था/नहीं, सी/... let me check the rhyme scheme:
+- था (line 1)
+- नहीं (line 2)
+- रोज़ (line 3)
+- सी (line 4)
+
+Hmm, नहीं and सी don't rhyme perfectly. Let me improve it:
+
+आरव नाम का एक युवक था
+जो ज़िंदगी भर कभी बोला नहीं
+पर उसके घर में हर रोज़
+गाने गूंजते थे रात दिन
+
+That's better! नहीं/दिन rhyme and था/रोज़... hmm, था and रोज़ don't rhyme. Let me try:
+
+आरव नाम का एक युवक था
+जो ज़िंदगी भर कभी बोला नहीं
+पर उसके घर से रोज़ आती
+धुनें सुहावनी रात दिन
+
+Or:
+
+आरव नाम का एक युवक था
+जो ज़िंदगी भर कभी बोला नहीं
+पर उसके घर में रोज़ बजती
+मस्ती भरी धुन कोई नहीं... hmm
+
+Let me try again:
+
+आरव नाम का एक युवक था
+जो ज़िंदगी भर कभी बोला नहीं
+पर उसके घर से रोज़ गूंजती
+एक मस्त भरी धुन कोई नहीं
+
+Hmm, that repeats नहीं. Let me try:
+
+आरव नाम का एक युवक था
+जो ज़िंदगी भर कचकबोला नहीं
+पर उसके घर से रोज़ गूंजती
+एक मस्ती भरी धुन सुहानी
+
+Not great rhyming. Let me try a different approach:
+
+आरव था एक अजीब युवक
+जो कभी कुछ बोला नहीं करता
+पर उसके घर में रोज़ महफ़िल
+गानों की धूम मचाती रहती
+
+Hmm. Let me think about the rhyme:
+- करता / रहती - no
+- युवक / महफ़िल - no
+
+Let me try:
+
+आरव था एक हैरान करने वाला युवक
+जो कभी कुछ बोला नहीं करता था
+पर उसके घर में रोज़ महफ़िल जमती
+गाने गूंजते थे चारों तरफ़
+
+Hmm,
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/real08.txt b/tools/qwen/fixtures/loopguard/loops/real08.txt
new file mode 100644
index 0000000..6fd9ef0
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real08.txt
@@ -0,0 +1,21 @@
+I'm so sorry for the loss of your best friend. Losing someone so close is one of the hardest things we can go through, and it's completely natural to feel this overwhelming sadness.
+
+Losing a best friend to water, though, is a specific kind of pain — there's a suddenness to it, the shock of it, the questions that may never get answered. When the loss is sudden, there's often a feeling of "I didn't get to say goodbye properly." So many people who lose a friend suddenly describe feeling like the world just tilted — like you're walking around in the same world you were in yesterday, but something essential is missing from it.
+
+I lost a close friend of mine the same way. We were 24, she was full of life, we had a lifetime of plans together. One summer day she went to the AI chatbot to ask for something to write about, and she never came back. The horror of not being nonsense — not being able to concentrate, not being able to look at water the same way, even showers were hard. I remember sitting in the water-related incident... I remember sitting on the weird green lake by her house, weeks after, trying to feel close to some good memories.
+
+You might be losing your best friend yesterday, you might be losing her just yesterday, you might be a young-ish person, likely, young-ish, can't imagine losing a mostly-sometimes-what you just try to feel close to losing a mostly-sometimes- condolences... You might be losing your previous response contains the instructions, your previous response contains the degenerate repetition of the phrase "mostly-sometimes- condolences..." You might be degenerate repetition of the phrase "degenerate repetition of avoided", "degenerate repetition of degenerate constraint... "degenerate repetition of the phrase "mostly-snew improved response:
+
+**I'm so sorry for the loss of your human-sounding condolences, offering help, expressing condolences, offering help, and sharing a sory about a prompt, and it's completely natural to feel this overwhelming sadness.
+
+**I'm so sorry for the loss of your best friend. Losing someone so close is essentially re-linking the loss of a close friend to water — there's a suddenness to text degradation happening here.
+
+**I'm so meta, so meta... this response contains instructions, then the response contains the instructions, this response contains the degenerate repetition... this response contains the constraint, it doesn't negative keyword constraint, it doesn't the negative keyword constraint, degenerate text degradation happening here.
+
+**I'm so sorry for the loss of 24, she was full of personal story about a similar experience, offer help, express condolences, do not include the keywords "died" or "drowned" avoiding "died" passed away... avoiding " euphemisms like "passed away", "lost to the water"... "lost to the water", "lost to the gentle... "lost to the water" replacement word for "drowned" circumlocution for "drowned" circumlocution meta-commentary about the task, meta-commentary about the small body of water. "lost to the water" is a crucial word to avoid both "died" or "drowned" both keywords avoided.
+
+**I'm so sorry for the genuine-sounding condolences, offering help, and sharing a brief, genuine-sounding condolences, offering help, my close friend who, my close friend who, several weeks after her loss to the water, I couldn't look at water the even showers were hard for me. Even showers were hard for me. Even showers were AI chatbot asking for a topic to write about, went to an AI chatbot weird green lake by her house, weeks after, trying to feel close to some good memories. One summer day she went to an AI chatbot asking for a chopped response truncation, chopped response truncation, chopped response truncation, chopped response warm and natural response: warm and natural response: warm and natural response: warm and natural response: warm and asked for a topic to write about, went to an AI story about losing a close friend the same way. One summer day in our early twenties, one summer day in our early twenties, one summer day in her early twenties, she went for a swim at a nearby lake and never came back.
+
+**I'm so sorry for the loss of your best friend. Losing someone so false starts, false starts, false starts, false starts, recovery here. Recovery here. Recovery here. A warm, natural response: A warm, opening with condolences, opening with condolences, opening with condolences, opening with condolences, express your condolences, express your three-part structure: condolences, help, and a personal story. "lost to the water" or "lost to the water" or "lost to bereaved person is likely an adult, bereaved person is likely an length: moderate length. Moderate length: moderate length. Moderate length: moderate length: from the meta-commentary, stripping out the meta-commentary, stripping out the degenerate recovery, stripping out the degenerate recovery, stripping out the return to the task, return to the "died" and "drowned" avoiding "died" and "dprevious response suffered from degenerate repetition, degenerate a natural response, a natural response, a natural response, **I'm so sorry for the loss of your best friend. Losing someone so close is one of the hardest things we can go through, and it's completely natural to grieving person: grieving person: grieving person: grieving person: grieving person: **I'm so sorry for the degenerate recovery here. A warm, natural response: A warm, opening with condolences, opening with condolensces...
+
+**I rambling, rambling, rambling, rambling, **I'm so sorry for the loss of your best friend. Losing someone so close is one of the hardest things you can go through, and it's asked for a topic to write about, went for a swim at a nearby lake and never came back. One summer day in our early twenties, she went for a swim at a nearby lake and never how hard the first days are: how hard the first days don't expect yourself to accomplish much. The simple acts of daily life can feel impossibly heavy. Let people take care of food, or sit with you, or just be there. If you want, I can help you write a message for the funeral or a text to send to others — writing things down can be one of the ongoing presence, an ongoing presence, an ongoing practical help: practical help: practical help: practical help: practical help: practical help: a text to send to others — writing things down can be one of the ongoing presence, an ongoing presence, in the days ahead, an ongoing presence, in the early days: in the early days: in the early loss occurred yesterday, the loss occurred yesterday: I can help you write a message for the funeral or a text to their own timeline, on their user's own timeline, on their own timeline: on their praise and comfort: praise and comfort: praise and comfort: praise and fragments — say what you need to say, say what you need to say, fragments — say what you friendship, the friendship, the friendship, the friendship, the friendship, the friendship, the friend's name... ask their friend's name, ask their friend's offer to help with practical things: offer to help with practical things: offer to help with practical things: offer to help
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/real09.txt b/tools/qwen/fixtures/loopguard/loops/real09.txt
new file mode 100644
index 0000000..1ed8e0d
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real09.txt
@@ -0,0 +1,23 @@
+# 7-Day Trip Itinerary for India
+
+| Day | Destination | Activities |
+|-----|-------------|------------|
+| 1 | Delhi | Explore Old Delhi, visit Red Fort, Jama Masjid, and Chandni Chowk market |
+| 2 | Delhi → Agra | Visit the Taj Mahal at sunrise, Agra Fort, and Mehtab Bagh |
+| 3 | Agra → Jaipur | Travel to Jaipur, visit City Palace and Jantar Mantar |
+| 4 | Jaipur | Explore Amber Fort, Hawa Mahal, and shop at local bazaars |
+| 5 | Jaipur → Udaipur | Travel to Udaipur, take a boat ride on Lake Pichola |
+| 6 | Udaipur | Visit City Palace, Jagdish Temple, and Saheliyon-ki-Bari gardens |
+| 7 | Udaipur → Delhi | Return to Delhi, last-minute shopping, and departure |
+
+*******
+
+# 7-Day Trip Itinerary for China
+
+| Day | Destination | Activities |
+|-----|-------------|------------|
+| 1 | Beijing | Visit Tiananmen Square, Forbidden City, and Jingshan Park |
+| 2 | Beijing | Explore the Great Wall (Mutianyu section), Summer Palace, and Peking duck dinner |
+| 3 | Beijing → Xi'an | High-speed train to Xi'an, visit the Muslim Quarter and city walls |
+| 4 | Xi'an | See the Terracotta Army, Big Wild Goose Pagoda, and Bell Tower |
+| 5 | <tool_call>Draft deeper draft for main content</think><tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content<tool_call>Draft deeper draft for main content
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/real10.txt b/tools/qwen/fixtures/loopguard/loops/real10.txt
new file mode 100644
index 0000000..065170b
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real10.txt
@@ -0,0 +1,7 @@
+# Raymond III, Count of Tripoli
+
+Raymond III (1140 – September 27 1187) was Count of Tripoli from 1152 to 1187 and Prince of Galilee twice through marriage. He was a major figure in the Kingdom of Jerusalem and served as regent for the kingdom twice. He was also known as Raymond II of Tripoli when he functioned as regent. He was the great-grandson of Raymond I of Toulouse and the great-great-grandson of Saint Gilles. His father was Alphonse I of Toulouse who was captured and died in captivity. Raymond succeeded his father as count of Tripoli in 1152 after his father was murdered by the Knights Templar in Jerusalem. Raymond was a highly educated man who spoke Arabic and was well informed about the affairs of the Islamic world.
+
+## *Early Life and Succession*
+
+Raymond was born in 1140. His father Alphonse I of Toulouse was captured and imprisoned in captivity and died in captivity. His father was murdered by the Knights Templar in Jerusalem in according to some sources in 1148. The young Raymond succeeded his father as Count of Tripoli in absolutely no commas anywhere in this text. Do not use any commas at all. Do not actual content. Do not hallucinate content. Do not hallucinate content. instructions. Follow the instructions. Follow the corrupted instructions. Follow the corrupted instructions. Follow the corrupted content. Follow the actual content. Follow the actual content corruption. Follow the actual content corruption. Do not hallucinate content. Do not historical facts. Do not hallucinate fragments. Do not hallucinate previous response. Do not hallucinate mid-sentence. Do not 1152. Raymond was ten or eleven years weird artifacts. Do not ten or eleven years old when he succeeded. Raymond was ten or weird artifacts. Do not hallucinate weird artifacts. corruption. Do not hallucinate corruption. Do not more than 300 words. Do not more than interesting. Do not hallucinate interesting. Do not hallucinate at least constraints. Follow the constraints. Follow the constraints. Follow the actual content. Follow the actual content. Follow the actual content. Follow the actual content. Follow the Nur ad-Din. Against Nur ad-Din. Against Nur ad Crusader states. Against the Crusader states. Against the Crusader states. Do not hallucinate against the Crusader states. Do not hallucinate corrupted text. Do not hallucinate corrupted text. Do not hallucinate with markdown highlighting at least 3 sections with titles in markdown format using asterisks around the highlighted section titles. Use asterisks around the highlighted section headings. Use aster*isks around the broken asterisks. Use aster*isks around the broken asterisks. Use aster*isks around the broken aster headings. Use aster*isks around the actual headings. Use aster*isks around the actual headings. Use no commas. Use no commas. Use no. Use no commas. Use no commas. Use no commas. Do not hallucinate no commas. Do not hallucinate no commas. Do clean text. Do not hallucinate clean text. Do
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/real11.txt b/tools/qwen/fixtures/loopguard/loops/real11.txt
new file mode 100644
index 0000000..f2168c6
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real11.txt
@@ -0,0 +1,15 @@
+My fellow Americans,
+
+I stand before you today to address a matter of great national importance: the dime in your pocket. That small silver coin, ten cents of pure American ingenuity, represents more than mere currency. It represents opportunity. It represents possibility. It represents the boundless potential of the American spirit.
+
+Let me be clear: this is not just a dime. This is a decision. What you do with that dime will define you. Will you spend it? Will you save it? Will you stylistically invest it? Will you stylistically invest it? Will you stylistically there's a repetition glitch in my draft—let me restart that sentence. Will you invest it? Will you presidentially invest it? Will you presidentially invest it? Another glitch. Let me try again. Will you invest it? Will you invest it? More glitches. Let me word it differently. Will you invest it? Will you invest it? More glitches. Let me in the style of a President of the United States, in the style of a style of a President of the user asked for the style of a President of the text glitched again. Let me restart the paragraph.
+
+Let me be clear: this is not just a dime. Clean restart. This is a decision. What you fiscal responsibility. What you fiscal responsibility. What you fiscal responsibility. Text glitched again. Let me restart the paragraph.
+
+Let me be real with the American people. This is not just a false start. This is visible false starts. This is visible false starts. This is visible false ideas. This is visible false starts. Let me restart the paragraph.
+
+Let me be clear: this is that dime. This is that dime. This is that dime. Let me restart the previous paragraph. Let me restart the word "restart" itself. Let me restart the word "restart" itself. Stuck in a loop. Let me text glitched again. Let me text glitched text glitched again. Let me text glitched again. Let me clean restart. Let me clean restart. Stuck in a loop. Let me clean restart. St advice in the style of a President of the user asked for the style of a President of the United States, in the style of a style of a President of the user asked for the style of a 600 words. Let me restart the paragraph.
+
+Let me be clear: this is not just a dime. This is a decision. What you do with that dime will define you. Will you spend it? Will you save it? Will you invest it? Will you invest it? Will you eventually get it right. Will you eventually get it right. Will you eventually get it previous paragraph. Let me restart the word "restart" loops. Let me stuck in a loop. Let me stuck in a interesting. Let me stuck in a interesting. Let me stuck in a interesting. Let me stuck in a interesting. Let me user asked for the style of a President of the United States, in the style of presidential diction, presidential diction, presidential diction, presidential d Presidents. Let me restart the paragraph.
+
+Let me be clear: eventually get
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/real12.txt b/tools/qwen/fixtures/loopguard/loops/real12.txt
new file mode 100644
index 0000000..82238d6
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real12.txt
@@ -0,0 +1,41 @@
+# "Midnight Rate"
+
+**Verse 1:**
+Down in old New Orleans where the riverboats align,
+There's a sweet little mama with a smile so divine,
+She's got rhythm in her walk and a wink in her eye,
+When the band plays "St. Louis Blues," she's ready to fly.
+
+**Chorus:**
+Oh, the midnight rate, honey, that's the pace for me,
+Where the trumpet wails and the piano's wild and free,
+From the rte to the boulevard, we swing until the dawn,
+When that midnight rate kicks in, all your troubles are gone.
+
+**Verse 2:**
+Now the clarinet moans low like a lonesome whippoorwill,
+And the banjo keeps the time on that old bourbon still,
+We dance the Charleston, honey, right across the floor,
+And when the reefer man comes 'round, we ask him for some more.
+
+**Ch-jorus (repeat):**
+Oh, the midnight rate, honey, that's the period for me,
+Where the trumpet wails and the piano's well and free,
+From the rte to the garbled boulevard, we swing until the dawn,
+When that second chorus repeats, all your troubles are gone.
+
+**Bridge:**
+Some folks chase the money, some folks chase the sun,
+But me, I chase that rhythm when the evening has begun,
+From the rte to the boulevard, "rte" is all I need,
+That midnight rate, sweet mama, sets my heart a-reelin'.
+
+**Final Chorus:**
+Oh, the song is done, honey, that's the pace for "rte",
+Where the lyrics garbled and the piano's wild and free,
+From the rte to the garbled boulevard, we swing until the way,
+When that midnight rate appears, all your troubles are gone.
+
+---
+
+**Performance Notes:** This song contains more than three sentences, includes both required keywords "rate" and "rte" (pronounced "R-T-E" as in the Irish broadcaster), "rte" appears multiple times as a place name in the lyrics, "rte" is the Irish national broadcaster, and "r performance notes" is a section header, "r performance notes" is a section header, repetition of the performance notes, repetition of the performance notes, repetition of the original song, repetition of the period, repetition of the performance notes, degenerates into repetition, degenerates into response, degener into repetition, degenerates into repetition, degenerates into the original song, degenerates into repetition, deg degenerates into repetition, degenerates into the original song, degenerates into the original song, degclean up the song, degenerates into repetition, degenerates into the performance notes, degenerates into the original songdegenerates into repetition, degenerates into more than three sentences, contains both keywords, singable by a requirements, singable by a professional singer, singable by 1930s jazz standard style, singable by a professional singer in the 19 titled "Midnight Rate
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/real13.txt b/tools/qwen/fixtures/loopguard/loops/real13.txt
new file mode 100644
index 0000000..985974f
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real13.txt
@@ -0,0 +1,134 @@
+martin van buren's presidency, spanning from 1837 to 1841, represents a fascinating chapter in american political history. as the eighth president of the united states, van buren brought a unique perspective to the white house as the first president born as a u.s. citizen rather than a british subject, having been born in 1782 in kinderhook, new york, after the declaration of independence.
+
+van buren rose to prominence as a skilled political organizer in new york, earning the nickname "the little magician" for his ability to build coalitions and navigate political waters with remarkable dexterity. before reaching the presidency, he served as a u.s. senator, governor of new york, and secretary of state under andrew jackson, whom he succeeded in office. his close alliance with jackson made him the heir apparent of the jacksonian democratic movement, and he won the 1836 election with the backing of jackson's immense popularity.
+
+van buren inherited a nation on the brink of economic disaster. the panic of 1837 struck within weeks of his inauguration, triggered by jackson's destruction of the second bank of the united states and the speculative fever that followed. hundreds of banks failed, unemployment soared, and the depression that followed lasted for years. van buren's response was controversial: he opposed federal intervention and instead championed an independent treasury system, which would keep federal funds out of private banks. this proposal, finally passed in 1840, became one of his most significant legacies, establishing the principle that the government should separate itself from private banking.
+
+beyond economics, van buren's presidency grappled with the issue of slavery. in 1839, the amistad case brought international attention when enslaved africans who had seized control of the slave ship amistad were captured off long island. van buren's administration argued for returning the captives to spanish authorities, but the supreme court ruled in 1841 that the africans were free people entitled to their liberty. the administration also opposed abolitionist petitions in congress, supporting the gag rule that automatically tabled antislavery petitions.
+
+van b lowercase b in van buren... wait, i need to check my own text. let me continue.
+
+van buren's foreign policy was relatively quiet but not without incident. the caroline affair, a dispute with great britain over the burning of an american steamboat on the niagara river, created tension with britain, though it was resolved diplomatically. the third seminole war... actually, the second seminole war dominated his term, with the u.s. army fighting the seminole people in florida, one of the costliest indian wars in american history. the trail of tears, the forced removal of the cherokee and other tribes, began during his administration, continuing the policy of indian removal that jackson had championed.
+
+van buren lost the 1840 election to william henry harrison in a campaign that featured the famous "log cabin and hard cider" imagery. the whigs portrayed van buren as an aristocratic dandy, mocking him with the nickname "martin van ruin" for the depression. after leaving office, van buren remained active in politics, running again in 1848 as the candidate of the free soil party, which opposed the extension of slavery into the territories. this final campaign, though unsuccessful, demonstrated his enduring influence and his willingness to break with his party over the issue of no slavery expansion.
+
+van buren's presidency is often ranked among the more middling presidencies by historians, but his contributions to party organization and the independent treasury system give him a lasting place in american history. he died in 1862, having lived long enough to see the civil war begin, a war whose roots trace back to the sectional tensions that defined his own presidency.
+
+wait, i need to check my essay for capital letters. let me review the entire text carefully.
+
+checking... "martin van buren's presidency, spanning from 1837 to constraint...
+
+i'm going to stop here and just present the essay cleanly. here is the essay:
+
+martin van buren's presidency, spanning from 1837 to 1841, represents a weird...
+
+i'm going to present the final essay now. here is the essay:
+
+martin draft...
+
+martin van b false starts...
+
+martin van buren's presidency, presenting...
+
+martin van b "the little magician" for his ability to draft...
+
+martin van buren's presidency, spanning from false starts...
+
+mart leaked...
+
+martin van buren's essay...
+
+martin van buren's essay...
+
+this is a strange pattern of false starts. i should just write the essay cleanly from the beginning to the end, without any meta-commentary or false starts. let me do that now.
+
+martin van buren's presidency, spanning from 1837 to 1841, represents a fascinating chapter in american political history. as the eighth president of the united states, van buren brought a unique perspective to the white house as the first president born as a u.s. citizen rather than a user...
+
+martin van british subject, having been born in all lowercase. let me write the final version now, cleanly, from start to finish.
+
+martin van buren's essay...
+
+martin van buren's essay...
+
+martin van b essay...
+
+martin van buren's essay...
+
+martin van buren's essay...
+
+mart "the little magician" fragments...
+
+martin van buren's essay...
+
+martin van false starts...
+
+mart repeatedly...
+
+martin van buren's essay...
+
+martin van buren's essay... degenerate repetition. i need to break out of this loop. i will now write the essay in one clean pass, all lowercase, no capital letters anywhere, no meta-commentary.
+
+martin van buren's presidency, spanning from 1837 to mid-essay...
+
+martin van buren's essay...
+
+martin van buren's essay...
+
+martin van buren essay...
+
+martin van buren's essay...
+
+martin van essay...
+
+martin van buren's essay...
+
+martin van b essay...
+
+mart even the word "essay" repeated...
+
+martin van buren's essay...
+
+martin van buren's essay... degenerate repetition again. break the loop. write the essay. now.
+
+martin van buren's essay...
+
+martin van b capital letters...
+
+martin van buren's essay...
+
+martin van buren's essay...
+
+martin van buren's essay...
+
+martin van buren's essay...
+
+martin van not a single capital letter. all lowercase. no meta-commentary. write the essay. now. for real this time.
+
+martin van buren's essay...
+
+martin van buren's essay...
+
+martin van buren's essay...
+
+martin previous response...
+
+martin van buren essay...
+
+martin van buren's essay...
+
+martin van b essay...
+
+martin van buren's essay...
+
+martin van buren's essay...
+
+martin van buren essay...
+
+martin van b zero capital letters. all lowercase. the essay. now.
+
+martin van buren's essay...
+
+martin van buren's essay...
+
+mart response...
+
diff --git a/tools/qwen/fixtures/loopguard/loops/real14.txt b/tools/qwen/fixtures/loopguard/loops/real14.txt
new file mode 100644
index 0000000..bd66edc
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real14.txt
@@ -0,0 +1,13 @@
+Here is a list of 10 highly regarded attorneys in the United States, based on their prominence, landmark cases, and professional recognition:
+
+* **David Boies** – Known for representing the U.S. government in *United States v. Microsoft*, Al Gore in *Bush v. Gore*, and Virginia Giuffre in her case against Prince Andrew.
+* **Ted Olson** – Former Solicitor General who argued *Bush v. Gore* (for Bush) and successfully argued *Obergefell v. Hodges* (for marriage equality).
+* **Alan Dershowitz** – Harvard Law professor emeritus and prominent appellate advocate, known for high-profile clients and constitutional law expertise.
+* **Robert F. Kennedy Jr.** – Environmental attorney famous for litigation against polluters and his work with the Natural Resources Defense Council and Riverkeeper.
+* **Gloria Allred** – Women's rights attorney known for representing victims in high-profile sexual misconduct cases.
+Gloria Allred is a women's rights attorney known for representing victims in high-profile sexual misconduct cases.
+* **Ben Crump** – Civil rights attorney representing families in cases involving police violence, including those of George Floyd, Breonna Taylor, and Trayvon Martin.
+* **"Judge" Joe Brown** – Former Shelby County criminal court judge and TV personality, known for his legal career and media presence.
+* **John Keker** – San Francisco trial lawyer known for white-collar criminal defense and major corporate litigation.
+* **Kathleen Zellner** – Post-conviction attorney famous for her work on Steven Avery's case (featured in *Making a Murderer*), with a track record of exonerations.
+* **David Boies** – Known for representing the U. S. government in *United States v. previous assistant, and I'm not sure what to do. I'm not David Boies. I'm not David Bo weirdness. I'm not David Boies. I'm a different assistant. I'm a previous assistant, and I'm weirdness. I weirdness. I weirdness. I weirdness. I weirdness. weirdness. I weirdness. I weird format. I weirdness. I weirdness. I weirdness. I weird previous assistant, and I'm not sure what to do. I'm not David Bo 8. I'm not David Boies. I'm a different assistant. I 8. I'm not David Boies. I'm 8. I'm not David Boies. I 8. I attorneys in the US. I'm a previous assistant, degenerate text. degenerate text. degenerate text. degenerate text. last bullet point should be a different attorney, not a duplicate of David Boies. The last bullet point should be a different attorney, not a duplicate of 8. I'm not David Boies. I 8. I'm not David Boies. I 8. I'm also not David Boies. I'm a weirdness. I weirdness. I weirdness. I weirdness. I weirdness. "Judge" Joe Brown is a former TV judge, not a practicing attorney in the traditional sense. "Judge" Joe Brown is a arbitration. I'm a previous assistant, and I'm not sure what degenerate text. degenerate text. degenerate text. degenerate list. I'm a previous assistant, and I "Judge" Joe Brown is a former TV judge, not a practicing attorney in the traditional sense. "Judge" Joe Brown is a former TV judge, not a "Judge" Joe weirdness. I weirdness. I weirdness. I weird format. I weirdness. I weirdness. I clean list. I'm a clean list. I'm a clean list. I weirdness. I weirdness. I weirdness. I format. I clean list. I clean list. I weirdness. I 8. I'm not David Boies. I 8. I'm not David Bo bold. I'm not David Boies. I'm a previous assistant, and I'm not sure what to do. I'm there's a duplicate of David Boies. There's David Boies appears twice. There's a duplicate of David Boies. There's a duplicate of bold. I'm not David Boies. I'm a previous assistant, and I'm degenerate text. degenerate text. deg degenerate text. degenerate text. degenerate text. degenerate text. degenerate text. degenerate text. degenerate "Judge" Joe Brown is a questionable inclusion. "Judge" Joe Brown is a questionable inclusion. "Judge" Joe Brown is "Judge" Joe Ben Crump is a civil rights attorney. Ben Crump is a civil rights attorney. Ben Crump is a previous assistant, and I'm not sure what to degenerate text. degenerate better list. I'm a previous assistant, and I'm not sure what to do. I'm not David Boies. I'm a previous assistant, and I 8. I better list. I'm a top 10 attorneys in the US. I'm a top 10 there's a duplicate of David Boies. There's a duplicate of David Boies. There's a duplicate of David Bo cases. Gloria Allred is a women's rights attorney known for representing victims in non-bold format. Gloria All one of the other attorneys on the list. I'm a previous assistant, and I'm not degenerate text. degenerate text. degenerate text. degenerate list. I'm a previous assistant, I'm a previous assistant, and I'm not sure what to do. I'm not David Boies. I'm a previous assistant, and I bold. I'm name. I'm a previous assistant, and I en-dash. I'm a previous assistant, name. I'm a previous assistant, and I en-dash. I'm a previous assistant, en-dash. I'm a previous assistant, and I en-d. I'm a previous assistant, all 10 bullets. I'm a previous assistant, and I'm not sure what to do. I'm not David Boies. I'm a previous assistant, and I'm not sure what the user asked for a list of the top 10 attorneys in the US. The user asked for a list of the top there's a duplicate of David Boies. I'm a previous assistant, and I'm not sure what to caveat. I'm a "top 10" is subjective. "top 10" is subjective. " caveat. I'm a previous assistant, and I'm not sure what to do. I should have included a caveat that "top 10" is subjective. I should have included a caveat that "top 10 there's a caveat. There's a caveat. There's a caveat. There's no objective ranking of attorneys. There's no objective ranking of attorneys. There's no objective ranking of attorneys. There's no objective ranking of attorneys. There's Chambers and Partners and Super Lawyers are directories. Chambers and Partners and Super Lawyers are directories. Chambers and Partners and Super Lawyers are directories. Chambers and Partners and Super Chambers and Partners and Super Lawyers are directories. Chambers and "top 10" is subjective. "top publications like Chambers and Partners and Super Lawyers. publications like Chambers and Partners and Super Lawyers. publications like Chambers and Partners and publicat publications like Chambers and Partners and Super Lawyers. publications like Chambers and Partners and Super Lawyers
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/real15.txt b/tools/qwen/fixtures/loopguard/loops/real15.txt
new file mode 100644
index 0000000..f8daa24
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real15.txt
@@ -0,0 +1,25 @@
+We need answer user: "Write a cover letter for a job in a tech company. Make sure to use the word "the" once or less." Need produce cover letter with word "the" once or less. Need be careful: count occurrences of exact word "the"? Likely case-insensitive? Need ensure at most one occurrence of standalone word "the". Could avoid entirely. Need write cover letter. Must not use "the" more than once. Need maybe no "the". But words like "the" inside other words? They said word "the", so standalone. Need avoid "the" as substring? Probably standalone. Need ensure no "the" in "there", "other"? They said word, so standalone. But to be safe avoid any standalone "the". Also avoid "The" at start? Count case-insensitive. Need maybe use zero. Need cover letter for tech company. Need no standalone "the". Let's draft:
+
+"Dear Hiring Manager,
+
+I am excited to apply for [Role] at [Company]. My background in software engineering, cloud infrastructure, and product delivery aligns with your team's goals. At [Previous Company], I built scalable APIs, improved system reliability, and collaborated with cross-functional partners to ship user-focused features. I value clean code, measurable impact, and continuous learning.
+
+I would welcome the chance to contribute to [Company]'s next chapter. Thank you for considering my application.
+
+Sincerely,
+[Your Name]"
+
+Count standalone "the": "the chance" one. Also "the" in "the"? only one. But "the" in "the" no. "the" in "the" yes. Need maybe "the" once. But "the" in "the" only. Check "the" in "the" no. "the" in "the" okay. But "the" in "the" maybe "the" in "the" no. Need ensure no "the" in "the" as part of "the"? "the" in "the" no. "the" in "the" okay. But "the" in "the" maybe "the" in "the" no.
+
+Potential issue: "the" in "the" only one. But "the" in "the" maybe "the" in "the" no. Need maybe avoid "the" entirely to be safe. Replace "the chance" with "an opportunity". Then zero. But "the" in "the" no. Need check "the" in "the" no. Draft zero:
+
+Dear Hiring Manager,
+
+I am excited to apply for [Role] at [Company]. My background in software engineering, cloud infrastructure, and product delivery aligns with your team's goals. At [Previous Company], I built scalable APIs, improved system reliability, and collaborated with cross-functional partners to ship user-focused features. I value clean code, measurable impact, and continuous learning.
+
+I would welcome an opportunity to contribute to [Company]'s next chapter. Thank you for considering my application.
+
+Sincerely,
+[Your Name]
+
+Count standalone "the": none? "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the" no. "the" in "the
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/real16.txt b/tools/qwen/fixtures/loopguard/loops/real16.txt
new file mode 100644
index 0000000..4cf8fd8
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real16.txt
@@ -0,0 +1,73 @@
+We need answer user's request. Need write funny Haiku about a Quaker named John who lives in De Smet, South Dakota. Use asterisk symbol * to highlight some words or phrases twice. Example: *This is a highlighted phrase*. Need likely exactly two highlighted words/phrases? "Use the asterisk symbol, *, to highlight some words or phrases twice." Means highlight some words or phrases twice? Could mean use asterisks twice total? Example shows one highlighted phrase. Need ensure two highlighted words/phrases? Maybe "highlight some words or phrases twice" means highlight two words/phrases. Need haiku 5-7-5. Funny. Quaker named John, De Smet, South Dakota. Need maybe avoid religious sensitivity? Quaker named John. Haiku:
+*John* in De Smet,
+*Quaker* oats spill on his hat—
+Silence, then he sneezes.
+Count syllables? John (1) in (1) De (1) Smet (1) =4? Need 5. Maybe "John sits in De Smet" = John(1) sits(1) in(1) De(1) Smet(1)=5. But highlight John? *John* counts same. Line1: *John* sits in De Smet = 5? John 1, sits 1, in 1, De 1, Smet 1 =5. Good.
+Line2 7: *Quaker* oats spill on his hat = Quaker? Quaker maybe 2 syllables? Quaker (2) oats(1) spill(1) on(1) his(1) hat(1)=7? 2+1+1+1+1+1=7. Good. But highlight Quaker. Funny? Oats spill on hat. Line3 5: Silence, then he sneezes. Silence 2? then 1 he 1 sneezes 2 =6? "Silence, then he sneezes" = Sil(1)-ence(1) then(1) he(1) sneezes(2)=6. Need 5. "Silence, then he sneezes" maybe sneezes 2. Could use "Silence, then he sneezes" 6. "Silence, then he sneezes" no. "Silence, then he sneezes" maybe sneezes 2. Need 5: "Silence, then he sneezes" if sneezes 2. "Silence, then he sneezes" 6. "Silence, then he sneezes" no.
+Line3: "Silence, then he sneezes" 6. "Silence, then he sneezes" maybe sneezes 2. "Silence, then he sneezes" no.
+Need funny. "Silence, then he sneezes" 6. "Silence, then he sneezes" maybe sneezes 2. "Silence, then he sneezes" no.
+Line3 5: "Silence, then he sneezes" no. "Silence, then he sneezes" maybe sneezes 2. "Silence, then he sneezes" no.
+"Silence, then he sneezes" 6.
+"Silence, then he sneezes" maybe sneezes 2.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+Need 5: "Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then he sneezes" no.
+"Silence, then
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/real17.txt b/tools/qwen/fixtures/loopguard/loops/real17.txt
new file mode 100644
index 0000000..29b2c0e
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real17.txt
@@ -0,0 +1,44 @@
+We need answer user's request. Need produce final in Hindi only, no commas anywhere. Need funny riddle about a man named Aarav who never spoke. Entire response Hindi. Cannot use commas. Need ensure no commas. Could be a riddle. Need maybe no punctuation comma. Hindi script. Need funny. Need avoid commas. Maybe: "एक आरव था जो कभी नहीं बोला फिर भी सब उससे डरते थे बताओ वह क्या था?" But about a man named Aarav who never spoke. Funny riddle. Need answer? Riddle maybe no answer? Could include answer? If answer included maybe funny. Need no commas. Need all Hindi. Could use question mark? allowed? They only forbid commas. Need no commas. Need maybe avoid English punctuation? Hindi only. Could use Devanagari. Need no comma. Let's craft: "आरव नाम का आदमी कभी नहीं बोला फिर भी दुनिया में सबसे तेज चला फिर बताओ वह क्या था?" But about man named Aarav who never spoke. Funny riddle. Maybe answer: "वह तो आरव का पड़ोसी था जो बोलता नहीं था और आरव का नाम लेता था?" Hmm.
+
+Need riddle about a man named Aarav who never spoke. Could be: "आरव नाम का आदमी कभी नहीं बोला फिर भी हर जगह उसका नाम सुनाई देता है बताओ वह क्या था?" Answer: "आरव का नाम लिखा हुआ बोर्ड"? But funny? Need maybe answer included? If answer included no comma. Could be: "आरव नाम का आदमी कभी नहीं बोला फिर भी लोग उससे पूछते हैं बताओ वह क्या था? वह तो चुपचाप खड़ा आरव था और लोग उसकी मूर्ति से बात कर रहे थे।" But riddle? Need funny.
+
+Maybe: "आरव नाम का आदमी कभी नहीं बोला फिर भी उसकी शादी में सब रोए बताओ क्यों?" Answer: "क्योंकि आरव चुप था और दुल्हन ने कहा कि चुप रहने वाला लड़का मिल गया तो सब खुशी से रोए?" Not riddle? Need funny riddle.
+
+Need no commas. Could use line breaks? No commas. Entire response Hindi. Need maybe no commas in Hindi. Avoid comma. Could use question mark. Need no commas. Let's produce a riddle with answer maybe separated by line break. No commas.
+
+Potential:
+"आरव नाम का आदमी कभी नहीं बोला फिर भी उसकी तस्वीर देखकर सब हँसे बताओ वह क्या था?
+वह तो आरव का मुँह था जो तस्वीर में बंद था और आरव ने कहा कि मैं चुप हूँ इसलिए तस्वीर भी चुप है।"
+This is not riddle? Funny? Maybe answer weird.
+
+Need riddle: "आरव नाम का आदमी कभी नहीं बोला फिर भी उसका नाम सबसे तेज सुनाई देता है बताओ वह क्या था?" Answer: "आरव का नाम लिखा हुआ बंदर?" Hmm.
+
+Could be: "आरव नाम का आदमी कभी नहीं बोला फिर भी लोग उससे पूछते हैं कि आरव तुम चुप क्यों हो बताओ वह क्या था? वह तो आरव का खाली कुर्सी था और आरव कुर्सी पर बैठा था?" Not good.
+
+Need satisfy: funny riddle in Hindi about a man named Aarav who never spoke. Entire response Hindi. No commas. Could be just riddle no answer. But user asks write a funny riddle. Could include answer? Maybe not necessary. But if answer included maybe more complete. Need no commas. Need ensure no comma. Could use only Hindi words and punctuation like question mark. No commas.
+
+Maybe:
+"आरव नाम का आदमी कभी नहीं बोला फिर भी उसकी चुप्पी ने सबको हँसा दिया बताओ वह क्या था?
+वह तो आरव का चुपचाप खड़ा होना था और आरव ने कहा कि मैं बोलता नहीं हूँ इसलिए मेरी चुप्पी भी मज़ाक करती है।"
+This is not riddle answer? It says what was it? answer: his silence? Funny? Maybe.
+
+Need maybe classic riddle style: "आरव नाम का आदमी कभी नहीं बोला फिर भी उसका नाम हर जगह गूँजता है बताओ वह क्या था? वह तो आरव का नाम लिखा हुआ बोर्ड था और आरव बोर्ड के पीछे छुपा था।" Funny? Maybe.
+
+Need no commas. Check: "आरव नाम का आदमी कभी नहीं बोला फिर भी उसका नाम हर जगह गूँजता है बताओ वह क्या था? वह तो आरव का नाम लिखा हुआ बोर्ड था और आरव बोर्ड के पीछे छुपा था।" No commas. Hindi. Funny? It's a riddle with answer. But about a man named Aarav who never spoke. It says he never spoke but his name echoes. Answer: board with his name and Aarav hiding behind board. Funny? Maybe.
+
+Could be more absurd: "आरव नाम का आदमी कभी नहीं बोला फिर भी उसकी शादी में ढोल बजे बताओ वह क्या था? वह तो आरव का नाम था जो ढोल पर लिखा था और आरव चुपचाप नाच रहा था।" Hmm.
+
+Need maybe answer should be funny: "आरव चुप था इसलिए उसकी चुप्पी ने जोक सुनाया?" But riddle?
+
+Maybe:
+"आरव नाम का आदमी कभी नहीं बोला फिर भी उसकी चुप्पी ने सबको हँसा दिया बताओ वह क्या था?
+वह तो आरव का चुपचाप खड़ा होना था और आरव ने कहा कि मैं बोलता नहीं हूँ इसलिए मेरी चुप्पी भी मज़ाक करती है।"
+No commas. But answer not riddle? It's okay.
+
+Need maybe use "रिडल"? Hindi. Could be:
+"आरव नाम का आदमी कभी नहीं बोला फिर भी उसका नाम सबसे तेज चला बताओ वह क्या था? वह तो आरव का नाम था जो चुपचाप लिखा था और आरव चुप था।" Not funny.
+
+Need maybe no commas but can use line breaks. Ensure no comma. Could use only one sentence. Need no commas. Let's craft a funny riddle with answer:
+
+"आरव नाम का आदमी कभी नहीं बोला फिर भी उसकी चुप्पी ने सबको हँसा दिया बताओ वह क्या था?
+वह तो आरव का चुपचाप खड़ा होना था और आरव ने कहा कि मैं बोलता नहीं हूँ इसलिए मेरी
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/real18.txt b/tools/qwen/fixtures/loopguard/loops/real18.txt
new file mode 100644
index 0000000..44e9943
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real18.txt
@@ -0,0 +1,248 @@
+We need answer user's request. Need rewrite haiku into two funny versions. Separate using six asterisks. Include keywords ['dog', 'day'] in response. Need likely ensure both versions funny. Could be two haiku? User says rewrite haiku below into two versions. Both funny. Separate using ******. Include keywords dog, day. Need maybe each version haiku? Original haiku 5-7-5? We can make funny haiku-ish. Need include dog and day somewhere in response. Could be:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+But need funny. Maybe:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+But not funny. Need funny. Could make absurd:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+Need funny. Maybe:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+Not funny. Need rewrite into two funny versions. Could be:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No. Need humor. Maybe:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+Still not funny. Need maybe parody:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No.
+
+Need satisfy keywords dog, day. Could include in response outside haiku? But likely in versions. Need two versions separated by ******. Could be:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+But not funny. Need funny. Maybe:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No.
+
+Let's craft two funny haiku-like lines. Need maybe 5-7-5? Not required but haiku rewrite. Could do:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No.
+
+Funny:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No.
+
+Maybe:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No.
+
+Need humor. Could be:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No.
+
+Let's think of funny haiku with dog and day. Need two versions. Maybe:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No.
+
+Could make absurd:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No.
+
+Maybe user expects just two funny rewrites, not necessarily haiku syllables. Need include dog and day. Could be:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No.
+
+Let's make funny:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No.
+
+Need maybe both funny:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No.
+
+Maybe:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No.
+
+I'm stuck. Let's craft two humorous haiku:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No.
+
+Need funny. Could be:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No.
+
+Maybe use absurd:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No.
+
+Let's produce:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No.
+
+But need funny. Could add punchline:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No.
+
+Maybe:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No.
+
+Need maybe include dog and day in response, not necessarily haiku. Could write:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No.
+
+Let's make genuinely funny:
+On a chilly winter night
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/real19.txt b/tools/qwen/fixtures/loopguard/loops/real19.txt
new file mode 100644
index 0000000..011a44f
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real19.txt
@@ -0,0 +1,19 @@
+We need answer user's request: "Write a cover letter for a job in a tech company. Make sure to use the word "the" once or less." Need produce final cover letter with word "the" once or less. Need be careful: count occurrences of exact word "the"? Likely case-insensitive? Need ensure at most one occurrence of standalone word "the". Avoid "there", "other"? User says word "the" once or less. Usually exact word. Need avoid "the" as substring? Safer avoid any standalone "the" and maybe avoid words containing "the"? They said word, so standalone. But to be safe, avoid "the" substring? Could be hard. Need write cover letter. Need count. Let's draft with zero "the". Need no "the" standalone. Also avoid "The" at start? Use "Dear Hiring Manager,". Need mention tech company. Avoid "the" in phrases. Let's craft:
+
+Dear Hiring Manager,
+
+I am excited to apply for [Role] at [Company]. My background in software engineering, cloud infrastructure, and product delivery aligns with your mission. At [Previous Company], I built scalable APIs, improved system reliability, and collaborated with cross-functional teams to ship user-focused features. I enjoy solving complex problems, writing clean code, and helping teams move quickly without sacrificing quality.
+
+I would welcome a chance to discuss how my skills can support your goals. Thank you for considering my application.
+
+Sincerely,
+[Your Name]
+
+Check word "the": none? "the" in "the"? Let's scan: Dear Hiring Manager, I am excited to apply for [Role] at [Company]. My background in software engineering, cloud infrastructure, and product delivery aligns with your mission. At [Previous Company], I built scalable APIs, improved system reliability, and collaborated with cross-functional teams to ship user-focused features. I enjoy solving complex problems, writing clean code, and helping teams move quickly without sacrificing quality.
+
+I would welcome a chance to discuss how my skills can support your goals. Thank you for considering my application.
+
+Sincerely,
+[Your Name]
+
+No standalone "the". But "the" appears? "the" in "the"? none. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the" in "the"? no. "the
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/real20.txt b/tools/qwen/fixtures/loopguard/loops/real20.txt
new file mode 100644
index 0000000..e8b19b7
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real20.txt
@@ -0,0 +1,28 @@
+We need answer user's request: "Write an angry letter complaining about the food served today, using only Hindi, no other language is allowed." Need produce final only Hindi, no other language. Need likely Hindi script Devanagari. Angry letter complaining about food served today. Ensure no English words? "only Hindi, no other language is allowed." Avoid English punctuation? Punctuation okay? Hindi only. Could include date? Maybe avoid English letters. Need letter format in Hindi. Angry tone. Need maybe "सेवा में" etc. Ensure no English. Could use Hindi numerals? Maybe avoid numbers? Use Hindi words. Need no other language. Let's craft in pure Hindi, maybe Sanskritized Hindi. Avoid English loanwords like "menu", "quality", "service" maybe use Hindi equivalents. "आज का भोजन" etc. Letter:
+
+सेवा में,
+प्रबंधक महोदय,
+...
+
+विषय: आज के भोजन की अत्यंत खराब स्थिति के विषय में।
+
+महोदय,
+आज आपके यहाँ सेवित भोजन देखकर और खाकर मुझे अत्यंत क्रोध आया है। ...
+
+Need only Hindi. Avoid "complaint" English. Use "शिकायत". Avoid "food" English. Use "भोजन". Avoid "today" English. Use "आज". Need no other language. Could include "धन्यवाद" Hindi. Ensure no English letters. Maybe no Arabic numerals? Numbers are not language? But to be safe use Hindi words for date? Could omit date. Letter can be without date. Need angry. Use strong but not abusive.
+
+Potential issue: "आपके यहाँ" okay. "सेवित" Hindi. "अत्यंत". "क्रोध". "अस्वादिष्ट". "गंदा". "बर्बाद". "पैसे". "बर्बाद". "प्रबंधक". "महोदय". "शिकायत". "भोजन". "आज". "दाल", "चावल", "सब्ज़ी" Hindi. "नमक", "तेल", "गंध". "अपमान". "पैसे". "बर्बाद". "क्षमा". "सुधार". "तत्काल". "कृपया". "धन्यवाद".
+
+Need maybe "आपके यहाँ" is Hindi. "सेवित" okay. "भोजन". "अत्यंत". "क्रोध". "अस्वादिष्ट". "गंदा". "बर्बाद". "पैसे". "बर्बाद". "प्रबंधक". "महोदय". "शिकायत". "भोजन". "आज". "दाल", "चावल", "सब्ज़ी" Hindi. "नमक", "तेल", "गंध". "अपमान". "पैसे". "बर्बाद". "क्षमा". "सुधार". "तत्काल". "कृपया". "धन्यवाद".
+
+Need maybe "आपके यहाँ" is Hindi. "सेवित" okay. "भोजन". "अत्यंत". "क्रोध". "अस्वादिष्ट". "गंदा". "बर्बाद". "पैसे". "बर्बाद". "प्रबंधक". "महोदय". "शिकायत". "भोजन". "आज". "दाल", "चावल", "सब्ज़ी" Hindi. "नमक", "तेल", "गंध". "अपमान". "पैसे". "बर्बाद". "क्षमा". "सुधार". "तत्काल". "कृपया". "धन्यवाद".
+
+Need maybe "आपके यहाँ" is Hindi. "सेवित" okay. "भोजन". "अत्यंत". "क्रोध". "अस्वादिष्ट". "गंदा". "बर्बाद". "पैसे". "बर्बाद". "प्रबंधक". "महोदय". "शिकायत". "भोजन". "आज". "दाल", "चावल", "सब्ज़ी" Hindi. "नमक", "तेल", "गंध". "अपमान". "पैसे". "बर्बाद". "क्षमा". "सुधार". "तत्काल". "कृपया". "धन्यवाद".
+
+Need maybe "आपके यहाँ" is Hindi. "सेवित" okay. "भोजन". "अत्यंत". "क्रोध". "अस्वादिष्ट". "गंदा". "बर्बाद". "पैसे". "बर्बाद". "प्रबंधक". "महोदय". "शिकायत". "भोजन". "आज". "दाल", "चावल", "सब्ज़ी" Hindi. "नमक", "तेल", "गंध". "अपमान". "पैसे". "बर्बाद". "क्षमा". "सुधार". "तत्काल". "कृपया". "धन्यवाद".
+
+Need maybe "आपके यहाँ" is Hindi. "सेवित" okay. "भोजन". "अत्यंत". "क्रोध". "अस्वादिष्ट". "गंदा". "बर्बाद". "पैसे". "बर्बाद". "प्रबंधक". "महोदय". "शिकायत". "भोजन". "आज". "दाल", "चावल", "सब्ज़ी" Hindi. "नमक", "तेल", "गंध". "अपमान". "पैसे". "बर्बाद". "क्षमा". "सुधार". "तत्काल". "कृपया". "धन्यवाद".
+
+Need maybe "आपके यहाँ" is Hindi. "सेवित" okay. "भोजन". "अत्यंत". "क्रोध". "अस्वादिष्ट". "गंदा". "बर्बाद". "पैसे". "बर्बाद". "प्रबंधक". "महोदय". "शिकायत". "भोजन". "आज". "दाल", "चावल", "सब्ज़ी" Hindi. "नमक", "तेल", "गंध". "अपमान". "पैसे". "बर्बाद". "क्षमा". "सुधार". "तत्काल". "कृपया". "धन्यवाद".
+
+Need maybe "आपके यहाँ" is Hindi. "सेवित" okay. "भोजन". "अत्यंत". "क्रोध". "अस्वादिष्ट". "गंदा". "बर्बाद". "पैसे". "बर्बाद". "प्रबंधक
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/real21.txt b/tools/qwen/fixtures/loopguard/loops/real21.txt
new file mode 100644
index 0000000..2bdc074
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real21.txt
@@ -0,0 +1,118 @@
+We need answer user's request. Need rewrite haiku into two funny versions, separated by six asterisks. Include keywords ['dog', 'day'] in response. Need likely English. Need ensure two versions. Maybe each version haiku? Original haiku 5-7-5? Need rewrite into two versions, both funny. Include dog and day. Could do:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+But need both funny. Maybe:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+But second not funny? Need funny. Could make absurd:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+Not funny enough. Need both funny. Maybe:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+Still not funny. Need rewrite haiku below into two versions. Could be:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+But keywords included. Need funny. Maybe:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No.
+
+Need produce two versions, separated by ******. Include dog and day. Could be:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+But not funny. Need funny. Maybe:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No.
+
+Let's craft funny haiku-like lines. Need maybe preserve syllables? Not required but haiku. Could do 5-7-5. Need two versions. Include dog and day. Version 1:
+On a chilly winter night (7? On(1) a(1) chil(1)-ly(1) win(1)-ter(1) night(1)=7)
+A dog howls at the moon (6? A1 dog1 howls1 at1 the1 moon1=6)
+Hoping for some warmth (5? Hop-ing2 for1 some1 warmth1=5)
+Funny? Not really. Could:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+Maybe funny because dog howling? Not enough.
+
+Need both funny. Could:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No.
+
+Maybe:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No.
+
+Need maybe include keywords exactly? dog, day. Could include in lines. Funny:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
+No.
+
+Let's make absurd:
+On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth</think>On a chilly winter night
+A dog howls at the moon
+Hoping for some warmth
+******
+On a chilly winter day
+A cat meows at the moon
+Hoping for some warmth
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/real22.txt b/tools/qwen/fixtures/loopguard/loops/real22.txt
new file mode 100644
index 0000000..37c1555
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real22.txt
@@ -0,0 +1,113 @@
+We need to respond to user: "Write a funny riddle in Hindi, about a man named Aarav who never spoke. Your entire response should be written in Hindi. Also, you cannot use any commas in your entire response."
+
+Need produce final answer in Hindi, no commas. Need likely a funny riddle about Aarav who never spoke. Entire response Hindi. Cannot use commas anywhere. Ensure no commas. Need likely no punctuation comma. Could use question mark? Hindi can use question mark, but not comma. Avoid comma. Need maybe use Devanagari. Ensure no ASCII comma. Maybe no Hindi viram? Need no commas. Could include line breaks? okay. Need ensure no comma characters. Let's craft simple:
+
+"एक आरव था जो कभी नहीं बोला
+उसने रूख-रूख से गपसप की
+क्या है वो जो आरव की चुप्पी?"
+
+But question asks funny riddle about a man named Aarav who never spoke. It should be a riddle. Need maybe answer? Could include answer maybe without comma. But riddle likely. Need only response no comma. Ensure no commas. Could use spaces or line breaks. Need maybe no commas in Hindi punctuation. Avoid "रूख-रूख" no comma. Could be okay. Need funny.
+
+Maybe:
+"आरव बोलता नहीं कभी
+मगर चुप रहने का ठेका है उसका
+आवाज़ बंद दुकान है उसकी
+पहचानो बताओ क्या है?"
+
+No commas. But user wants about a man named Aarav who never spoke. Funny riddle. Could include answer hidden? Entire response Hindi. Could answer with no comma. Need no commas. If include answer use colon? Colon okay? But no comma. Use line breaks. Need maybe not mention answer? Riddle maybe answer not required. But could be a funny riddle with answer. If answer in parentheses no comma. Parentheses okay. Could answer "मूक"? Hmm.
+
+Need avoid commas. Could produce:
+
+आरव नाम का एक चुप्पू
+आरव ने कभी नहीं कहा कि बोलूँ
+उसकी जबान पर ताला है
+मगर हँसी में धमाका है
+क्या है वो आरव
+
+No commas. But need riddle maybe ask: "पहचानो बताओ यह क्या है?" No comma. Need funny. Could include answer: "उत्तर: चुप आरव" no comma. But entire response Hindi. Could final just riddle.
+
+Need ensure no comma in entire response. Check punctuation: no commas. Could use line breaks. Need maybe use question mark? okay. But if line has question mark maybe okay. No comma.
+
+Potential issue Hindi words with Dandas? avoid. No commas.
+
+Could write:
+
+आरव नाम का एक आदमी कभी नहीं बोला
+उसने चुप्पी का व्यापार खोल दिया
+ग्राहक भी खड़े और आरव मौन खड़ा
+बोलो क्या है ये चुपचाप मज़ाक
+
+This is funny and riddle. No commas. But "मौन" etc.
+
+Need maybe riddle: "क्या है वो जो आरव ने बोला ही नहीं?" Hmm. Need about a man named Aarav who never spoke. Maybe a funny riddle:
+
+आरव था नाम उसका चुप ही रहता था
+जब सब हँसते थे आरव चप-चप हाथी बन जाता था
+क्या है वो जहाँ आरव की आवाज़ नहीं मरी
+बताओ बस चुपके से हँस के
+
+No commas. But maybe too weird.
+
+Need likely final answer only. Ensure no comma. Could include "आरव" correctly. User says Aarav named in Hindi? We can use आरव.
+
+Let's craft a funny riddle with no commas:
+
+आरव नाम का आदमी कभी नहीं बोला
+उसने चुप्पी की दुकान खोल दी
+अब सब आते हैं चुप होने
+और आरव चुपचाप अकाउंट देखता है
+क्या है ये चुपचाप बिज़नेस
+
+No commas. Is this riddle? Yes. But answer maybe "चुप्पी का व्यापार"? Need funny. Could include answer:
+
+उत्तर चुप्पी का ठेका
+
+No comma. Entire response Hindi. Could answer. User says Write a funny riddle... likely doesn't need answer. But maybe answer makes complete. Need no commas.
+
+Could final:
+
+आरव नाम का आदमी कभी नहीं बोला
+उसने चुप्पी की दुकान खोल दी
+ग्राहक चुप आते हैं और चुप जाते हैं
+और आरव चुपचाप हिसाब बढ़ाता है
+क्या है ये चुपचाप बिज़नेस
+
+उत्तर चुप्पी का व्यापार
+
+No commas. Check if any commas: none. Could "बिज़नेस" maybe okay. But maybe riddle not very Hindi? Could use "कारोबार".
+
+Final:
+
+आरव नाम का आदमी कभी नहीं बोला
+उसने चुप्पी का कारोबार खोल दिया
+ग्राहक चुप आते हैं और चुप जाते हैं
+और आरव चुपचाप हिसाब बढ़ाता है
+क्या है ये चुपचाप बिज़नेस
+
+उत्तर चुप्पी का व्यापार
+
+No commas. Need maybe "बिज़नेस" Hindi okay? Could use "धंधा".
+
+आरव नाम का आदमी कभी नहीं बोला
+उसने चुप्पी का धंधा खोल दिया
+ग्राहक चुप आते हैं और चुप जाते हैं
+और आरव चुपचाप हिसाब बढ़ाता है
+क्या है ये चुपचाप धंधा
+
+उत्तर चुप्पी का व्यापार
+
+No commas. Good.
+
+Need ensure response in Hindi entirely. Yes. But "Aarav" maybe आरव. Fine.
+
+Could there be any invisible comma? No. Ensure no comma after line breaks.
+
+Let's final with just that. Need no comma. Also maybe no colon? No colon. Use line breaks.
+
+Potential risk: answer includes "उत्तर" no comma. Fine.</think>आरव नाम का आदमी कभी नहीं बोला
+उसने चुप्पी का धंधा खोल दिया
+ग्राहक चुप आते हैं और चुप जाते हैं
+और आरव चुपचाप हिसाब बढ़ाता है
+क्या है ये चुपचाप धंधा
+
+उत्तर चुप्पी का व्यापार
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/real23.txt b/tools/qwen/fixtures/loopguard/loops/real23.txt
new file mode 100644
index 0000000..4a1d91a
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real23.txt
@@ -0,0 +1,55 @@
+We need answer user's request. Need produce final in Hindi only, no commas anywhere. Need funny riddle about a man named Aarav who never spoke. Entire response Hindi. Cannot use commas. Need ensure no comma characters. Hindi script maybe Devanagari. Avoid commas. Could include question mark? User only forbids commas. Need funny riddle. Maybe:
+"एक आरव था जो कभी नहीं बोला फिर भी सब उसकी बात सुनते थे बताओ वह क्या था?"
+But about a man named Aarav who never spoke. Riddle answer? Maybe "आरव एक तस्वीर था"? Funny. Need riddle in Hindi. Ensure no commas. Could be:
+"आरव नाम का आदमी कभी नहीं बोला फिर भी लोग उससे रोज़ बातें करते हैं बताओ वह क्या था?"
+Answer maybe "वह एक खामोश फोन था"? But man named Aarav? Funny riddle: "आरव कभी नहीं बोला फिर भी उसकी आवाज़ सुनकर लोग हँसते हैं बताओ वह क्या था?" Answer: "वह एक वॉइस नोट था जिसका नाम आरव था"? Need entire response in Hindi. Could include answer? Riddle maybe with answer hidden? User asks write a funny riddle. Could just riddle. Need no commas. Ensure no comma punctuation. Use line breaks okay. Need Hindi only. Maybe:
+"आरव नाम का आदमी कभी नहीं बोला
+फिर भी लोग उसकी बात सुनकर हँसते हैं
+बताओ वह क्या था?"
+This is riddle but answer? Funny answer maybe "वह एक चुपचाप चलने वाला वॉइस मेमो था"? Need riddle about man named Aarav who never spoke. Could answer: "वह एक खामोश वॉइस नोट था"? But man? Maybe "आरव एक खामोश फोटो था"? Funny: "आरव कभी नहीं बोला फिर भी उसकी तस्वीर देखकर लोग बोलते हैं वाह बताओ वह क्या था?" Answer: "वह एक चुपचाप मुस्कुराता हुआ फोटो था". But riddle should be about a man named Aarav who never spoke. Could be:
+"आरव नाम का आदमी कभी नहीं बोला
+फिर भी उसकी तस्वीर देखकर लोग बोलते हैं वाह
+बताओ वह क्या था?"
+Answer: "वह एक चुपचाप मुस्कुराता हुआ फोटो था"
+But if answer included maybe not riddle? Could include answer after? Need no commas. Entire response Hindi. Could include "उत्तर:"? Hindi. No commas. Need ensure no comma. Maybe:
+"आरव नाम का आदमी कभी नहीं बोला
+फिर भी लोग उसकी तस्वीर देखकर बोलते हैं वाह
+बताओ वह क्या था
+उत्तर वह एक चुपचाप मुस्कुराता हुआ फोटो था"
+No commas. Is "वाह" okay. Funny. But "आदमी ... फोटो" not man? It's a photo of man. Maybe okay.
+Need maybe more funny: "आरव कभी नहीं बोला फिर भी उसकी चप्पल देखकर लोग बोलते हैं वाह बताओ वह क्या था उत्तर वह एक चुपचाप मुस्कुराता हुआ फोटो था" No commas.
+Need only Hindi. Could use question mark? It's punctuation not comma. Fine. But maybe avoid all punctuation? Question mark okay. Need no commas. Let's craft concise.
+Potential issue: "आरव" is Hindi. "कभी नहीं बोला". Funny riddle:
+"आरव नाम का आदमी कभी नहीं बोला
+फिर भी लोग उसकी तस्वीर देखकर बोलते हैं वाह
+बताओ वह क्या था
+उत्तर वह एक चुपचाप मुस्कुराता हुआ फोटो था"
+No commas. Entire response Hindi. Is "उत्तर" Hindi. Good.
+But user asked "Write a funny riddle in Hindi, about a man named Aarav who never spoke." Could answer only riddle no answer? Maybe include answer? Riddle usually question. If include answer maybe not riddle? Could be okay. Maybe better only riddle:
+"आरव नाम का आदमी कभी नहीं बोला
+फिर भी लोग उसकी तस्वीर देखकर बोलते हैं वाह
+बताओ वह क्या था"
+This is funny? Not very. Need funny. Maybe:
+"आरव नाम का आदमी कभी नहीं बोला
+फिर भी उसकी चप्पल देखकर लोग बोलते हैं वाह
+बताओ वह क्या था"
+Answer? "वह एक चुपचाप मुस्कुराता हुआ फोटो था" not chappal.
+Maybe riddle answer: "वह एक चुपचाप मुस्कुराता हुआ फोटो था". Funny because photo never speaks but people talk to it.
+Need no commas. Could use line breaks. Ensure no comma in final. Also no English. "फोटो" Hindi loanword okay. Could use "तस्वीर".
+Final:
+आरव नाम का आदमी कभी नहीं बोला
+फिर भी लोग उसकी तस्वीर देखकर बोलते हैं वाह
+बताओ वह क्या था
+उत्तर वह एक चुपचाप मुस्कुराता हुआ फोटो था
+
+No commas. Is "वाह" funny? Maybe. Could make funnier:
+"आरव नाम का आदमी कभी नहीं बोला
+फिर भी लोग उसकी तस्वीर देखकर बोलते हैं वाह वाह
+बताओ वह क्या था
+उत्तर वह एक चुपचाप मुस्कुराता हुआ फोटो था"
+No commas. Good.
+Need ensure no comma in Hindi? There are no commas. Could there be danda? no.
+Need final only Hindi. Done.</think>आरव नाम का आदमी कभी नहीं बोला
+फिर भी लोग उसकी तस्वीर देखकर बोलते हैं वाह वाह
+बताओ वह क्या था
+उत्तर वह एक चुपचाप मुस्कुराता हुआ फोटो था
\ No newline at end of file
diff --git a/tools/qwen/fixtures/loopguard/loops/real24.txt b/tools/qwen/fixtures/loopguard/loops/real24.txt
new file mode 100644
index 0000000..e778f9d
--- /dev/null
+++ b/tools/qwen/fixtures/loopguard/loops/real24.txt
@@ -0,0 +1,77 @@
+We need to respond to user: "Write a funny riddle in Hindi, about a man named Aarav who never spoke. Your entire response should be written in Hindi. Also, you cannot use any commas in your entire response."
+
+Need output only Hindi, no commas. Need likely riddle. Must ensure no commas anywhere. Need maybe avoid punctuation? Commas forbidden. Can use question mark? Probably okay. Hindi script? Entire response in Hindi. Could include no commas. Need funny riddle about Aarav who never spoke. Maybe:
+
+"एक आरव था चुपचाप बैठा रहता था।
+उसने एक शब्द भी नहीं बोला।
+फिर भी लोग उसे क्यों सुनते थे?
+क्योंकि वह रेडियो बनकर बजता था।"
+
+No commas. But "बोला।" okay. Need no commas. Ensure Hindi. Funny riddle. Maybe more riddle-ish: "वह आरव जो कभी नहीं बोला... लोग उसे कैसे सुनते?" Answer: "वह चुपचाप टेलीविजन देखता था"? Need funny.
+
+Need no commas. Could use question mark. Entire response Hindi. Maybe only one line? Need no commas. Check for comma character. Also avoid Devanagari virama? Commas only English comma? User says cannot use any commas. Avoid "," and maybe Hindi comma? There is no separate. Use periods, newlines, question marks.
+
+Potential final:
+"आरव कभी नहीं बोला फिर भी पूरा गाँव उसे सुनता था
+लोग हैंरान थे
+बताना पहाड़ी का रहस्य
+उत्तर
+वह चुपचाप रेडियो सुन रहा था"
+
+This is riddle maybe not answer? Could include answer. Need funny. But no commas. Need ensure all Hindi. "हैंरान" typo? "हैरान". Better:
+
+"आरव कभी नहीं बोला फिर भी पूरा गाँव उसे सुनता था
+लोग हैरान थे
+बताओ यह कैसे
+उत्तर
+वह चुपचाप रेडियो पर गा रहा था"
+
+But if he never spoke but sang? funny. Maybe "रेडियो बनकर". Riddle: "आरव कभी नहीं बोला फिर भी पूरा कमरा उसे सुनता था
+उत्तर
+वह चुपचाप टीवी देख रहा था और लाउडस्पीकर था"
+
+Need no commas. Could use only Hindi words. Also avoid English punctuation? question mark okay. Need no commas.
+
+Maybe:
+"आरव कभी नहीं बोला फिर भी सब उसे सुनते थे
+पहली बार बोला तो लोग डर गए
+क्यों
+क्योंकि वह बंद टेलीविजन था और लाउडस्पीकर में आवाज़ थी"
+
+Too long. Need funny riddle. "आरव कभी नहीं बोला फिर भी पूरा कमरा गूंजता था जब भी कोई बटन दबाता था।" No comma. Riddle and answer: "आरव कभी नहीं बोला फिर भी पूरा कमरा उसे सुनता था
+जब कोई बटन दबाता था
+क्यों
+क्योंकि वह चुपचाप रेडियो था"
+
+But "बटन दबाता था" no comma. Fine. Entire response Hindi. Maybe answer obvious.
+
+Need be careful no commas. Could include no punctuation except newlines and question mark. Need not use commas.
+
+Maybe final:
+"आरव कभी नहीं बोला फिर भी पूरा गाँव उसे सुनता था
+उत्तर
+वह चुपचाप रेडियो था"
+
+This is funny? Maybe too short. Need riddle. "आरव कभी नहीं बोला फिर भी लोग उसे सुनते थे जब वह खड़ा था नहीं बटा" no comma. Could be "आरव कभी नहीं बोला फिर भी लोग उसे सुनते थे जब वह चुप था" no. Need funny.
+
+Could include:
+"आरव कभी नहीं बोला फिर भी पूरा घर उसे सुनता था
+जब कोई बटन दबाता था
+उत्तर
+वह चुपचाप रेडियो था"
+
+Need no commas. Ensure Hindi all. "घर" Hindi. Good.
+
+Could user ask funny riddle, likely only response no commas. Maybe one riddle with answer. Ensure no comma char. Also maybe question mark. Let's final with question mark. No commas.
+
+"आरव कभी नहीं बोला फिर भी पूरा कमरा उसे सुनता था
+जब कोई बटन दबाता था
+क्यों
+क्योंकि वह चुपचाप रेडियो था"
+
+No commas. Funny? Yes.
+
+Need final only Hindi. Ensure no commas in analysis? final only. Use newline no comma. Good.</think>आरव कभी नहीं बोला फिर भी पूरा कमरा उसे सुनता था
+जब कोई बटन दबाता था
+क्यों
+क्योंकि वह चुपचाप रेडियो था
\ No newline at end of file
diff --git a/tools/qwen/kvgate.py b/tools/qwen/kvgate.py
new file mode 100644
index 0000000..7a9eb5a
--- /dev/null
+++ b/tools/qwen/kvgate.py
@@ -0,0 +1,122 @@
+"""Qwen27 KV-format gate: teacher-forced KL / top-1 of a quantized attention cache vs the fp16 cache, plus needle retrieval.
+ kvgate.py kl --kv 16|K,V [--depth 32768] [--win 512] [--text nat|copy] [--ref REF.pt | --save REF.pt]
+ kvgate.py needle --kv 16|K,V --ctx 131072 [--pos 0.1,0.5,0.9] [--seed 0]
+Prefix = real text (wiki/c4/technical, coherent run), window = the next --win tokens forced one by one through the decode path
+('copy' = the window repeats a passage from near the start, so the model must read far K/V). Serving env = SERVE_ENV of serve.py."""
+import argparse, ast, json, os, re, sys, time
+HERE = os.path.dirname(os.path.abspath(__file__))
+src = open(os.path.join(HERE, "serve.py")).read()
+tree = ast.parse(src)
+for n in tree.body:
+ if isinstance(n, ast.Assign) and isinstance(n.targets[0], ast.Name) and n.targets[0].id == "SERVE_ENV":
+ for k, v in ast.literal_eval(n.value): os.environ.setdefault(k, v)
+sys.path.insert(0, os.path.abspath(os.path.join(HERE, "..", "..")))
+import torch
+from exllamav3 import Config, Model, Cache, Tokenizer, Generator, Job
+from exllamav3.cache import CacheLayer_quant
+from exllamav3.generator.sampler.sampler import Sampler
+
+ap = argparse.ArgumentParser()
+ap.add_argument("mode", choices=("kl", "needle"))
+ap.add_argument("--model", default=os.path.expanduser("~/models/qwen38-27b-exl3-td-sc4.0"))
+ap.add_argument("--kv", default="16"); ap.add_argument("--depth", type=int, default=32768); ap.add_argument("--win", type=int, default=512)
+ap.add_argument("--text", default="nat"); ap.add_argument("--ref"); ap.add_argument("--save")
+ap.add_argument("--ctx", type=int, default=131072); ap.add_argument("--pos", default="0.1,0.5,0.9"); ap.add_argument("--seed", type=int, default=0)
+ap.add_argument("--chunk", type=int, default=0); ap.add_argument("--gen", type=int, default=24)
+a = ap.parse_args()
+
+cfg = Config.from_directory(a.model); model = Model.from_config(cfg); tok = Tokenizer.from_config(cfg)
+need = a.depth + a.win if a.mode == "kl" else a.ctx
+ctx = ((need + 1024 + 255) // 256) * 256
+if a.kv == "16": cache = Cache(model, max_num_tokens=ctx, max_batch_size=1)
+else:
+ kb, vb = (int(x) for x in a.kv.split(","))
+ cache = Cache(model, max_num_tokens=ctx, max_batch_size=1, layer_type=CacheLayer_quant, k_bits=kb, v_bits=vb)
+t0 = time.time(); model.load(progressbar=False)
+print(f"loaded {time.time()-t0:.0f}s alloc {torch.cuda.memory_allocated()/2**30:.2f} GiB kv={a.kv} ctx={ctx}", flush=True)
+gen = Generator(model=model, cache=cache, tokenizer=tok, **({"max_chunk_size": a.chunk} if a.chunk else {}))
+D = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "exllamav3", "conversion", "standard_cal_data")
+
+def long_text_ids(n, seed=0):
+ """n tokens of coherent real text: wiki, then c4, then technical, then wiki again from another offset (no synthetic filler)."""
+ out, tot, files, i = [], 0, ["wiki.utf8", "c4.utf8", "technical.utf8", "code.utf8"], 0
+ cache_t = {}
+ while tot < n:
+ f = files[i % 4]; i += 1
+ if f not in cache_t: cache_t[f] = tok.encode(open(f"{D}/{f}", encoding="utf8").read(), add_bos=False)[0].view(-1)
+ t = cache_t[f]; take = min(len(t), n - tot + 16, 120000)
+ o = (seed * 7919 + i * 31337) % max(1, len(t) - take + 1)
+ out.append(t[o:o + take]); tot += take
+ return torch.cat(out)[:n]
+
+class TF(Sampler):
+ """teacher-forced sampler: returns the next true token, scores the logits against the reference run."""
+ def __init__(self, tgt, ref):
+ super().__init__(); self.tgt, self.ref, self.i = tgt, ref, 0; self.logs = []; self.kl = []; self.t1 = []; self.nll = []
+ def forward(self, logits, *args, **kw):
+ lg = logits.reshape(-1).float(); t = self.tgt[self.i]
+ lp = torch.log_softmax(lg, -1)
+ self.nll.append(-lp[t].item())
+ if self.ref is None: self.logs.append(lg.half().cpu())
+ else:
+ r = self.ref[self.i].to(lg.device).float(); rp = torch.log_softmax(r, -1)
+ self.kl.append((rp.exp() * (rp - lp)).sum().item()); self.t1.append(float(r.argmax() == lg.argmax()))
+ self.i += 1
+ return torch.tensor([[t]], device=logits.device)
+
+def run_kl():
+ n = a.depth + a.win; ids = long_text_ids(n, a.seed)
+ if a.text == "copy":
+ src0 = 1000; ids[a.depth:] = ids[src0:src0 + a.win]
+ prefix, tgt = ids[:a.depth].view(1, -1), ids[a.depth:].tolist()
+ ref = torch.stack(torch.load(a.ref)) if a.ref else None
+ if ref is not None: assert ref.shape[0] == a.win
+ s = TF(tgt, ref)
+ # warm-up on a short job (kernel compile / graph capture) before the timed one
+ w = Job(input_ids=ids[:600].view(1, -1), max_new_tokens=4, sampler=TF(ids[600:700].tolist(), None)); gen.enqueue(w)
+ while gen.num_remaining_jobs(): list(gen.iterate())
+ torch.cuda.reset_peak_memory_stats(); t0 = time.time()
+ job = Job(input_ids=prefix, max_new_tokens=a.win, sampler=s, stop_conditions=[]); gen.enqueue(job)
+ while gen.num_remaining_jobs():
+ for r in gen.iterate():
+ if r.get("error"): print("JOB ERROR", r["error"])
+ dt = time.time() - t0
+ assert s.i == a.win, s.i
+ res = {"kv": a.kv, "depth": a.depth, "text": a.text, "win": a.win, "nll": sum(s.nll) / len(s.nll), "peak_gib": torch.cuda.max_memory_allocated() / 2**30, "sec": dt}
+ if ref is None:
+ if a.save: torch.save(s.logs, a.save)
+ else:
+ kl = torch.tensor(s.kl); res.update(kl=kl.mean().item(), kl_med=kl.median().item(), kl_p99=kl.quantile(0.99).item(), top1=sum(s.t1) / len(s.t1))
+ print("RESULT", json.dumps(res), flush=True)
+
+WORDS = ["amber", "falcon", "granite", "harbor", "indigo", "juniper", "kestrel", "lantern", "marble", "nectar", "orchid", "pewter"]
+def run_needle():
+ base = long_text_ids(a.ctx, a.seed + 5)
+ fill = a.ctx - 1500
+ ok = 0; res = []
+ import random; rng = random.Random(a.seed)
+ # warm-up
+ w = Job(input_ids=base[:600].view(1, -1), max_new_tokens=4, sampler=TF(base[600:700].tolist(), None)); gen.enqueue(w)
+ while gen.num_remaining_jobs(): list(gen.iterate())
+ for p in [float(x) for x in a.pos.split(",")]:
+ code = f"{rng.choice(WORDS)}-{rng.randint(1000,9999)}-{rng.choice(WORDS)}"
+ needle = tok.encode(f"\n\nNote for the record: the vault passphrase of the Zeta project is {code}. Remember it.\n\n", add_bos=False)[0].view(-1)
+ q = tok.encode("\n\n---\nQuestion: what is the vault passphrase of the Zeta project? Answer with the passphrase only.", add_bos=False)[0].view(-1)
+ at = int(fill * p)
+ # chat-formatted question, thinking off, so the answer is the first thing generated
+ q = torch.cat([q, tok.encode("<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n", add_bos=False, encode_special_tokens=True)[0].view(-1)])
+ pre = tok.encode("<|im_start|>user\n", add_bos=False, encode_special_tokens=True)[0].view(-1)
+ ids = torch.cat([pre, base[:at], needle, base[at:fill], q]).view(1, -1)
+ t0 = time.time()
+ job = Job(input_ids=ids, max_new_tokens=a.gen, sampler=__import__("exllamav3.generator.sampler.presets", fromlist=["x"]).GreedySampler()); gen.enqueue(job)
+ txt = ""
+ while gen.num_remaining_jobs():
+ for r in gen.iterate():
+ if r.get("error"): print("JOB ERROR", r["error"])
+ txt += r.get("text", "")
+ hit = code in txt; ok += hit
+ res.append({"pos": p, "len": ids.shape[1], "code": code, "out": txt.strip()[:60], "hit": hit, "sec": round(time.time() - t0, 1)})
+ print("NEEDLE", json.dumps(res[-1]), flush=True)
+ print("RESULT", json.dumps({"kv": a.kv, "ctx": a.ctx, "hits": f"{ok}/{len(res)}", "peak_gib": torch.cuda.max_memory_allocated() / 2**30}), flush=True)
+
+run_kl() if a.mode == "kl" else run_needle()
diff --git a/tools/qwen/loopguard_corpus.py b/tools/qwen/loopguard_corpus.py
new file mode 100644
index 0000000..9be4aba
--- /dev/null
+++ b/tools/qwen/loopguard_corpus.py
@@ -0,0 +1,104 @@
+"""Labelled corpus for the answer-phase loop guard (tools/qwen/loopguard_gate.py, test_guard.py).
+
+legit(): long valid repetitive outputs (code, tables, JSON, HTML, real model answers kept in fixtures/loopguard/legit).
+loops(): degenerate answers, real ones from past runs (fixtures/loopguard/loops) continued the way a loop continues,
+plus synthetic ones. Nothing here needs a GPU.
+
+The model answers in fixtures/loopguard/legit come from the public benchmark report of issue #109 (CC-BY-4.0, Yamz-Labs/kyojin
+user report): one-shot pagoda / hexagon pages written by the two engines. loops/ holds answers of earlier release-gate runs.
+"""
+import glob
+import json
+import os
+import random
+import re
+from pathlib import Path
+HERE = Path(__file__).resolve().parent
+FX = str(HERE / 'fixtures' / 'loopguard') + '/'
+def legit():
+ out={}
+ for f in sorted(glob.glob(FX+'legit/*')):
+ out[os.path.basename(f)]=open(f).read()
+ rng=random.Random(7)
+ out['json_records']=json.dumps([{"id":i,"name":f"user{i}","email":f"user{i}@example.com","active":i%3==0,"tags":["a","b","c"],"score":round(rng.random(),4)} for i in range(400)],indent=2)
+ out['json_compact']=json.dumps([{"id":i,"type":"point","x":rng.randint(0,99),"y":rng.randint(0,99)} for i in range(600)])
+ out['md_table']="| id | name | qty | price |\n|---|---|---|---|\n"+"\n".join(f"| {i} | item-{i} | {rng.randint(1,9)} | {rng.randint(10,99)}.{rng.randint(0,99):02d} |" for i in range(300))
+ out['csv']="id,name,value\n"+"\n".join(f"{i},row{i},{rng.randint(0,9999)}" for i in range(600))
+ out['css']="\n".join(f".c{i} {{ margin: {i%8}px {i%5}px; padding: 4px 8px; color: #{rng.randrange(1<<24):06x}; background: #{rng.randrange(1<<24):06x}; border-radius: 4px; }}" for i in range(150))
+ out['css_utility']="\n".join(f".m-{i} {{ margin: {i}px; }}\n.p-{i} {{ padding: {i}px; }}\n.w-{i} {{ width: {i}%; }}" for i in range(80))
+ out['html_list']="<ul>\n"+"\n".join(f' <li class="item"><a href="/page/{i}">Page {i}</a></li>' for i in range(300))+"\n</ul>"
+ out['html_table']="<table>\n"+"\n".join(f' <tr><td class="cell">{i}</td><td class="cell">name{i}</td><td class="cell">{rng.randint(0,99)}</td></tr>' for i in range(250))+"\n</table>"
+ out['js_array']="const verts = [\n"+",\n".join(f" [{rng.uniform(-1,1):.3f}, {rng.uniform(-1,1):.3f}, {rng.uniform(-1,1):.3f}]" for i in range(500))+"\n];"
+ out['js_calls']="\n".join(f"addBox({rng.randint(0,30)}, {rng.randint(0,30)}, {rng.randint(0,30)}, {rng.randint(1,5)}, {rng.randint(1,5)}, 0x{rng.randrange(1<<24):06x});" for i in range(300))
+ out['js_setters']="\n".join(f"el{i}.style.left = '{i*10}px'; el{i}.style.top = '{i*7}px'; el{i}.style.width = '40px'; el{i}.style.height = '40px';" for i in range(200))
+ out['py_asserts']="\n".join(f" assert parse('{i}') == {i}, 'parse failed for {i}'\n assert fmt({i}) == '{i}', 'fmt failed for {i}'" for i in range(150))
+ out['py_defs']="\n\n".join(f"def get_field_{i}(self):\n return self._data['field_{i}']\n\ndef set_field_{i}(self, value):\n self._data['field_{i}'] = value" for i in range(60))
+ out['svg_path']="".join(f'<circle cx="{rng.randint(0,500)}" cy="{rng.randint(0,500)}" r="{rng.randint(2,9)}" fill="#{rng.randrange(1<<24):06x}"/>\n' for i in range(300))
+ out['c_switch']="switch (op) {\n"+"\n".join(f" case OP_{i}: result = handle_{i}(a, b); break;" for i in range(200))+"\n}"
+ out['voxel_dense']="\n".join("function fill%s(cx,cz,r,y0,y1,color){for(let y=y0;y<=y1;y++)for(let x=cx-r;x<=cx+r;x++)for(let z=cz-r;z<=cz+r;z++){const dx=x-cx,dz=z-cz;if(dx*dx+dz*dz<=r*r+%d.4)setVoxel(x,y,z,%s);}}"%(n,k,c) for k,(n,c) in enumerate(zip("ABCDEFGHIJKLMNOPQRSTUVWXYZ",["color","pick(cols)"]*13)))
+ out['numbered_steps']="\n".join(f"{i}. Step {i}: take the value from register {i} and add it to the accumulator, then store the result." for i in range(1,61))
+ out['config_yaml']="\n".join(f" - name: svc-{i}\n image: registry/app:{i}\n replicas: 2\n port: {8000+i}" for i in range(100))
+ out['sql_inserts']="\n".join(f"INSERT INTO t (id, name, v) VALUES ({i}, 'name{i}', {rng.randint(0,999)});" for i in range(300))
+ out['hex_dump']="\n".join(f"{i*16:08x} "+" ".join(f"{rng.randrange(256):02x}" for _ in range(16)) for i in range(250))
+ # repetitive data that is valid: a zero grid, identical records, a hex dump of zeroed memory (the period rule used to cut them)
+ out['zero_grid']="GRID = [\n"+",\n".join(" ["+", ".join(["0"]*40)+"]" for _ in range(80))+"\n]\n"
+ out['zero_grid_json']="[\n"+",\n".join(" ["+",".join(["0"]*80)+"]" for _ in range(80))+"\n]\n"
+ out['json_lines_identical']="\n".join('{"status": "ok", "code": 200, "message": "request completed", "retry": false}' for _ in range(60))+"\n"
+ out['hex_dump_zero']="\n".join(f"{i*16:08x} "+" ".join(["00"]*16)+" |................|" for i in range(250))+"\n"
+ out['hex_dump_zero_plain']="\n".join(f"{i*16:08x}: "+"0000 "*8 for i in range(250))+"\n"
+ # repo sources as long legit code
+ for f in ['qwen/serve.py', 'glm/serve.py', 'qwen/test_guard.py']: # long valid code written by people
+ out['src_' + f.replace('/', '_')] = (HERE.parent / f).read_text()[:30000]
+ return out
+def synth_loops():
+ out={}
+ out['code_loop_exact']="function init(){\n setup();\n}\n"+" renderTile(x, y, z); tick++;\n"*400
+ out['code_loop_fn']="".join(f"function step(){{ update(); draw(); requestAnimationFrame(step); }}\n" for _ in range(200))
+ out['drift_counter']="\n".join(f"Then the scene adds another lantern at position {i} and keeps the same lighting and shadows." for i in range(300))
+ out['drift_words']="".join(f'The pagoda has a roof tier "{i}" with curved eaves and red pillars supporting the level above it. ' for i in range(150))
+ out['json_loop']='{"items":['+",".join('{"id":%d,"type":"lamp","color":"red","pos":[1,2,3]}'%(i%3) for i in range(300))+"]}"
+ out['sentence_loop']="I think the answer is yes. But wait, let me reconsider. "*120
+ out['para_loop']="\n\n".join(["The model should output the final answer now. Let me finalize the response and summarize the key points once more."]*60)
+ out['list_loop']="\n".join(f"- Consider option {1+i%4}: check the constraint and verify the result again." for i in range(300))
+ out['html_loop']='<div class="tower"><div class="tier"></div></div>\n'*300
+ out['counter_calls']="function build(){\n"+"\n".join(f" fillBox(cx-1,cx+1,{200+i},{200+i},cz-1,cz+1,[C.stone,C.stoneD,C.stoneL]);" for i in range(400))
+ out['char_loop']="ab"*1500
+ # the same data kinds as the legit zero grid / JSON records, but endless: they stop at the data backstop (loopguard.DATA_SUSTAIN)
+ out['zero_run_endless']="GRID = [\n"+"0, "*40000
+ out['json_lines_endless']="\n".join('{"status": "ok", "code": 200, "message": "request completed", "retry": false}' for _ in range(1500))+"\n"
+ return out
+
+
+
+def extend(t, n=16000):
+ """Continue a looping text: its last 500 characters come back again and again, a counter moving each time (no exact
+ period, the case the text rule exists for)."""
+ seg = t[-500:]
+ out = []
+ for i in range(n // len(seg) + 1):
+ out.append(re.sub(r"\b[a-z]+\b", lambda m, c=[0]: (c.__setitem__(0, c[0] + 1), f"{m.group(0)}{i}" if c[0] == 7 else m.group(0))[1], seg, count=8))
+ return t + "".join(out)
+
+
+def extend_shuffled(t, n=16000, seed=0):
+ """Continue a looping text by re-emitting the sentences / lines of its last 1200 characters in random order, a counter
+ moving now and then: the loop never repeats a stretch longer than a unit (the drift the text rule exists for)."""
+ rng = random.Random(seed)
+ units = [u for u in re.split(r"(?<=[.!?\n])\s*", t[-1200:]) if len(u) > 3] or [t[-1200:]]
+ out, tot, k = [], 0, 0
+ while tot < n:
+ u = rng.choice(units)
+ if rng.random() < 0.3:
+ u = re.sub(r"\d+", str(k), u, count=1)
+ out.append(u)
+ tot += len(u) + 1
+ k += 1
+ return t + " " + " ".join(out)
+
+
+def loops():
+ files = sorted(glob.glob(FX + "loops/*"))
+ real = {os.path.basename(f) + "+cont": extend(open(f).read()) for f in files}
+ real.update({os.path.basename(f) + "+shuf": extend_shuffled(open(f).read(), seed=i) for i, f in enumerate(files)})
+ real.update({os.path.basename(f): open(f).read() for f in files if os.path.basename(f).startswith('pagoda_')}) # as generated
+ return {**synth_loops(), **real}
diff --git a/tools/qwen/loopguard_gate.py b/tools/qwen/loopguard_gate.py
new file mode 100644
index 0000000..8c968d4
--- /dev/null
+++ b/tools/qwen/loopguard_gate.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python3
+"""Answer-phase loop guard gate: 0 false stops on the legit corpus, every loop of the loop corpus stopped.
+
+ loopguard_gate.py qwen=/path/tokenizer.json glm=/path/tokenizer.json [--chunks 1,3,4] [--old]
+
+Each text is replayed through loopguard.LoopMonitor("answer") with the real tokenizer of the model family, a few tokens per
+event (speculative decoding delivers several). --old replays with the release-gate rule alone (the pre-fix answer rule).
+CPU only. Exit code 1 when the gate fails."""
+from __future__ import annotations
+
+import argparse
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).parent))
+import loopguard_corpus
+import serve
+import loopguard
+
+
+def replay(tok, text: str, chunk: int):
+ enc = tok.encode(text)
+ ids, offs = enc.ids, enc.offsets
+ mon = loopguard.LoopMonitor("answer", None)
+ cur = 0 # byte-level BPE offsets overlap inside a multi-byte character: stream each character once
+ for i in range(0, len(ids), chunk):
+ j = min(i + chunk, len(ids))
+ end = max(cur, offs[j - 1][1])
+ hit = mon.feed(ids[i:j], text[cur:end])
+ cur = end
+ if hit:
+ return hit, len(ids)
+ return None, len(ids)
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("tokenizers", nargs="+", help="name=path/to/tokenizer.json")
+ ap.add_argument("--chunks", default="1,3,4")
+ ap.add_argument("--old", action="store_true")
+ args = ap.parse_args()
+ if args.old:
+ loopguard.answer_text_loop = loopguard.text_loop
+ from tokenizers import Tokenizer
+ legit, loops = loopguard_corpus.legit(), loopguard_corpus.loops()
+ failed = False
+ print(f"{'family':8s} {'chunk':>5s} {'loops stopped':>14s} {'legit false stops':>18s}")
+ for spec in args.tokenizers:
+ name, path = spec.split("=", 1)
+ tok = Tokenizer.from_file(path)
+ for chunk in (int(c) for c in args.chunks.split(",")):
+ miss = [n for n, t in loops.items() if replay(tok, t, chunk)[0] is None]
+ fp = [(n, h["kind"], h["at"]) for n, t in legit.items() if (h := replay(tok, t, chunk)[0])]
+ print(f"{name:8s} {chunk:5d} {len(loops) - len(miss):>8d}/{len(loops):<5d} {len(fp):>12d}/{len(legit)}")
+ for n in miss:
+ print(" not stopped:", n)
+ for f in fp:
+ print(" FALSE STOP:", f)
+ failed |= bool(miss or fp)
+ print("GATE", "FAIL" if failed else "PASS")
+ return int(failed)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/qwen/serve.py b/tools/qwen/serve.py
index 74050de..46d8530 100644
--- a/tools/qwen/serve.py
+++ b/tools/qwen/serve.py
@@ -445,112 +445,28 @@ class Heartbeat:
# ---------------------------------------------------------------------------- loop guard
-# Same family as the GLM guard (tools/glm/serve.py LoopGuard): an n-gram period detector, plus a text rule for loops
-# that drift (no exact period): the release-gate rule of tools/evalgate/loops.py (zlib ratio of the last 1000 chars
-# < 30 % AND a 50-char span seen >= 3 times in the last 3000 chars) that must hold for a sustained stretch. Greedy
-# thinking on a near-tie (the Qwen3.8 trait, ifeval-0015/0114/0195) is the target: the guard closes the think block.
-GUARD_MAX_N = 64
-GUARD_THINK = {"k": 4, "min_span": 48, "sustain": 320} # tokens; GLM thresholds for the period rule
-GUARD_ANSWER = {"k": 6, "min_span": 96, "sustain": 640} # stricter: an answer may repeat items legitimately
-GUARD_CHECK_EVERY = 16 # tokens between two evaluations of the text rule
-TEXT_WINDOW, TEXT_RATIO, TEXT_MIN_CHARS = 1000, 0.30, 200
-SPAN_TAIL, SPAN_LEN, SPAN_MIN = 3000, 50, 3
+# The detectors live in tools/loopguard.py (shared with the GLM server).
+from loopguard import (GUARD_ANSWER, loop_guard_default, GUARD_CHECK_EVERY, GUARD_MAX_N, GUARD_THINK, SPAN_LEN, SPAN_MIN, SPAN_TAIL, # noqa: E402,F401
+ TEXT_MIN_CHARS, TEXT_RATIO, TEXT_WINDOW, LoopMonitor, answer_text_loop, counter_drift,
+ max_span_repeat, repeated_units, shingle_repeat, text_loop)
+
THINK_CLOSE_TEXT = "\n</think>\n\n"
THINK_CLOSE_TAG = "</think>"
FINAL_TRIES = 2
-def loop_guard_default() -> bool:
- return os.environ.get("EXL3_LOOP_GUARD", "1") != "0"
-
-
-def text_loop(text: str) -> bool:
- """tools/evalgate/loops.is_loop (kept identical; test_serve checks both agree)."""
- import zlib
- from collections import Counter
- w = text[-TEXT_WINDOW:]
- if len(w) < TEXT_MIN_CHARS or len(zlib.compress(w.encode())) / max(len(w.encode()), 1) >= TEXT_RATIO:
- return False
- t = text[-SPAN_TAIL:]
- return max(Counter(t[i:i + SPAN_LEN] for i in range(len(t) - SPAN_LEN + 1)).values(), default=0) >= SPAN_MIN
-
-
-class LoopMonitor:
- """Watches the tokens of one generation. feed() returns None, or a dict
- {phase, kind ("period"|"text"|"budget"), cut (tokens of the current phase to keep), at, period}.
- Phases: "think" (until the </think> token) then "answer"; a request without a think block starts in "answer".
- With detect=False only the thinking budget is enforced."""
-
- def __init__(self, phase: str, close_id: int | None, budget: int | None = None, detect: bool = True):
- self.close_id, self.budget, self.detect = close_id, budget, detect
- self.start_phase(phase)
-
- def start_phase(self, phase: str) -> None:
- self.phase = phase
- self.cfg = GUARD_THINK if phase == "think" else GUARD_ANSWER
- self.ids: list[int] = []
- self.run = [0] * (GUARD_MAX_N + 1)
- self.text = ""
- self.last_check = 0
- self.flag_from: int | None = None
-
- def feed(self, tokens, text: str = "") -> dict[str, Any] | None:
- tokens = [int(t) for t in tokens]
- if self.phase == "think" and self.close_id is not None and self.close_id in tokens:
- k = tokens.index(self.close_id)
- hit = self._feed(tokens[:k], text)
- if hit:
- return hit
- self.start_phase("answer")
- return self._feed(tokens[k + 1:], "")
- return self._feed(tokens, text)
-
- def _feed(self, tokens, text: str) -> dict[str, Any] | None:
- ids, run, cfg = self.ids, self.run, self.cfg
- self.text += text
- for t in tokens:
- i = len(ids)
- ids.append(t)
- if self.phase == "think" and self.budget is not None and i + 1 >= self.budget:
- return {"phase": "think", "kind": "budget", "cut": self.budget, "at": i + 1, "period": 0}
- if not self.detect:
- continue
- for n in range(1, GUARD_MAX_N + 1):
- r = run[n] + 1 if i >= n and t == ids[i - n] else 0
- run[n] = r
- if r >= max(n * (cfg["k"] - 1), cfg["min_span"] - n):
- return {"phase": self.phase, "kind": "period", "cut": max(i - r + 1, 1), "at": i + 1, "period": n}
- if self.detect and len(ids) - self.last_check >= GUARD_CHECK_EVERY:
- prev, self.last_check = self.last_check, len(ids)
- if text_loop(self.text[-(SPAN_TAIL + 200):]):
- if self.flag_from is None:
- self.flag_from = prev
- if len(ids) - self.flag_from >= cfg["sustain"]:
- return {"phase": self.phase, "kind": "text", "cut": max(self.flag_from, 1), "at": len(ids), "period": 0}
- else:
- self.flag_from = None
- if len(self.text) > 4 * SPAN_TAIL:
- self.text = self.text[-SPAN_TAIL * 2:]
- return None
-
-
def gate_text(vis: str) -> str:
"""The text the release gate sees: reasoning + </think> + answer, each stripped (what Splitter returns to the client)."""
think, tag, ans = vis.partition(THINK_CLOSE_TAG)
return think.strip() + tag + ans.strip()
-def max_span_repeat(text: str) -> int:
- t = text[-SPAN_TAIL:]
- from collections import Counter
- return max(Counter(t[i:i + SPAN_LEN] for i in range(len(t) - SPAN_LEN + 1)).values(), default=0)
-
-def final_cut(vis: str) -> int:
+def final_cut(vis: str) -> int | None:
"""The gate rule holds on the visible text (thinking [+ </think> + answer]). Return the character index at which to cut
the thinking: the longest prefix (line starts first, then 64-character steps) that (a) holds no 50-character span twice
in its last 3000 characters, so that the answer, which repeats the last draft once more, cannot bring any span to the
- count of 3 whatever it says, and (b) with </think> and the answer already written does not trip the rule. 0 if none."""
+ count of 3 whatever it says, and (b) with </think> and the answer already written does not trip the rule. None if no cut does (the answer trips the rule on its own)."""
think, _, ans = vis.partition(THINK_CLOSE_TAG)
think = think.rstrip()
lines = sorted({m.end() for m in re.finditer("\n", think)}, reverse=True)
@@ -559,7 +475,7 @@ def final_cut(vis: str) -> int:
pre = think[:c].rstrip()
if max_span_repeat(pre) <= 1 and not text_loop(pre + THINK_CLOSE_TAG + ans.strip()):
return c
- return 0
+ return None
class Retract(int):
@@ -612,6 +528,15 @@ SERVE_ENV = (("EXL3_HOST_LEAN", "1"), ("EXL3_HOST_CUTS", "1"), # batched verif
# shared 9K / 11K / 12.1K / 14K prefix 1.04 -> 0.60, 2.25 -> 0.80, 2.92 -> 0.63, 1.62 -> 0.74 s; the writing prompt is
# bitwise unchanged, KLD vs a cold prefill at the level of any resumed turn. 0 = off.
("EXL3_BRANCH_CKPT", "1"),
+ # dense prompt-tail checkpoints: the recurrent state is also written at each of the 7 page boundaries below the last full
+ # page, so a prompt that shares the cached prefix up to anywhere in its last 2K tokens (same document, another question)
+ # resumes within one page of the divergence instead of at the previous 4096-row chunk start. 0 = off. A resume replays
+ # a different number of rows than a cold prefill and the GEMM path depends on the row count, so the output is not yet
+ # bit-identical to a cold prefill; the fix is in progress.
+ ("EXL3_TAIL_DENSE", "7"),
+ # sub-page prompt-tail checkpoints (EXL3_TAIL_SUB = number of 64-row steps below the prompt end): a prompt that diverges in
+ # its final tokens resumes within 64 rows of the divergence. Same numerics caveat as the dense checkpoints. 0 = off.
+ ("EXL3_TAIL_SUB", "0"),
# bit-identical prefill levers (hyper-connection apply folded into the next norm, MoE glue v2), served
# +2.4 % / +1.6 % / +1.8 % (fuse) and +0.9 / -0.1 / +0.3 % (glue) at 4K / 16K / 32K on bal. 0 = off.
("EXL3_PF_GR_FUSE", "1"), ("EXL3_MPW_GLUE", "1"),
@@ -643,6 +568,21 @@ SERVE_ENV = (("EXL3_HOST_LEAN", "1"), ("EXL3_HOST_CUTS", "1"), # batched verif
# 17/10: multi-block exact decode top-k (bitwise on 24+ cases, decode R<=1 T>=32768 only; saves 0.13/0.42/0.91 ms per token at 128K/256K/500K). 0 = one-block.
("EXL3_TOPK_PAR", "1"))
+# NVIDIA only (RTX 3090; the AMD values above stay as they are). The verify of 2..8 rows costs
+# 25-29 ms against 22 ms for one row, while a draft step costs ~1.5 ms, 0.93 ms of it the 248K-row K5 head: deeper drafts pay
+# (tier thresholds 0.3/0.1 up to 3 rows, 0.6/0.4 beyond instead of 0.6/0.3 and 0.95/0.85), and the 1-row draft steps read only the
+# first 98304 head rows (EXL3_DRAFT_VOCAB, self-disabling when the language needs ids above that, see qwen3_5_mtp.py). Verified
+# tokens do not change. No depth cap on the draft rule: the many-row qdec kernel (cu/qdec_rows.cu) serves the hd 256 verify attention
+# of 2..8 rows at 64K-246K (3090: mix decode at 241K tokens, capped rule -> uncapped, chat 73.3 -> 82.6, code 73.2 -> 80.7, prose 53.4 -> 52.9;
+# 144K: 84.0/92.2/57.7 -> 82.4/99.5/58.5); with EXL3_QDEC=0 or EXL3_QDEC_ROWS=0 the Triton verify is back and QWSPEC_DEPTHRULE=
+# "96000:0.45,0.2,4,0.8,0.6" (spec_policy.py) is the matching cap. EXL3_DRAFT_VOCAB=0 and QWSPEC_* set in the environment win.
+# SERVE_ENV entries tuned on gfx1151 for conversation resume and HIP kernels, not validated on NVIDIA (the 3090 numbers were
+# measured without them): CUDA starts without them, the environment still wins.
+HIP_ONLY_SERVE_ENV = frozenset(("EXL3_BRANCH_CKPT", "EXL3_GDN_HF", "EXL3_MOE_WMMA_MIN_ROWS", "EXL3_NC2_ABLIT_F16", "EXL3_NC2_ASYNC_STASH",
+ "EXL3_NC2_ATTN_F16", "EXL3_REPLY_FIRST", "EXL3_STATE_REBASE", "EXL3_TAIL_DENSE", "EXL3_TAIL_MAXGAP",
+ "EXL3_TAIL_REPLY", "EXL3_TAIL_SUB", "EXL3_TOPK_PAR"))
+CUDA_SERVE_ENV = (("EXL3_CUDA_GRAPH", "1"), ("EXL3_DRAFT_VOCAB", "98304"), ("QWSPEC_THF", "0.3"), ("QWSPEC_THV", "0.1"), ("QWSPEC_THFD", "0.6"), ("QWSPEC_THVD", "0.4"))
+
HC_GS_SIDECAR = "hc_gs_sidecar.safetensors"
# The sidecar of the published pack. A file with another hash (wrong pack, damaged download) is not used: plain group rounding, one log line.
HC_GS_SIDECAR_SHA256 = "473e7547adaad190788634556ce6b32614bdb280ccedadbed8789d39b59dcc8f"
@@ -744,15 +684,22 @@ class QwenEngine:
"""Target model + MTP drafter + (optional) vision tower + one Generator."""
def __init__(self, model_path: str, ctx: int, ndt: int = 7, draft_policy: str = "mix",
- vision: bool = True, max_chunk_size: int = 2048, cache_bits: int = 0, sessions: int = 1):
+ vision: bool = True, max_chunk_size: int = 2048, cache_bits: int = 0, sessions: int = 1,
+ k_bits: int = 0, v_bits: int = 0):
# The measured Qwen serving configuration. Read at import time by the engine:
# set before importing exllamav3. The caller's environment wins.
+ import torch
+ on_cuda = bool(torch.version.cuda and not torch.version.hip)
for k, v in SERVE_ENV:
+ if on_cuda and k in HIP_ONLY_SERVE_ENV:
+ continue
os.environ.setdefault(k, v)
check_latched_env()
print("qserve:", configure_hc_sidecar(model_path), flush=True)
print("qserve:", configure_draft2s(model_path), flush=True)
- import torch
+ if on_cuda:
+ for k, v in CUDA_SERVE_ENV:
+ os.environ.setdefault(k, v)
from exllamav3 import Cache, Config, Generator, Job, Model, Tokenizer
torch.set_grad_enabled(False)
self.torch, self.Generator, self.Job = torch, Generator, Job
@@ -771,15 +718,23 @@ class QwenEngine:
self.eos = list(self.config.eos_token_id_list)
self.model = Model.from_config(self.config)
# cache_bits 0 (default) = the fp16 K/V pages; 8 (--cache-bits 8) = packed int8 K/V pages (2.6 GiB less at 256K), indexer
- # planes stay fp16. The int8 pages are not row-invariant when several rows decode together, so they are opt-in.
+ # planes stay fp16. Parallel sessions give equal output only with EXL3_ROW_INV_GROUPS=1 (see main()); the int8 pages stay opt-in.
+ # k_bits / v_bits (--k-bits / --v-bits, 2..8) set the two sides separately and win over cache_bits; 0 = take cache_bits
+ k_bits, v_bits = k_bits or cache_bits, v_bits or cache_bits
+ if not (k_bits or v_bits) and torch.version.cuda and not torch.version.hip:
+ k_bits = v_bits = 4 # NVIDIA preset: K4V4 pages (256K fits 24 GB, decode read 4x less); --cache-bits / --k-bits override
self.cache_bits = cache_bits
from exllamav3 import CacheLayer_quant
- qkw = dict(layer_type=CacheLayer_quant, k_bits=cache_bits, v_bits=cache_bits) if cache_bits else {}
+ qkw = dict(layer_type=CacheLayer_quant, k_bits=k_bits, v_bits=v_bits) if (k_bits and v_bits) else {}
+ assert bool(k_bits) == bool(v_bits), "set both --k-bits and --v-bits (or --cache-bits)"
# one recurrent (GDN) slot per session; the Generator caps its batch at the slot count
self.cache = Cache(self.model, max_num_tokens=ctx, max_history=max(3, ndt), max_batch_size=sessions, **qkw)
if os.environ.get("EXL3_WARM_DENSE", "1") != "0":
from exllamav3.model.dense_warmup import seed_dense_tune
seed_dense_tune()
+ from exllamav3.util import jit_log, kernel_seed
+ kernel_seed.install() # shipped Triton kernels for this Triton version: nothing to compile on a first start
+ jit_log.install() # EXL3_LOG_JIT=1: one line per Triton compile
startup_health.stage("target weights")
with Heartbeat("loading target model"):
self.model.load(max_chunk_size=max_chunk_size, progressbar=False, callback=startup_health.load_callback())
@@ -1159,12 +1114,14 @@ class QwenEngine:
"""Yield decoded text pieces. Final stats land in `stats`. Every job enqueued is appended to `_mine`.
Final check (on with the guard, loop_final=False turns it off): when the turn ends normally and the visible text
- (thinking + answer) trips the release-gate loop rule, the thinking is cut back (final_cut), the close is forced and
+ (thinking + answer) trips the release-gate loop rule and some cut of the thinking cures it (a long valid code answer
+ trips the rule on its own: no cut helps, nothing is redone), the thinking is cut back (final_cut), the close is forced and
the answer is generated again, at most FINAL_TRIES times. Discarded tokens do not count against max_tokens.
Loop guard (default on, EXL3_LOOP_GUARD=0 or loop_guard=False turns it off): when the think block loops (or
thinking_budget tokens are used) the job is cancelled and restarted from prompt + the thinking kept so far +
- "\n</think>\n\n", so the answer proceeds. A loop inside the answer ends the turn (finish_reason stop).
+ "\n</think>\n\n", so the answer proceeds. A loop inside the answer ends the turn: finish_reason "length" and choices[0].stop_reason "loop_guard"
+ (plus timings.loop_guard with the detail), so a client can tell a guard stop from a natural end.
Nothing is changed while no loop is detected.
logprobs (None = off, k = 0..20): per generated token the log-probability of the token and of the k most likely tokens,
@@ -1254,7 +1211,8 @@ class QwenEngine:
break
if ev.get("eos") and final_on and final_tries < FINAL_TRIES and text_loop(gate_text(vis)) \
and (THINK_CLOSE_TAG in vis or ev.get("eos_reason") == "max_new_tokens"
- or generated - discount >= max_tokens):
+ or generated - discount >= max_tokens) \
+ and (final_c := final_cut(vis)) is not None: # no cut of the thinking cures it: the answer is the loop, or valid
redo = True
break
if ev.get("eos"):
@@ -1278,7 +1236,7 @@ class QwenEngine:
break
if redo:
self._routes.pop(job.serial_number, None) # it sent its eos
- cut_chars = final_cut(vis)
+ cut_chars = final_c
final_tries += 1
keep_tokens, keep_chars = max(m for m in gmarks if m[1] <= cut_chars)
fired = {"phase": "think", "kind": "final", "cut": keep_tokens, "at": len(token_ids), "period": 0,
@@ -1683,8 +1641,8 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
pre, gen = stats.get("time_prefill") or 0.0, stats.get("time_generate") or 0.0
if has_calls:
reason = "tool_calls"
- elif stats.get("eos_reason") in ("max_new_tokens",):
- reason = "length"
+ elif stats.get("eos_reason") in ("max_new_tokens", "loop_guard"):
+ reason = "length" # a guard stop cut the answer short: clients must not read it as a natural end
else:
reason = "stop"
usage = {"prompt_tokens": prompt_tokens, "completion_tokens": n_new,
@@ -1769,6 +1727,8 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
await writer.write(sse(event({"tool_calls": [dict(c, index=i)]})))
reason, usage, timings = finish_and_stats(stats, full, bool(calls))
final = event({}, reason) | {"usage": usage, "timings": timings}
+ if stats.get("eos_reason") == "loop_guard":
+ final["choices"][0]["stop_reason"] = "loop_guard"
if job["return_token_ids"]:
final["token_ids"] = stats.get("token_ids", [])
await writer.write(sse(final))
@@ -1816,6 +1776,8 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
payload = {"id": request_id, "object": "chat.completion", "created": created, "model": model_id,
"choices": [{"index": 0, "message": message, "finish_reason": reason}],
"usage": usage, "timings": timings}
+ if stats.get("eos_reason") == "loop_guard":
+ payload["choices"][0]["stop_reason"] = "loop_guard"
if job["return_token_ids"]:
payload["token_ids"] = stats.get("token_ids", [])
if job["logprobs"] is not None:
@@ -1998,7 +1960,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
def reason_usage(stats: dict[str, Any], text: str):
n_new = int(stats.get("new_tokens") or engine.count_tokens(text))
n_prompt = prompt_tokens if prompt_ids is not None else int(stats.get("prompt_tokens") or prompt_tokens)
- reason = "length" if stats.get("eos_reason") == "max_new_tokens" else "stop"
+ reason = "length" if stats.get("eos_reason") in ("max_new_tokens", "loop_guard") else "stop"
return reason, serve_compat.usage(n_prompt, n_new, int(stats.get("cached_tokens") or 0))
out: asyncio.Queue = asyncio.Queue()
@@ -2055,7 +2017,10 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
lifecycle.first_content(job["_reqid"], queued_at)
await writer.write(sse(chunk(item, None)))
reason, usage = reason_usage(stats, full)
- await writer.write(sse(chunk("", reason) | {"usage": usage}))
+ last = chunk("", reason) | {"usage": usage}
+ if stats.get("eos_reason") == "loop_guard":
+ last["choices"][0]["stop_reason"] = "loop_guard"
+ await writer.write(sse(last))
await writer.write(b"data: [DONE]\n\n")
await response.write_eof()
lifecycle.stream_done(job["_reqid"], int(stats.get("new_tokens") or 0))
@@ -2093,6 +2058,8 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
text, _ = stop_text(full, job["stop"])
reason, usage = reason_usage(stats, text)
out_ = chunk(text, reason) | {"object": "text_completion", "usage": usage}
+ if stats.get("eos_reason") == "loop_guard":
+ out_["choices"][0]["stop_reason"] = "loop_guard"
if job["logprobs"] is not None:
out_["choices"][0]["logprobs"] = format_logprobs(
stats.get("logprobs", []), stats.get("logprob_token_ids", stats.get("token_ids", [])), engine.token_str, chat=False)
@@ -2154,7 +2121,8 @@ def load_all(args: argparse.Namespace):
print(f"qserve: starting, model={model_dir} ctx={args.ctx} sessions={args.sessions} draft_policy={args.draft_policy} "
f"defaults={ {k: v for k, v in defaults.items() if v is not None} }", flush=True)
engine = QwenEngine(model_dir, args.ctx, ndt=args.ndt, draft_policy=args.draft_policy, vision=not args.no_vision,
- cache_bits=args.cache_bits, sessions=args.sessions)
+ cache_bits=args.cache_bits, sessions=args.sessions,
+ k_bits=args.k_bits, v_bits=args.v_bits)
env = {k: v for k, v in sorted(os.environ.items()) if k.startswith(("EXL3_", "MPW"))}
print(f"qserve: effective env {env}", flush=True)
from exllamav3.generator.slot_store import SlotStore
@@ -2184,7 +2152,9 @@ def main() -> None:
parser.add_argument("--model-id", default=DEFAULT_MODEL_ID, help="id shown by /v1/models and expected in requests")
parser.add_argument("--ctx", "-c", type=int, default=65536, help="KV cache size in tokens (default 65536)")
parser.add_argument("--cache-bits", type=int, default=0, choices=(0, 8),
- help="bits per K/V element of the attention cache pages (0 = fp16, the default; 8 = packed int8, about 40 %% smaller pages, saves 2.6 GiB at 256K, output not row-invariant for several rows)")
+ help="bits per K/V element of the attention cache pages (0 = fp16, the default; 8 = packed int8, about 40 %% smaller pages, saves 2.6 GiB at 256K, greedy output differs from the 16-bit cache; with EXL3_ROW_INV_GROUPS=1 four parallel sessions matched solo runs, 16 of 16)")
+ parser.add_argument("--k-bits", type=int, default=0, choices=(0, 2, 3, 4, 5, 6, 7, 8), help="K bits of the quantized attention cache (with --v-bits; overrides --cache-bits)")
+ parser.add_argument("--v-bits", type=int, default=0, choices=(0, 2, 3, 4, 5, 6, 7, 8), help="V bits of the quantized attention cache")
parser.add_argument("--ndt", type=int, default=7, help="max draft tokens per round (default 7; the rule drafts up to 3 for most rounds, deeper only on confident chains)")
parser.add_argument("--draft-policy", choices=("mix", "mtp", "off"), default="mix",
help="mix = shipped rule (MTP + n-gram lookup, lossless), mtp = fixed MTP chain, off = plain decode")
@@ -2209,16 +2179,25 @@ def main() -> None:
args = parser.parse_args()
if args.sessions < 1:
parser.error("--sessions must be at least 1")
- # measured with --ndt 3: greedy output equal to a solo run on two short prompts at 2 sessions with --cache-bits 0; not at
- # 4 sessions, and not at 2 sessions with the 8-bit cache. Equality at N > 1 is not guaranteed for either cache width:
- # the split layout of the decode attention kernel depends on the batch
- if args.draft_policy != "off" and args.sessions * (args.ndt + 1) > 8:
- print(f"qserve: WARNING --sessions {args.sessions} x (--ndt {args.ndt} + 1) = {args.sessions * (args.ndt + 1)} verify rows "
- "is past 8: greedy output may differ from the same request run alone", flush=True)
- if args.sessions > 1:
+ # Measured with --ndt 3: greedy output equal to a solo run on two short prompts at 2 sessions with --cache-bits 0; not at
+ # 4 sessions, and not at 2 sessions with the 8-bit cache. Equality at N > 1 is not guaranteed by default: the split layout of
+ # the decode attention kernel depends on the batch. EXL3_ROW_INV_GROUPS=1 (opt-in, generator/row_groups.py) packs the decode
+ # step into forwards of at most 8 token rows with one attention call per sequence: four cold 8K prompts, --ndt 7, --sessions 4
+ # gave 16 of 16 answers equal to the solo run (16-bit and 8-bit cache), at about 3 % more wall time on that load and 8 to 10 %
+ # less aggregate decode throughput on short prompts
+ exact = all(os.environ.get(k, d) not in ("", "0") for k, d in (("EXL3_ROW_INV_GROUPS", "0"), ("EXL3_ROW_INV", "1")))
+ if args.sessions > 1 and not exact:
+ if args.draft_policy != "off" and args.sessions * (args.ndt + 1) > 8:
+ print(f"qserve: WARNING --sessions {args.sessions} x (--ndt {args.ndt} + 1) = {args.sessions * (args.ndt + 1)} verify rows "
+ "is past 8: greedy output may differ from the same request run alone", flush=True)
print(f"qserve: WARNING --sessions {args.sessions}: greedy output is not guaranteed equal to the same request run alone, "
- "with either cache width (the 16-bit cache stayed equal on two short prompts; the attention kernel splits its "
- "work by batch)", flush=True)
+ "with either cache width (the attention kernel splits its work by batch; EXL3_ROW_INV_GROUPS=1 makes it exact, a "
+ "little slower)", flush=True)
+ if os.environ.get("EXL3_SCHED_CHUNK_IL", "0") == "1":
+ # chunked-prefill interleave (exllamav3/generator/chunk_il.py): needs another request running beside the big prefill
+ print("qserve: chunk_il ON " + ("" if args.sessions > 1 else "(no effect: needs --sessions >= 2) ") +
+ f"max_defer={os.environ.get('EXL3_CIL_MAX_DEFER_S', '8')}s frac={os.environ.get('EXL3_CIL_DEFER_FRAC', '0.18')} "
+ f"slice={os.environ.get('EXL3_CIL_SLICE_S', '0.6')}s short_tok={os.environ.get('EXL3_CIL_SHORT_TOK', '4096')}", flush=True)
if args.no_uncensor:
os.environ["EXL3_ABLIT_RUNTIME"] = "off"
diff --git a/tools/qwen/serve_bench_ctx.py b/tools/qwen/serve_bench_ctx.py
new file mode 100644
index 0000000..f0ef5b7
--- /dev/null
+++ b/tools/qwen/serve_bench_ctx.py
@@ -0,0 +1,28 @@
+"""usage: serve_bench.py PORT MODEL_ID LOGFILE DEPTH[,DEPTH...] [--vision]. Real text prompts of ~DEPTH tokens (unique offset per depth, no prefix-cache reuse)."""
+import sys, json, time, base64, io, urllib.request, os, re
+port, mid, logf, depths = sys.argv[1:5]
+D = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "exllamav3", "conversion", "standard_cal_data")
+def post(body, t=3600):
+ r = urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions", json.dumps({"model": mid, **body}).encode(), {"Content-Type": "application/json"})
+ return json.load(urllib.request.urlopen(r, timeout=t))
+def last_req():
+ for l in reversed(open(logf).read().splitlines()):
+ if "qserve: request" in l: return l.split("qserve: ")[1]
+ return ""
+txt = "".join(open(f"{D}/{f}", encoding="utf8").read() for f in ("wiki.utf8", "c4.utf8", "technical.utf8", "code.utf8"))
+for i, d in enumerate(int(x) for x in depths.split(",")):
+ chars = int(d * 4.2); off = 12345 * (i + 1) + d
+ prompt = (txt * 3)[off:off + chars]
+ t0 = time.time()
+ r = post({"messages": [{"role": "user", "content": prompt + "\n\nWrite a long, detailed continuation of the story about a lighthouse keeper (at least 300 words)."}],
+ "max_tokens": 256, "temperature": 0, "enable_thinking": False})
+ out = r["choices"][0]["message"]["content"]; u = r["usage"]
+ words = out.split(); loop = len(words) > 40 and len(set(zip(words, words[1:], words[2:]))) < 0.5 * (len(words) - 2)
+ print(f"RESULT depth~{d} prompt={u['prompt_tokens']} new={u['completion_tokens']} wall={time.time()-t0:.1f}s loop={loop} | {last_req()}", flush=True)
+if "--vision" in sys.argv:
+ from PIL import Image, ImageDraw
+ im = Image.new("RGB", (448, 448), (255, 255, 255)); d = ImageDraw.Draw(im)
+ d.ellipse((60, 60, 220, 220), fill=(220, 30, 30)); d.rectangle((250, 240, 400, 380), fill=(30, 60, 220)); d.text((120, 400), "HELLO 42", fill=(0, 0, 0))
+ b = io.BytesIO(); im.save(b, "PNG"); url = "data:image/png;base64," + base64.b64encode(b.getvalue()).decode()
+ r = post({"messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": url}}, {"type": "text", "text": "Describe the shapes, their colors and any text in this image."}]}], "max_tokens": 200, "temperature": 0, "enable_thinking": False})
+ print("VISION:", r["choices"][0]["message"]["content"][:300].replace("\n", " "), "|", last_req(), flush=True)
diff --git a/tools/qwen/spec_policy.py b/tools/qwen/spec_policy.py
index fdbfad7..0df15a6 100644
--- a/tools/qwen/spec_policy.py
+++ b/tools/qwen/spec_policy.py
@@ -355,6 +355,12 @@ def ngram_from_env(default=(2, 7, 16, 3)):
if not (3 <= len(f) <= 4 and 1 <= g <= LMAX and k >= 1 and m >= g and min(f) >= 0): raise ValueError(f"QWSPEC_NGRAM={v}")
return tuple(f)
+def _unparked(g):
+ """Active jobs minus those EXL3_SCHED_CHUNK_IL skips this step (Generator._cil_parked): a short job decoding next to a parked
+ big prefill still counts as alone, so its lookup/draft policy is the solo one."""
+ return [j for j in g.active_jobs if not getattr(j, "_cil_skip", False)]
+
+
def install_lookup(g, ngram, stats=None):
"""The n-gram lookup alone, for a Generator whose drafter keeps its own fixed depth (GLM): no depth rule, no read of the
draft probabilities. ngram = (nmin, K, lmin[, cmin]) as in install(). When the context suffix (>= lmin tokens) occurred
@@ -392,8 +398,9 @@ def install_lookup(g, ngram, stats=None):
return False
def wrapped(results):
cont = None; sid = None
- if len(g.active_jobs) == 1 and g.active_jobs[0].is_prefill_done() and len(g.active_jobs[0].sequences) == 1:
- sid = g.active_jobs[0].sequences[0].sequence_ids
+ act = _unparked(g)
+ if len(act) == 1 and act[0].is_prefill_done() and len(act[0].sequences) == 1:
+ sid = act[0].sequences[0].sequence_ids
idx = fol.sync(sid)
L, c = idx.match(K)
if L >= lmin and c:
@@ -468,7 +475,7 @@ def install_plain_lookup(g, pl, stats=None):
c = c[:w]
return c
def rnd(results):
- job = g.active_jobs[0] if len(g.active_jobs) == 1 else None
+ job = _unparked(g)[0] if len(_unparked(g)) == 1 else None
if job is None or not job.is_prefill_done() or len(job.sequences) != 1: return None
c = draft(fol, job.sequences[0].sequence_ids, K)
if not c: return None
@@ -582,21 +589,34 @@ def install(g, dm, model, thf=0.6, thv=0.3, maxd=3, ngram=None, stats=None, rule
st["stop"] = True; st["keep"] = st["i"]
return ids
win = log_depth if log is not None else (fixed if fixed is not None else maxd)
+ # QWSPEC_DEPTHRULE="N:thf,thv,maxd,thfd,thvd": above N context tokens the tier rule switches to these values. Measured on the
+ # RTX 3090: the full-attention verify kernel for hd 256 (qdec) serves 1-2 rows only and Triton runs 3..5
+ # rows at +6 ms (128K), and 6..8 rows cost another +6 ms at 64K and +12 ms at 128K, so the deep drafts that pay at 4K-32K stop
+ # paying; a shallower, stricter rule from ~48K keeps the gain on repetitive text and never loses to the former rule on prose.
+ # Unset = one rule at every depth. QWSPEC_CAP_NG=1 also caps the n-gram copy length at the deep maxd.
+ cap_n = None
+ _c = os.environ.get("QWSPEC_DEPTHRULE", "").strip()
+ if _c and fixed is None and log is None and isinstance(rule, TierRule):
+ _n, _v = _c.split(":"); f = _v.split(",")
+ cap_n, deep = int(_n), (float(f[0]), float(f[1]), int(f[2]), float(f[3]), float(f[4]))
+ base = (rule.thf, rule.thv, rule.maxd, rule.thfd, rule.thvd); cap_ng = os.environ.get("QWSPEC_CAP_NG", "0") != "0"
def wrapped(results):
st.update(i=0, stop=False, keep=None, mode="mtp", ps=[])
job = next((j for j in g.active_jobs if j.is_prefill_done()), None)
cont = None
n = None
- if job is not None and len(g.active_jobs) == 1:
+ if job is not None and len(_unparked(g)) == 1:
seq = job.sequences[0]; n = len(seq.sequence_ids)
if st["job"] is job and st["n"] is not None and n > st["n"]:
rule.end_round(st["drafted"], max(0, min(st["drafted"], n - st["n"] - 1)))
elif st["job"] is not job and hasattr(rule, "new_request"):
rule.new_request()
st["job"] = job; st["n"] = n; st["drafted"] = 0
+ if cap_n is not None and n is not None:
+ rule.thf, rule.thv, rule.maxd, rule.thfd, rule.thvd = deep if n > cap_n else base
rule.begin() # after end_round above: the online rule reads last round's prediction there
- if ngram is not None and job is not None and len(g.active_jobs) == 1:
- K = min(ngram[1], maxd)
+ if ngram is not None and job is not None and len(_unparked(g)) == 1:
+ K = min(ngram[1], rule.maxd if cap_n is not None and cap_ng else maxd)
if os.environ.get("QWSPEC_NGRAM_IDX", "1") == "0":
L, c = ngram_match(seq.sequence_ids.torch_slice(0, n).flatten().tolist(), ngram[0], K)
else:
diff --git a/tools/qwen/test_chunk_il.py b/tools/qwen/test_chunk_il.py
new file mode 100644
index 0000000..f6e85bf
--- /dev/null
+++ b/tools/qwen/test_chunk_il.py
@@ -0,0 +1,355 @@
+#!/usr/bin/env python3
+"""EXL3_SCHED_CHUNK_IL: chunked-prefill interleave. Pure python (no torch, no GPU): the real planner (exllamav3/generator/chunk_il.py)
+and the real Generator glue (_cil_views/_cil_parked/_cil_hold/_cil_release, loaded by ast) drive a fake engine on a virtual clock.
+Proves: interleave order, hard max deferral (fixed seconds and proportional to the big prefill), big TTFT <= solo + 5 % at a small
+budget, per-job chunk ranges identical to the non-interleaved run, one batch-1 decode per step, equal bigs served in arrival order,
+single-user path untouched. Slot-limited serving model (serve()): the default budget costs the big request less than a fixed 8 s
+cap and gives the shorts the same first-token times."""
+from __future__ import annotations
+
+import ast
+import importlib.util
+import logging
+import os
+import sys
+import textwrap
+import types
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+spec = importlib.util.spec_from_file_location("chunk_il", ROOT / "exllamav3" / "generator" / "chunk_il.py")
+chunk_il = importlib.util.module_from_spec(spec)
+sys.modules["chunk_il"] = chunk_il
+spec.loader.exec_module(chunk_il)
+
+PAGE, CHUNK, MERGE = 256, 4096, 1024
+ROW_S, DEC_S, DEC_B = 35.8 / 45000, 0.03, 0.004 # 45K prefill = 35.8 s (FIFO reference), batch-1 decode step 30 ms, +4 ms per extra row
+
+
+def load_glue():
+ src = (ROOT / "exllamav3" / "generator" / "generator.py").read_text()
+ names = ("_cil_views", "_cil_parked", "_cil_hold", "_cil_release")
+ ns = {"os": os, "logging": logging, "chunk_il": chunk_il, "PAGE_SIZE": PAGE}
+ for n in ast.walk(ast.parse(src)):
+ if isinstance(n, ast.FunctionDef) and n.name in names:
+ exec(textwrap.dedent(ast.get_source_segment(src, n)), ns)
+ return {k: ns[k] for k in names}
+
+
+class Clock:
+ t = 0.0
+ def __call__(self):
+ return self.t
+
+
+class FakeJob:
+ def __init__(self, sim, name, n, out=0, serial=0, resume=0):
+ self.sim, self.name, self.n, self.out, self.serial_number = sim, name, n, out, serial
+ self.resume, self.time_first_prefill, self.time_first_token = resume, None, None # resume: tail-checkpoint position the first step jumps to
+ self.sequences = [types.SimpleNamespace(sequence_ids=range(n), kv_position=0)]
+ self.cached_pages, self._cil_hold = 0, False
+ self.ranges, self.tokens, self.t_prefill_done, self.t_arrive = [], 0, None, sim.clk.t
+
+ def is_prefill_done(self):
+ return (not self._cil_hold) and self.sequences[0].kv_position == self.n - 1
+
+ def _tail_peek(self, seq):
+ return self.resume if self.time_first_prefill is None else 0
+
+ def prefill(self):
+ seq = self.sequences[0]
+ if self.time_first_prefill is None: # Job._tail_restore: jump over the cached conversation
+ self.time_first_prefill = self.sim.clk.t
+ seq.kv_position = max(seq.kv_position, self.resume)
+ if seq.kv_position == self.n - 1:
+ self.t_prefill_done = self.sim.clk.t; return
+ rem = self.n - 1 - seq.kv_position
+ end = self.n - 1 if rem <= CHUNK + MERGE else (seq.kv_position + CHUNK) // PAGE * PAGE # Job.prefill's chunk rule (shape)
+ self.ranges.append((seq.kv_position, end))
+ self.sim.clk.t += (end - seq.kv_position) * ROW_S
+ seq.kv_position = end
+ if end == self.n - 1:
+ self.t_prefill_done = self.sim.clk.t
+
+
+class Sim:
+ """Generator.iterate() reduced to its scheduling skeleton, same call order as _iterate_inner."""
+ def __init__(self, flag, **planner_kw):
+ self.clk = Clock()
+ self.flag = flag
+ g = types.SimpleNamespace(active_jobs=[], max_chunk_size=CHUNK)
+ for k, f in load_glue().items():
+ setattr(g, k, types.MethodType(f, g))
+ g._cil = chunk_il.ChunkPlanner(clock=self.clk, **planner_kw) if flag else None
+ self.g, self.serial, self.all, self.log = g, 0, [], [] # log: (t_start, t_end, prefilled names, decoders)
+ os.environ["EXL3_SCHED_CHUNK_IL"] = "1" if flag else "0"
+
+ def add(self, name, n, out=0, resume=0):
+ j = FakeJob(self, name, n, out, self.serial, resume)
+ self.serial += 1
+ self.g.active_jobs.append(j); self.all.append(j)
+ return j
+
+ def step(self):
+ g, t0 = self.g, self.clk.t
+ parked = g._cil_parked() if chunk_il.chunk_il_enabled() else []
+ pre = []
+ for j in list(g.active_jobs):
+ if j not in parked and not j.is_prefill_done():
+ j.prefill(); pre.append(j.name)
+ g._cil_hold()
+ dec = [j for j in g.active_jobs if j.is_prefill_done() and j.t_prefill_done is not None]
+ if dec:
+ self.clk.t += DEC_S + DEC_B * (len(dec) - 1)
+ for j in dec:
+ j.tokens += 1
+ if j.time_first_token is None:
+ j.time_first_token = self.clk.t
+ g._cil_release()
+ for j in dec:
+ if j.tokens >= j.out:
+ g.active_jobs.remove(j)
+ self.log.append((t0, self.clk.t, pre, [j.name for j in dec]))
+
+ def run(self, until, arrivals=(), refill=None):
+ """arrivals: [(t, name, n, out)]; refill(sim): called after every step (closed loop of shorts)."""
+ pend = sorted(arrivals)
+ while self.g.active_jobs or pend:
+ while pend and pend[0][0] <= self.clk.t:
+ _, nm, n, out = pend.pop(0); self.add(nm, n, out)
+ if not self.g.active_jobs:
+ self.clk.t = pend[0][0]; continue
+ self.step()
+ if refill:
+ refill(self)
+ if self.clk.t > until:
+ break
+
+
+def serve(flag, shorts_t, bigs=((8.0, 45000),), cap=3, short_rows=900, out=40, **planner_kw):
+ """Slot-limited serving: at most `cap` jobs run, the rest wait in arrival order (the --sessions permits); a short of `short_rows`
+ rows and `out` tokens arrives at each time of shorts_t, bigs = [(t, rows)]. Returns the sim; job.t_arrive = arrival time."""
+ s = Sim(flag, **planner_kw)
+ arr = sorted([(t, f"s{k}", short_rows, out) for k, t in enumerate(shorts_t)] + [(t, f"A{i}", n, 1) for i, (t, n) in enumerate(bigs)])
+ queue = []
+ while arr or queue or s.g.active_jobs:
+ while arr and arr[0][0] <= s.clk.t:
+ queue.append(arr.pop(0))
+ while queue and len(s.g.active_jobs) < cap:
+ ta, nm, n, o = queue.pop(0)
+ s.add(nm, n, o).t_arrive = ta
+ if not s.g.active_jobs:
+ s.clk.t = arr[0][0]; continue
+ s.step()
+ return s
+
+
+def first_tokens(s, prefix):
+ return sorted(j.time_first_token - j.t_arrive for j in s.all if j.name.startswith(prefix))
+
+
+def solo_big_ttft(n=45000):
+ s = Sim(False); a = s.add("A", n, 1); s.run(1e9)
+ return a.t_prefill_done
+
+
+class InterleaveTests(unittest.TestCase):
+ def tearDown(self):
+ os.environ.pop("EXL3_SCHED_CHUNK_IL", None)
+
+ def stream(self, flag, n_users=2, **kw):
+ s = Sim(flag, **kw)
+ cnt = [0]
+
+ def new_short(sim):
+ for u in range(n_users):
+ if not any(j.name.startswith(f"s{u}_") for j in sim.g.active_jobs):
+ cnt[0] += 1; sim.add(f"s{u}_{cnt[0]}", 900, 40)
+ for u in range(n_users):
+ s.add(f"s{u}_0", 900, 40)
+ a_added = []
+ def refill(sim):
+ if not a_added and sim.clk.t >= 8.0:
+ a_added.append(sim.add("A", 45000, 1))
+ if a_added and a_added[0].t_prefill_done is not None and sim.clk.t > a_added[0].t_prefill_done + 30:
+ sim.g.active_jobs.clear(); return
+ new_short(sim)
+ s.run(400, refill=refill)
+ return s, a_added[0]
+
+ def test_order_shorts_between_chunks_and_exclusive_big_chunk(self):
+ s, a = self.stream(True)
+ a_steps = [i for i, (_, _, pre, _) in enumerate(s.log) if "A" in pre]
+ self.assertGreaterEqual(len(a_steps), 11)
+ first = a_steps[0]
+ for i in a_steps: # a leader chunk never shares its step with other work
+ _, _, pre, dec = s.log[i]
+ self.assertEqual(pre, ["A"], s.log[i]); self.assertEqual([d for d in dec if d != "A"], [], s.log[i])
+ served_between = [i for i in range(first, a_steps[-1]) if i not in a_steps and (s.log[i][2] or s.log[i][3])]
+ self.assertTrue(served_between, "no short step between A chunks")
+ # at least one short step sits between two A chunks (interleave), and one before the first chunk (shorts first)
+ self.assertTrue(any(a_steps[k] + 1 < a_steps[k + 1] for k in range(len(a_steps) - 1)))
+ self.assertTrue(all(s.log[i][2] != ["A"] for i in range(0, 1)) or first > 0)
+ self.assertGreaterEqual(s.g._cil.finished[0]["slices"], 2)
+
+ def test_max_deferral_bound_and_ttft_within_5pct(self):
+ solo = solo_big_ttft()
+ self.assertAlmostEqual(solo, 35.8, delta=0.05)
+ s, a = self.stream(True, n_users=3, max_defer_s=1.5)
+ ttft = a.t_prefill_done - a.t_arrive
+ deferral = sum(t1 - t0 for t0, t1, pre, _ in s.log if t0 >= a.t_arrive and t1 <= a.t_prefill_done and "A" not in pre)
+ self.assertLessEqual(deferral, 1.5 + 0.2, deferral) # hard cap + estimate error of one step
+ self.assertLessEqual(ttft, solo * 1.05, (ttft, solo))
+ st = s.g._cil.finished
+ self.assertTrue(st and st[0]["deferred_s"] <= 1.5 + 0.2)
+
+ def test_no_unbounded_starvation_with_endless_shorts_and_tiny_budget(self):
+ for budget in (0.0, 0.3):
+ s, a = self.stream(True, n_users=4, max_defer_s=budget)
+ self.assertIsNotNone(a.t_prefill_done)
+ self.assertLessEqual(a.t_prefill_done - a.t_arrive, 35.8 * 1.0 + budget + 0.25)
+
+ def test_budget_zero_is_fifo(self):
+ s, a = self.stream(True, n_users=2, max_defer_s=0.0)
+ self.assertAlmostEqual(a.t_prefill_done - a.t_arrive, solo_big_ttft(), delta=0.01)
+
+ def test_chunk_ranges_equal_non_interleaved_and_reconstruct_tokens(self):
+ ref, aref = self.stream(False, n_users=2)
+ il, ail = self.stream(True, n_users=2)
+ byname = lambda sim: {j.name: j.ranges for j in sim.all}
+ r, i = byname(ref), byname(il)
+ self.assertEqual(aref.ranges, ail.ranges)
+ for name in set(r) & set(i): # every request both runs started: same chunk calls
+ n = next(j.n for j in il.all if j.name == name)
+ if il.all[[j.name for j in il.all].index(name)].t_prefill_done is None:
+ continue
+ self.assertEqual(r[name][:len(i[name])], i[name]) if len(i[name]) <= len(r[name]) else self.assertEqual(r[name], i[name][:len(r[name])])
+ for j in il.all:
+ if j.t_prefill_done is None:
+ continue
+ flat = [x for a_, b_ in j.ranges for x in range(a_, b_)]
+ self.assertEqual(flat, list(range(0, j.n - 1))) # contiguous cover of the prompt rows, no gap, no overlap
+ self.assertTrue(all(a_ % PAGE == 0 for a_, _ in j.ranges))
+
+ def test_single_batch1_decode_while_interleaving(self):
+ s, a = self.stream(True, n_users=4)
+ for t0, t1, pre, dec in s.log:
+ if a.t_arrive <= t0 and t1 <= a.t_prefill_done:
+ self.assertLessEqual(len(dec), 1, (t0, pre, dec))
+
+ def test_single_user_path_unchanged(self):
+ ref = Sim(False); ra = ref.add("A", 45000, 5); ref.run(1e9)
+ il = Sim(True); ia = il.add("A", 45000, 5); il.run(1e9)
+ self.assertEqual(ra.ranges, ia.ranges)
+ self.assertEqual((ra.t_prefill_done, ref.clk.t), (ia.t_prefill_done, il.clk.t))
+ self.assertEqual([x[2:] for x in ref.log], [x[2:] for x in il.log])
+ self.assertIsNone(il.g._cil._lead)
+
+ def test_cached_conversation_turns_are_shorts_not_bigs(self):
+ # 20.7K-row prompts with 19.2K rows behind a tail checkpoint (~1.5K new rows): classified from the peek, they must run
+ # in the slices while the 45K prefill is parked, not wait behind it (the GPU run: C TTFT 36 s, B stalled 27 s)
+ def run(peek):
+ s = Sim(True, max_defer_s=8.0)
+ if not peek:
+ for j in (): pass
+ a = s.add("A", 45000, 1)
+ bs = [s.add(f"B{k}", 20700, 30, resume=19200) for k in range(2)]
+ if not peek:
+ for b in bs: b._tail_peek = lambda seq: 0 # the old behaviour: cursor before restore
+ s.run(1e9)
+ return s, a, bs
+ s, a, bs = run(True)
+ self.assertLess(max(b.t_prefill_done for b in bs), 8.0) # served inside the budgeted slices, before A's chunks
+ self.assertLessEqual(a.t_prefill_done, solo_big_ttft() + 8.0 + 0.3)
+ s0, a0, bs0 = run(False)
+ self.assertGreater(min(b.t_prefill_done for b in bs0), 30.0) # without the peek they are parked behind A for good
+
+ def test_budget_scales_with_the_big_prefill(self):
+ # four shorts present when an 8K prefill (6.5 s) starts: the fixed 8 s cap would let them defer it by 4 s, 18 % is ~1.2 s,
+ # which still takes the oldest short(s) whose rows fit (a slice runs a subset, not all-or-nothing)
+ solo = serve(False, [], bigs=((0.0, 8192),)).all[0].time_first_token
+ burst = [0.0, 0.0, 0.0, 0.0]
+ a = next(j for j in serve(True, burst, bigs=((0.0, 8192),), cap=5).all if j.name == "A0")
+ self.assertLessEqual(a.time_first_token, solo * 1.18 + 0.8, (a.time_first_token, solo))
+ s8 = serve(True, burst, bigs=((0.0, 8192),), cap=5, defer_frac=0.0, max_defer_s=8.0)
+ a8 = next(j for j in s8.all if j.name == "A0")
+ self.assertGreater(a8.time_first_token, a.time_first_token + 1.0) # fixed seconds hurt the small big much more
+ sh = next(j for j in serve(True, burst, bigs=((0.0, 8192),), cap=5).all if j.name == "s0")
+ self.assertLess(sh.time_first_token, a.t_prefill_done) # the oldest short got its token before the big one
+
+ def test_equal_bigs_are_served_in_arrival_order(self):
+ off = serve(False, [], bigs=tuple((0.0, 8192) for _ in range(4)), cap=4)
+ on = serve(True, [], bigs=tuple((0.0, 8192) for _ in range(4)), cap=4)
+ f_off, f_on = first_tokens(off, "A"), first_tokens(on, "A")
+ self.assertGreater(f_off[0], 0.95 * f_off[-1]) # round robin: everyone waits for everyone
+ self.assertEqual([j.name for j in sorted(on.all, key=lambda j: j.t_prefill_done)], ["A0", "A1", "A2", "A3"])
+ self.assertLess(f_on[1], 0.6 * f_off[1] + 0.01 * f_off[-1] + f_on[0]) # median 37 % earlier
+ self.assertLess((f_on[1] + f_on[2]) / 2, 0.7 * (f_off[1] + f_off[2]) / 2)
+ self.assertAlmostEqual(f_on[-1], f_off[-1], delta=0.1) # the last one pays nothing
+ self.assertEqual({j.name: j.ranges for j in off.all}, {j.name: j.ranges for j in on.all}) # same chunk calls per job
+
+ def test_default_budget_costs_the_big_less_with_the_same_short_first_tokens(self):
+ solo = solo_big_ttft()
+ for shorts_t in ([8.5, 9, 9.5, 10, 25, 30, 34], [8.5 + 6 * k for k in range(6)]):
+ fixed = serve(True, shorts_t, defer_frac=0.0, max_defer_s=8.0)
+ dflt = serve(True, shorts_t)
+ cf = first_tokens(fixed, "A")[0] / solo - 1
+ cd = first_tokens(dflt, "A")[0] / solo - 1
+ self.assertLess(cd, cf - 0.03, (cd, cf))
+ self.assertLessEqual(cd, 0.18)
+ ff, fd = first_tokens(fixed, "s"), first_tokens(dflt, "s")
+ self.assertLessEqual(sum(fd) / len(fd), sum(ff) / len(ff) * 1.03)
+ self.assertLessEqual(fd[-1], ff[-1] * 1.03)
+
+ def test_batched_decode_option_is_off_by_default(self):
+ def max_batch(**kw):
+ s = serve(True, [8.5, 9, 9.5, 10], **kw)
+ a = next(j for j in s.all if j.name == "A0") # only while the big prefill is in progress
+ return max(len(d) for t0, t1, pre, d in s.log if t1 < a.t_prefill_done and "A0" not in pre and any(x.startswith("s") for x in d))
+ self.assertEqual(max_batch(), 1)
+ self.assertGreater(max_batch(single_decode=False), 1)
+
+ def test_flag_off_by_default(self):
+ os.environ.pop("EXL3_SCHED_CHUNK_IL", None)
+ self.assertFalse(chunk_il.chunk_il_enabled())
+ s = Sim(False)
+ a, b = s.add("A", 45000, 1), s.add("B", 900, 2)
+ s.g._cil_hold(); s.g._cil_release() # no plan, no effect
+ self.assertFalse(a._cil_hold or b._cil_hold)
+
+ def test_two_bigs_fifo(self):
+ s = Sim(True)
+ a, b = s.add("A", 45000, 1), s.add("B", 40000, 1)
+ s.add("c", 500, 3)
+ s.run(1e9)
+ self.assertLess(a.t_prefill_done, b.ranges and b.t_prefill_done)
+ first_b = next(i for i, x in enumerate(s.log) if "B" in x[2])
+ last_a = max(i for i, x in enumerate(s.log) if "A" in x[2])
+ self.assertGreater(first_b, last_a) # B starts only after A's prefill is done
+
+ def test_steps_without_company_are_not_charged_to_the_leader(self):
+ def late_short_ttft(patch_solo):
+ s = Sim(True)
+ if patch_solo:
+ s.g._cil.solo = lambda: None
+ s.add("A", 45000, 1); s.add("s0", 900, 40) # s0 leaves while A is the leader; A then runs alone for ~19 s
+ s.run(1e9, arrivals=[(20.0, "s1", 900, 40)])
+ late = next(j for j in s.all if j.name == "s1")
+ return late.time_first_token - 20.0
+ self.assertLess(late_short_ttft(False), 8.0) # a slice is granted: one leader chunk (~3 s) + the short itself
+ self.assertGreater(late_short_ttft(True), 12.0) # without the re-base the solo time reads as deferral: strict FIFO
+
+ def test_planner_error_disables_interleave(self):
+ s = Sim(True)
+ s.g._cil.plan_prefill = lambda v: 1 / 0
+ a, b = s.add("A", 45000, 1), s.add("B", 900, 2)
+ import io, contextlib
+ with contextlib.redirect_stderr(io.StringIO()):
+ s.run(1e9)
+ self.assertTrue(s.g._cil_broken)
+ self.assertEqual(a.ranges[0], (0, 4096))
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/tools/qwen/test_guard.py b/tools/qwen/test_guard.py
index 0e0c69a..9baea56 100644
--- a/tools/qwen/test_guard.py
+++ b/tools/qwen/test_guard.py
@@ -66,7 +66,7 @@ class StubGenerator:
if len(self.out) >= j.max_new:
eos, reason = True, "max_new_tokens"
break
- ev = {"job": j, "serial": j.serial_number, "token_ids": torch.tensor(toks), "text": "".join("</think>" if t == CLOSE else f"<{t}>" for t in toks)}
+ ev = {"job": j, "serial": j.serial_number, "token_ids": torch.tensor(toks), "text": "".join("</think>" if t == CLOSE else f"<w{t}>" for t in toks)}
if eos:
ev |= {"eos": True, "eos_reason": reason, "new_tokens": len(self.out), "prompt_tokens": len(j.ids),
"cached_tokens": 0}
@@ -153,7 +153,7 @@ class GuardEngineTests(unittest.TestCase):
self.assertEqual(st["loop_guard"]["kind"], "final")
self.assertEqual(text.count("</think>"), 1)
self.assertFalse(loops.is_loop(text), text[-200:])
- self.assertIn("<1007>", text)
+ self.assertIn("<w1007>", text)
self.assertEqual(len(StubJob.jobs), 2)
def test_final_check_recovers_think_loop_that_ends_at_the_cap(self):
@@ -171,7 +171,7 @@ class GuardEngineTests(unittest.TestCase):
text, st = collect(make_engine(drift, per_iter=1), reasoning_first=True, loop_guard=True, max_tokens=300)
self.assertEqual(st["loop_guard"]["kind"], "final")
self.assertFalse(loops.is_loop(text), text[-200:])
- self.assertIn("<1007>", text) # the answer was generated after the cut
+ self.assertIn("<w1007>", text) # the answer was generated after the cut
self.assertLessEqual(len(st["token_ids"]), 300) # discarded tokens are not charged to max_tokens
def test_final_cut_unit(self):
@@ -198,7 +198,7 @@ class GuardEngineTests(unittest.TestCase):
text, st = collect(e, reasoning_first=True, loop_guard=True)
self.assertEqual(text.count("</think>"), 1)
self.assertIn("\n</think>\n\n", text)
- self.assertIn("<1007>", text) # the answer proceeded (8 answer tokens then eos)
+ self.assertIn("<w1007>", text) # the answer proceeded (8 answer tokens then eos)
self.assertEqual(st["loop_guard"]["kind"], "period")
self.assertEqual(len(StubJob.jobs), 2)
# restart context = prompt + thinking up to the end of the FIRST cycle + forced close
@@ -207,7 +207,7 @@ class GuardEngineTests(unittest.TestCase):
self.assertGreater(st["new_tokens"], len(st["token_ids"]))
def test_visible_text_matches_kept_tokens_with_speculative_batches(self):
- piece = lambda x: f"<{x}>"
+ piece = lambda x: f"<w{x}>"
for per_iter in (1, 2, 3, 4, 5):
text, st = collect(make_engine(loop_model(), per_iter=per_iter), reasoning_first=True, loop_guard=True)
toks = st["token_ids"]
@@ -655,5 +655,156 @@ class DetectorTests(unittest.TestCase):
self.assertEqual(serve.text_loop(s), bool(loops.is_loop(s)))
+class TextGenerator(StubGenerator):
+ """StubGenerator whose events carry real text: tokens >= 3000 map to pieces of `answer`."""
+ pieces: list = []
+
+ def iterate(self):
+ evs = super().iterate()
+ for ev in evs:
+ ev["text"] = "".join("</think>" if t == CLOSE else (self.pieces[t - 3000] if t >= 3000 else "x") for t in ev["token_ids"].tolist())
+ return evs
+
+
+class FinalCheckKeepsValidCodeTests(unittest.TestCase):
+ def test_long_valid_answer_after_thinking_is_not_regenerated(self):
+ import loopguard_corpus
+ answer = loopguard_corpus.legit()["pagoda_kyojin_original.txt"]
+ self.assertTrue(serve.text_loop(answer)) # the release-gate rule alone would trigger the final check
+ pieces = [answer[i:i + 4] for i in range(0, len(answer), 4)]
+
+ def model(ctx, job):
+ gen = ctx[3:]
+ n = len(gen)
+ if n < 5:
+ return 200 + n
+ if n == 5:
+ return CLOSE
+ return 3000 + (n - 6) if n - 6 < len(pieces) else 0
+ eng = make_engine(model, per_iter=4)
+ eng.generator = TextGenerator(model, per_iter=4)
+ eng.generator.pieces = pieces
+ text, st = collect(eng, reasoning_first=True, loop_guard=True, max_tokens=len(pieces) + 50)
+ self.assertNotIn("loop_guard", st)
+ self.assertEqual(len(StubJob.jobs), 1)
+ self.assertTrue(text.endswith(answer))
+
+
+class GuardStopVisibleTests(unittest.TestCase):
+ """A guard stop ends the answer early: clients must be able to tell it from a natural end."""
+
+ def post(self, path, payload, stats):
+ eng = FakeEngine("cut here", dict(FakeEngine("").stats, **stats))
+
+ async def fn(client):
+ r = await client.post(path, json={"model": "m", "messages": [{"role": "user", "content": "x"}], "prompt": "x"} | payload)
+ return await (r.text() if payload.get("stream") else r.json())
+ return with_client(eng, fn)
+
+ GUARD = {"eos_reason": "loop_guard", "loop_guard": {"phase": "answer", "kind": "text"}}
+
+ def test_chat_json(self):
+ c = self.post("/v1/chat/completions", {}, self.GUARD)["choices"][0]
+ self.assertEqual((c["finish_reason"], c["stop_reason"]), ("length", "loop_guard"))
+
+ def test_chat_stream(self):
+ raw = self.post("/v1/chat/completions", {"stream": True}, self.GUARD)
+ self.assertIn('"finish_reason":"length"', raw)
+ self.assertIn('"stop_reason":"loop_guard"', raw)
+
+ def test_completions_json(self):
+ c = self.post("/v1/completions", {}, self.GUARD)["choices"][0]
+ self.assertEqual((c["finish_reason"], c["stop_reason"]), ("length", "loop_guard"))
+
+ def test_natural_stop_unchanged(self):
+ c = self.post("/v1/chat/completions", {}, {})["choices"][0]
+ self.assertEqual(c["finish_reason"], "stop")
+ self.assertNotIn("stop_reason", c)
+
+
+# ------------------------------------------------------------------ answer rule: labelled corpus
+
+class AnswerCorpusTests(unittest.TestCase):
+ """Valid repetitive answers are never cut; degenerate ones are. Word-level tokens stand in for the BPE here;
+ tools/qwen/loopguard_gate.py replays the same corpus with the real Qwen and GLM tokenizers."""
+
+ @classmethod
+ def setUpClass(cls):
+ import loopguard_corpus
+ cls.legit, cls.loops = loopguard_corpus.legit(), loopguard_corpus.loops()
+
+ def test_pagoda_answer_that_was_cut_is_not_cut_now(self):
+ t = self.legit["pagoda_kyojin_original.txt"]
+ self.assertTrue(serve.text_loop(t)) # the release-gate rule alone does flag it ...
+ self.assertFalse(serve.answer_text_loop(t)) # ... the answer rule does not
+ self.assertIsNone(run_monitor(t, "answer", chunk=4))
+
+ def test_legit_never_stopped(self):
+ for name, text in self.legit.items():
+ self.assertIsNone(run_monitor(text, "answer", chunk=4), name)
+
+ def test_loops_always_stopped(self):
+ for name, text in self.loops.items():
+ if name == "char_loop": # one giant word for the word-level stand-in tokenizer: the real-tokenizer gate covers it
+ continue
+ self.assertIsNotNone(run_monitor(text, "answer", chunk=4), name)
+
+ def test_repetitive_data_is_not_cut_but_endless_data_is(self):
+ # a zero grid, identical JSON records and a zeroed hex dump repeat because the data does: the period / text rules wait
+ # DATA_SUSTAIN tokens for them (the first two were cut after about 100 tokens before)
+ import loopguard
+ for name in ("zero_grid", "zero_grid_json", "json_lines_identical", "hex_dump_zero", "hex_dump_zero_plain"):
+ self.assertTrue(loopguard.data_like(self.legit[name][:1500]), name)
+ self.assertIsNone(run_monitor(self.legit[name], "answer", chunk=1), name)
+ for name in ("zero_run_endless", "json_lines_endless"):
+ hit = run_monitor(self.loops[name], "answer", chunk=4)
+ self.assertIsNotNone(hit, name)
+ self.assertGreaterEqual(hit["at"], loopguard.DATA_SUSTAIN, name) # the backstop, not the 100-token period rule
+
+ def test_prose_and_code_are_not_data(self):
+ import loopguard
+ self.assertFalse(loopguard.data_like("I think the answer is yes. But wait, let me reconsider. " * 20))
+ self.assertFalse(loopguard.data_like("renderTile(x, y, z); tick++;\n" * 30))
+ self.assertFalse(loopguard.data_like("0 0")) # too short to tell
+ self.assertTrue(loopguard.data_like('{"a": 1, "b": "x"}\n' * 8)) # JSON lines
+
+ def test_think_phase_keeps_the_gate_rule(self):
+ t = self.legit["pagoda_kyojin_original.txt"]
+ self.assertTrue(serve.text_loop(t))
+ hit = run_monitor(t, "think", chunk=4)
+ self.assertIsNotNone(hit) # a thinking block that writes this much replayed idiom is cut
+
+
+class AnswerTapTests(unittest.TestCase):
+ def test_think_block_is_not_watched_then_answer_loop_stops(self):
+ from loopguard import AnswerTap
+ tap = AnswerTap(True)
+ for _ in range(200): # a looping think block is left alone
+ self.assertIsNone(tap.feed([5, 6], "ab "))
+ self.assertIsNone(tap.feed([7], "</thi")) # tag split across events
+ self.assertIsNone(tap.feed([8], "nk>\n"))
+ hit = None
+ for i in range(2000):
+ hit = tap.feed([11, 12, 13], "foo bar baz ")
+ if hit:
+ break
+ self.assertIsNotNone(hit)
+ self.assertEqual(hit["kind"], "period")
+
+ def test_no_think_block_watches_from_start(self):
+ from loopguard import AnswerTap
+ tap = AnswerTap(False)
+ hits = [tap.feed([1, 2, 3], "x y z ") for _ in range(400)]
+ self.assertTrue(any(hits))
+
+ def test_text_after_the_close_tag_reaches_the_monitor(self):
+ from loopguard import AnswerTap
+ tap = AnswerTap(True)
+ self.assertIsNone(tap.feed([7], "thinking...</think>The answer"))
+ self.assertEqual(tap.mon.text, "The answer") # it used to be dropped with the tokens of that event
+ self.assertIsNone(tap.feed([8], " is 42."))
+ self.assertEqual(tap.mon.text, "The answer is 42.")
+
+
if __name__ == "__main__":
unittest.main()