diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 36e9cb0..47a014a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,25 +13,27 @@ permissions: jobs: test: runs-on: macos-15 - # A run takes 5 to 8 minutes. A test that hangs stops here, not at the limit of 6 hours. - timeout-minutes: 30 - env: - # The oldest release that has every std::nn kernel that the program calls. - VX_VERSION: v0.0.5 + # With the tests of Qwen3.6, a run takes more than 30 minutes: a RUN line that compiles the app + # takes 90 to 115 s on this runner. A test that hangs stops here, not at the limit of 6 hours. + timeout-minutes: 60 steps: - uses: actions/checkout@v7 + # The file VX_VERSION names the Vx release that the program is tested with. The toolchain + # needs LLVM 22 and z3 on macOS. - name: Install Vx run: | brew install --quiet llvm@22 z3 - curl -fsSL https://vxlang.org/install.sh | VX_NO_MODIFY_PATH=1 sh - ~/.vx/current/bin/vxc --version + version=$(cat VX_VERSION) + curl -fsSL https://vxlang.org/install.sh | VX_VERSION="$version" VX_NO_MODIFY_PATH=1 sh + ~/.vx/current/bin/vxc --version | grep -F "vxc ${version#v} " # The system Python of the runner takes no packages, so they go in a venv. - name: Install the Python packages run: | + python3 --version python3 -m venv "$RUNNER_TEMP/venv" - "$RUNNER_TEMP/venv/bin/pip" install --quiet numpy ml_dtypes filecheck + "$RUNNER_TEMP/venv/bin/pip" install --quiet -r requirements-test.txt - name: Test run: PATH="$RUNNER_TEMP/venv/bin:$PATH" tests/run.sh diff --git a/README.md b/README.md index 3078b28..0e74f61 100644 --- a/README.md +++ b/README.md @@ -1,504 +1,115 @@ -# Qwen coder models in Vx +# Qwen models in Vx -This program runs Qwen coder models on the GPU of an Apple Silicon Mac. It is written in -[Vx](https://github.com/vx-lang/Vx), and it uses the GPU kernels of Vx's `std::nn`. It runs: +This program runs Qwen models on the GPU of an Apple Silicon Mac. It is written in +[Vx](https://github.com/vx-lang/Vx), and it uses the GPU kernels of Vx's `std::nn`. It generates +tokens with greedy decoding. Its tokenizer is also in Vx, so the prompt and the output are text. -- The dense Qwen2.5-Coder models, such as 0.5B and 7B, with bf16, fp8 or Q4_0 weights. -- The mixture-of-experts (MoE) model Qwen3-Coder-30B-A3B-Instruct, in Q4_0, as the section on the - MoE model below shows. +It runs these models: -The plan and its milestones are in [#5](https://github.com/vx-lang/qwen-vx/issues/5). Milestones 1 -to 6 are done. The MoE model was milestone 6, -[#6](https://github.com/vx-lang/qwen-vx/issues/6). Milestone 7 added a tokenizer in Vx, and the -prompt now runs on the GPU in chunks of tokens. +- **Qwen3.6-35B-A3B**, in Q4_0 with a 6-bit output matrix. This mixture-of-experts (MoE) model + mixes layers of linear attention (Gated DeltaNet) with layers of full attention. The program can + draft tokens with the multi-token prediction (MTP) layer of the model. +- Qwen3-Coder-30B-A3B-Instruct, an MoE model, in Q4_0. +- The dense Qwen2.5-Coder models, such as 0.5B and 7B, with bf16, fp8 or Q4_0 weights. -The program generates tokens with greedy decoding. Its tokenizer is also in Vx, so the prompt can -be text or token ids, and the program prints text or token ids. +## Speed -[`docs/optimizations.md`](docs/optimizations.md) is a journal of the optimizations: what each one -changed, its measurements, and the changes that did not help. +Qwen3.6-35B-A3B on a MacBook Air M4 with 32 GB, against llama.cpp b1b770d. Batch 1, greedy +decoding, 512 generated tokens, on 12 held-out code prompts (edit, complete, write and explain). +Generated tokens a second, the geometric mean over 3 runs of each prompt: -## Install Vx +| Decoding | qwen-vx | llama.cpp | Ratio | qwen-vx faster on | +| --- | ---: | ---: | ---: | ---: | +| Without drafts | 44.8 | 38.3 | 1.17× | 12 of 12 prompts | +| MTP drafts: `--mtp 3,5 --draft 11` against `draft-mtp` (3 tokens) | 71.2 | 58.5 | 1.22× | 12 of 12 prompts | +| Drafts from the context: `--draft 11` against `ngram-mod` | 56.3 | 46.0 | 1.22× | 11 of 12 prompts | -The program needs Vx v0.0.5 or later: +The prompt runs at 1.08× to 1.21× the speed of llama.cpp from 512 to 8,192 tokens, and generated +tokens at 1.16× to 1.21× after prompts of 64 to 32,768 tokens. With drafts, the text is the same as +without drafts. The run followed the benchmarking policy of the Vx repository. Its report, with +the setup, every run, the cases where qwen-vx is slower and the limits, is +[`docs/benchmarks/2026-11-25-qwen36-m4-mtp/`](docs/benchmarks/2026-11-25-qwen36-m4-mtp/README.md). -```sh -curl -fsSL https://vxlang.org/install.sh | sh -``` +## Install Vx -The toolchain goes in `~/.vx/current`. On a Mac, it also needs LLVM 22 (`brew install llvm@22`). -The commands below call `vxc`, so put the toolchain on `PATH`, as the installer says: +The program needs a Mac with Apple Silicon, and the Vx release that [`VX_VERSION`](VX_VERSION) +names (now v0.0.6). The toolchain also needs LLVM 22 and z3 from Homebrew: ```sh +brew install llvm@22 z3 +curl -fsSL https://vxlang.org/install.sh | VX_VERSION=$(cat VX_VERSION) sh export PATH="$HOME/.vx/bin:$PATH" ``` -To install Vx in another folder, give it as `VX_HOME`, and keep `VX_HOME` set: - -```sh -export VX_HOME="$HOME/tools/vx" -curl -fsSL https://vxlang.org/install.sh | sh -export PATH="$VX_HOME/bin:$PATH" -``` - -The commands below then name `$VX_HOME` in place of `~/.vx`, as in -`--machine $VX_HOME/current/fleet/m4-uma.vx`. - -[Getting started](https://vxlang.org/docs/getting-started.html) has the details. On a computer -with no Apple GPU, the same program runs on the CPU. +[`docs/usage.md`](docs/usage.md#install-vx) tells how to install Vx in another folder. -## Prepare a model +## Run Qwen3.6-35B-A3B -The scripts need Python 3 with NumPy. `--prompt` also needs the `tokenizers` package, and -`check_against_mlx.py` needs `mlx-lm`. The Python of Homebrew takes no packages of its own, so -put them in a virtual environment: +The scripts need Python 3.12 or later and the packages of [`requirements.txt`](requirements.txt). +The download is about 72 GB, and the weight file is about 21 GB: ```sh python3 -m venv .venv . .venv/bin/activate -pip install numpy tokenizers huggingface_hub -``` - -1. Download a model from Hugging Face, for example - [Qwen2.5-Coder-0.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-Coder-0.5B-Instruct), which - is 1 GB: - - ```sh - hf download Qwen/Qwen2.5-Coder-0.5B-Instruct --local-dir ~/models/Qwen2.5-Coder-0.5B-Instruct - ``` - -1. Convert it into the weight file and the tokenizer file that the Vx program reads: - - ```sh - python3 scripts/convert.py ~/models/Qwen2.5-Coder-0.5B-Instruct qwen-0.5b.vxw - python3 scripts/convert_tokenizer.py ~/models/Qwen2.5-Coder-0.5B-Instruct qwen.vxt - ``` - -1. Generate text with the Vx program, on the GPU: - - ```sh - vxc src/main.vx --package qwen=src --host default \ - --machine ~/.vx/current/fleet/m4-uma.vx -- qwen-0.5b.vxw \ - --tokenizer qwen.vxt --prompt "def fibonacci(n):" --steps 64 - ``` - - `vxc` first warns that it cannot check the memory of some functions with a dynamic shape - (W1029). These warnings are expected. The program then prints the prompt, the text that the - model writes, and the time of a token, about 11 ms on an M4. - - With `--chat`, the prompt is a request to the Instruct model. The program prints only the - reply, and it stops at the end of the reply. `--prompt-file FILE` reads the prompt from a file: - - ```sh - vxc src/main.vx --package qwen=src --host default \ - --machine ~/.vx/current/fleet/m4-uma.vx -- qwen-0.5b.vxw \ - --tokenizer qwen.vxt --chat --prompt "Write a C++ function that reverses a string." --steps 300 - ``` - - With `--draft 7`, the program checks drafts from the context: the tokens after the longest - earlier match of the last tokens. When the model keeps a draft, several tokens come from one - read of the weights, and the text is the same as without `--draft`. This helps most when the - reply repeats the prompt, as an edit of a file does: about 1.8 times as fast with the 30B - model (`docs/optimizations.md`, entry 14). It needs the 30B model in Q4_0 with the 6-bit - `lm_head` (`scripts/convert.py --q4 --q6-lm-head`), and `--steps` of at least 16. - -1. Generate a few tokens with the NumPy reference. It prints the prompt as token ids: - - ```sh - python3 scripts/reference.py qwen-0.5b.vxw \ - --tokenizer ~/models/Qwen2.5-Coder-0.5B-Instruct --prompt "def fibonacci(n):" --steps 8 - ``` - -1. Generate the same tokens with the Vx program. With `--tokens`, the prompt is token ids, and the - program prints the lines of `reference.py`. `--lines` prints the same lines for a text prompt: - - ```sh - vxc src/main.vx --package qwen=src --host default \ - --machine ~/.vx/current/fleet/m4-uma.vx -- qwen-0.5b.vxw --tokens 750,75698,1445,1648 --steps 8 - vxc src/main.vx --package qwen=src --host default \ - --machine ~/.vx/current/fleet/m4-uma.vx -- qwen-0.5b.vxw \ - --tokenizer qwen.vxt --prompt "def fibonacci(n):" --lines --steps 8 - ``` - - `compare.py` checks the output of `reference.py` and of the Vx program, when each is saved in a - file: - - ```sh - python3 scripts/compare.py reference.txt vx.txt - ``` - -`make_tiny_model.py` writes a model with the same layers and random weights. It is small enough -for tests that cannot download a real model. With `--moe`, it writes a tiny model with the layers -of Qwen3-Coder-30B-A3B. - -## The scripts - -| Script | What it does | -| --- | --- | -| `scripts/convert.py` | Converts a Hugging Face Qwen2 or Qwen3 MoE folder into a weight file. | -| `scripts/reference.py` | Computes the logits and the greedy tokens with NumPy, in float32. | -| `scripts/check_against_mlx.py` | Compares `reference.py` with MLX on the same model. | -| `scripts/compare.py` | Compares the output of the Vx program with the output of `reference.py`. | -| `scripts/make_tiny_model.py` | Writes a tiny model with random weights. | -| `scripts/qwen_weights.py` | Reads and writes the weight file. Its first comment describes the format. | -| `scripts/test_qwen_weights.py` | Tests the f8e4m3, Q4_0 and 6-bit codes, their scales and the quantized weight files. | -| `scripts/importance.py` | Measures the importance matrix of a bf16 model, for `convert.py --importance`. | -| `scripts/test_importance.py` | Tests `importance.py`. | -| `scripts/convert_tokenizer.py` | Converts a tokenizer.json into a tokenizer file. Its first comment describes the format. | -| `scripts/make_tiny_tokenizer.py` | Writes a tiny tokenizer.json, and texts that test each step of the tokenizer. | -| `scripts/test_tokenizer.py` | Compares the tokenizer in Vx with the `tokenizers` package. | -| `scripts/chat.py` | Chats with a model through a session, with a cache of the system prompt. | -| `scripts/make_vx_guides.py` | Makes the guides of `docs/vx-guides` from the Vx book. | -| `scripts/make_draft_prompts.py` | Writes the 12 code prompts that measure decoding with drafts. | -| `scripts/record_experts.cpp` | Records the greedy output and the experts of every position, with llama.cpp. Its first comment says how to build it. | -| `scripts/simulate_drafts.py` | Replays the recorded outputs as rounds of decoding with drafts, and estimates the speedup of each draft policy. | -| `scripts/test_simulate_drafts.py` | Tests `simulate_drafts.py`. | - -[`examples/`](examples/README.md) asks the 30B model for programs in Rust, C++ and Python. It -compiles each one and checks its output. - -## fp8 weights - -`convert.py --fp8` stores each weight matrix as f8e4m3 codes, one byte for each weight, with one f32 -scale for each block of 128 x 128. A weight is the value of its code times the scale of its block. -The norms, the biases and the embedding table stay bf16, so a token reads about half the bytes of -bf16. The Vx program reads an fp8 file like a bf16 file, and runs the fp8 kernels of `std::nn` for -it. - -`reference.py` widens the codes and scales exactly to float32. With `--perplexity`, it measures -how well a model predicts a text. On the first 512 tokens of `scripts/tools/gen_error_index.py` in the Vx repository: - -| Model | bf16 perplexity | fp8 perplexity | Greedy tokens of fp8 | -| --- | --- | --- | --- | -| Qwen2.5-Coder-0.5B-Instruct | 20.054 | 20.030 | the same 64 as bf16 | -| Qwen2.5-Coder-7B-Instruct | 10.072 | 10.085 | the same 64 as bf16 | - -On the fp8 file, the Vx program chose the same 64 greedy tokens as `reference.py`, with each logit -within 6e-05. One token of the 7B model took 95 ms in fp8 and 156 ms in bf16 on a quiet M4, which -is about 10.5 and 6.4 tokens per second. - -## Q4_0 weights - -`convert.py --q4` stores each weight matrix except `lm_head` in the Q4_0 format of llama.cpp. A -row has one f16 scale for each 32 weights, and each weight is a 4-bit code from 0 to 15. The -weight is (code - 8) times its scale. The codes round as llama.cpp rounds them, and a test checks -them against the loop of llama.cpp. For Qwen2.5-Coder-7B-Instruct, the codes and scales of all -197 Q4_0 tensors were the same bits as in the Q4_0 GGUF file that Qwen publishes. `lm_head` is fp8, as llama.cpp also keeps its output matrix -above 4 bits. - -`convert.py --q4 --importance FILE` rounds each group of 32 weights with an importance matrix, as -llama.cpp does with one. `importance.py` measures it: the mean square of each input of each -matrix over a sample text, for each expert on its own tokens. The converter then tries 19 scales -for each group, and keeps the one with the smallest error, where the error of a weight counts as -much as its input matters. A test checks the codes and scales against the loops of llama.cpp. - -`convert.py --q4 --q6-lm-head` stores `lm_head` in 6 bits in place of fp8: a code from 0 to 63 for -each weight, and an f16 scale for each 32 weights of a row. The weight is (code - 32) times its -scale. That is 6.5 bits for each weight, as in the Q6_K of llama.cpp, and the codes round as its -`make_qx_quants` rounds them. The `lm_head` of Qwen3-Coder-30B-A3B is then 253 MB in place of -311 MB, and `src/q6.vx` reads it. See [the MoE model](#the-moe-model) for its cost in perplexity. - -The Vx program reads a Q4_0 file like the others, and runs the Q4_0 kernels of `std::nn` for it. -Of four 4-bit formats, Q4_0 was the closest to bf16 on the 7B model. The measurement is in -[#6](https://github.com/vx-lang/qwen-vx/issues/6#issuecomment-6879596230). - -## The MoE model - -Qwen3-Coder-30B-A3B is 61 GB in bf16, so this Mac runs it in Q4_0, at 17.8 GB: - -```sh -python3 scripts/convert.py --q4 ~/models/Qwen3-Coder-30B-A3B-Instruct qwen3-30b-q4.vxw -vxc src/main.vx --package qwen=src --host default \ - --machine ~/.vx/current/fleet/m4-uma.vx -- qwen3-30b-q4.vxw --tokens 750,75698,1445,982,257 --steps 64 +pip install -r requirements.txt +hf download Qwen/Qwen3.6-35B-A3B --local-dir ~/models/Qwen3.6-35B-A3B +python3 scripts/convert.py --q4 --q6-lm-head ~/models/Qwen3.6-35B-A3B qwen36.vxw +python3 scripts/convert_tokenizer.py ~/models/Qwen3.6-35B-A3B qwen36.vxt ``` -The conversion took 3.4 minutes and 18.6 GB of memory on an M4 with 32 GB. The tokens are -`def fibonacci(n):` and a new line with 4 spaces. The tokenizer of the 30B model gives the same -tokens for that text, so `--tokenizer qwen3.vxt --prompt "$(printf 'def fibonacci(n):\n ')"` is -the same prompt, after `convert_tokenizer.py ~/models/Qwen3-Coder-30B-A3B-Instruct qwen3.vxt`. The Vx program wrote a recursive -and an iterative `fibonacci` in the 64 steps. `reference.py` on the same file chose the same 64 -tokens, with each logit within 5.4e-05. - -The program gives the GPU the pages of the mapped weight file, with no copy. This needs the vxc of -Vx `main` at c4e57fd7 or later ([vx-lang/Vx#3606](https://github.com/vx-lang/Vx/pull/3606)). On -an M4 with 32 GB, the load takes about 10.5 s, and the program has 0.3 GB of private memory at -a short context and 2.1 GB at 8,000 tokens of context. When it copied the weights, the load took -29 to 38 s and 18.9 to 20.4 GB. The file cache keeps one copy of the weights for all the runs, and -macOS can drop those pages when other programs need memory. - -An importance matrix makes the Q4_0 file closer to bf16. `importance.py` needs the bf16 file, and -took 110 minutes for 150 chunks of 512 tokens on an M4 with 32 GB: - -```sh -python3 scripts/convert.py ~/models/Qwen3-Coder-30B-A3B-Instruct qwen3-30b.vxw -python3 scripts/importance.py qwen3-30b.vxw --tokenizer ~/models/Qwen3-Coder-30B-A3B-Instruct \ - --out importance.npz --chunks-per-text 8 TEXT... -python3 scripts/convert.py --q4 --importance importance.npz \ - ~/models/Qwen3-Coder-30B-A3B-Instruct qwen3-30b-q4.vxw -``` - -The sample text below was the first 8 chunks of each of 19 files: - -- `SmallVector.h` and `DenseMap.h` of LLVM 22. -- `argparse.py`, `subprocess.py`, `asyncio/base_events.py`, `http/client.py` and - `pydoc_data/topics.py` of Python 3.13. -- `src/ahocorasick.rs` of aho-corasick 1.1.4, `src/map.rs` of indexmap 2.14.0, `src/expr.rs` of - syn 2.0.118, and `src/parser/parser.rs` of clap_builder 4.6.0. -- `src/runtime/scheduler/multi_thread/worker.rs` and `CHANGELOG.md` of tokio 1.52.3. -- `lib/compress/zstd_compress.c` of zstd 1.5.7, and `lib/commands/ls.js` and - `lib/utils/display.js` of npm 11.16.0. -- `stdlib/std/nn.vx`, `www/book/src/tasks.md` and `www/book/src/ownership.md` of the Vx repository. - -Both programs measured the perplexity as `llama-perplexity -c 512 --chunks 8 --no-escape` -measures it, on three files of the Vx repository that are not in the sample: -`src/dialect/MetalImage.cpp` at vx-lang/Vx@7e3cf6a3, `src/hir/check/calls.rs` at -vx-lang/Vx@4df81bf6, and `docs/parallel_compiler_architecture.md` at vx-lang/Vx@f2415488. - -| Weights | Program | MetalImage.cpp | calls.rs | architecture.md | -| --- | --- | --- | --- | --- | -| bf16 | `reference.py` | 3.6813 | 5.9254 | 5.6790 | -| Q4_0 of `convert.py --q4` | `reference.py` | 3.7290 | 6.0010 | 5.7670 | -| Q4_0 of `convert.py --q4 --importance` | `reference.py` | 3.6881 | 5.9664 | 5.7472 | -| The Q4_0 codes of unsloth in a file of `convert.py --q4` | `reference.py` | 3.6918 | 5.9535 | 5.7516 | -| Q4_0 of unsloth with an importance matrix | `llama-perplexity` | 3.7091 | not measured | not measured | - -The importance matrix removed 86% of the gap to bf16 on `MetalImage.cpp`, 46% on `calls.rs` and -23% on the architecture document. - -`lm_head` in 6 bits (`--q6-lm-head`) costs 0 to 0.25% of perplexity. This table has the Q4_0 file of -`convert.py --q4` with three forms of `lm_head`, all measured again with `reference.py` on -2026-11-17. For the bf16 row, the script took `lm_head` from the bf16 file. - -| `lm_head` | Bytes a token | MetalImage.cpp | calls.rs | -| --- | --- | --- | --- | -| bf16 | 622 MB | 3.7395 | 6.0024 | -| fp8 | 311 MB | 3.7283 | 6.0032 | -| 6 bits | 253 MB | 3.7392 | 6.0177 | - -On `MetalImage.cpp`, fp8 happens to score below bf16, and 6 bits scores the same as bf16. -A scale for each 16 weights in place of 32 gave 3.7393 on `MetalImage.cpp`, and rounding to the -largest weight of each group, without the search of `make_qx_quants`, gave 3.7392, so neither helps. - -The fourth file has the codes and scales of the unsloth file for each matrix that is Q4_0 there. -The `experts_down` of the first 6 layers are Q4_1 there, so they stay ours. The unsloth file also -has `lm_head` in Q6_K and the embedding table in Q4_0. So 3.7091 and 3.6918 differ in the program -and in some weights. Compare files with the same program. - -A token took 28.0 ms in Vx with the cheaper kernel launches of -[#3152](https://github.com/vx-lang/Vx/pull/3152) and [#3165](https://github.com/vx-lang/Vx/pull/3165), -and 24.3 ms in llama.cpp. Each token runs about 477 kernels. The details are in -[#6](https://github.com/vx-lang/qwen-vx/issues/6#issuecomment-6879596324). - -## The prompt in chunks - -A generated token reads every weight that it uses, so it waits for memory. The prompt has all its -tokens at the start, so the program runs it in chunks of up to 2048 tokens. A chunk reads each -weight once for all its tokens. `src/prefill.vx` has the kernels of a chunk: - -- One product for each weight format. A block decodes 128 rows of the matrix and 32 columns at a - time into shared memory, and multiplies them with the inputs of 16 tokens, with a matmul of - tiles (`@`). -- For the experts of a MoE layer, the CPU sorts the tokens of the chunk by expert. Then a tile of - 16 tokens reads the weights of one expert. -- Attention in three passes: the scores, as a matmul of the queries and the keys; their softmax; - and the sum of the values, as a matmul of the weights and the values. The rows of the matmuls - are the query heads of one key-value head for two tokens, so a tile of the cache serves 16 - rows. The matmuls skip the positions after the tokens of their tile. Attention takes 128 - tokens of the chunk at a time, so that its scratch tensor of scores does not grow with the - chunk. - -The time of each prompt token, on an M4 with 32 GB, with the prompt as the first tokens of this -README: - -| Model | Prompt | One token at a time | In chunks | -| --- | --- | --- | --- | -| Qwen2.5-Coder-0.5B-Instruct, bf16 | 600 tokens | 11.1 ms | 1.15 ms | -| Qwen3-Coder-30B-A3B-Instruct, Q4_0 | 1000 tokens | 46.7 ms | 10.8 ms | -| Qwen3-Coder-30B-A3B-Instruct, Q4_0 | 2000 tokens | | 8.1 ms | - -Both ways chose the same tokens after the prompt. On the 0.5B model, `compare.py` compared 32 steps -with `reference.py`, and the largest logit difference was 5.5e-05. The times include the first -compile of the kernels of a chunk, about 4 seconds. Without it, the prompt of 2000 tokens takes -7.0 ms a token. - -Before the attention in tiles, each block did one token, and so each chunk read the whole cache -once for each token in each layer. Then the prompts of 1000 and 2000 tokens took 15.1 ms and -16.2 ms a token. Now the products of the experts take most of the time of a chunk. Their `@` -loads its sum from shared memory and stores it back for each 32 columns, and the 32 KB of shared -memory does not hold larger tiles -([#19](https://github.com/vx-lang/qwen-vx/issues/19)). - -`tests/prefill.vx` runs a prompt of 40 tokens through each tiny model one token at a time, and in -chunks of 16 tokens. The logits of the last token must be within 0.0001, and the next 8 tokens -equal. - -## Long contexts - -A generated token attends to every position before it. The `nn_attention` of Vx v0.0.4 has one -block for each query head, so its time grows with the number of positions. The `nn_attention` of -Vx main splits the positions among blocks -([vx-lang/Vx#3216](https://github.com/vx-lang/Vx/pull/3216)). `src/attention.vx` is a copy of it, -until a Vx release has it ([#4](https://github.com/vx-lang/qwen-vx/issues/4)). - -The time of a generated token of Qwen3-Coder-30B-A3B in Q4_0, on an M4 with 32 GB, after a prompt -of the first tokens of this README: - -| Positions | One block for each head | Positions split among blocks | -| --- | --- | --- | -| 5 | 26.7 ms | 25.4 ms | -| 1000 | 40.7 ms | 27.5 ms | -| 2000 | 57.3 ms | 30.8 ms | - -Both chose the same tokens. On Qwen2.5-Coder-0.5B, 100 tokens after a prompt of 600 went past -position 640, where a block takes 64 positions in place of 32. `compare.py` gave the same tokens -as `reference.py`, with each logit within 5.3e-05. `tests/generate.vx` also runs the tiny models -with 1024 positions after a prompt of 700 tokens. - -## Sessions and the prompt cache - -`scripts/chat.py` keeps the model and its KV cache between turns. It runs `src/main.vx --session`, -and sends each turn the whole conversation. The session finds the longest prefix of tokens that the -cache holds, and runs only the tokens after it: +Then ask the model: ```sh -python3 scripts/convert_tokenizer.py ~/models/Qwen3-Coder-30B-A3B-Instruct qwen3.vxt -python3 scripts/chat.py qwen3-30b-q4.vxw qwen3.vxt --system-file SYSTEM.md --cache system.kv +vxc -O2 src/main.vx --package qwen=src --host default \ + --machine ~/.vx/current/fleet/m4-uma.vx -- qwen36.vxw --tokenizer qwen36.vxt \ + --chat --prompt "Write a C++ function that reverses a string." --steps 512 --mtp 3,5 --draft 11 ``` -With `--cache`, the first session runs the system prompt once and saves its KV cache to the file. -Later sessions load the file, so the system prompt does not run again. A cache file fits only the -model and the weight file that made it. - -vxc does not give its standard input to the program, and it keeps the standard output of the -program until the program ends. So a session reads its requests from one named pipe and writes its -replies to another. The comment at the start of `src/session.vx` describes the requests. - -On an M4 with 32 GB, with a system prompt of the first 8000 characters of this README, and -Qwen3-Coder-30B-A3B in Q4_0: - -| Turn | Prompt | Tokens that ran | Time of the prompt | -| --- | --- | --- | --- | -| The first, with no cache | 2465 tokens | 2465 | 50.0 s | -| The second, in the same session | 2539 tokens | 29 | 2.3 s | -| The first, in a new session that loaded the cache of the system prompt | 2465 tokens | 20 | 2.5 s | - -The KV cache holds f16 values, 98 KB for each token of Qwen3-Coder-30B-A3B, so the cache file of -the 2445 tokens of the system prompt takes 240 MB. With f32 values it took 481 MB, 0.4 s to save -and 1.9 s to load, and the reply after the load was the same text as the reply with no cache. A session -takes about a minute to start, to compile the program and to load the weights. +`vxc` compiles the program and runs it. It first warns that it cannot check the memory of some +functions with a dynamic shape (W1029). These warnings are expected. Use `-O2` for every run that +you time. -[`docs/vx-guides`](docs/vx-guides) has system prompts that teach Qwen3-Coder to write Vx, which -it never learned. Each one is a set of chapters of the Vx book for one kind of program, such as -kernels on the GPU of a Mac, of about 13000 tokens. With `--cache`, it runs once. +## Options -`tests/session.vx` runs a conversation of three turns on the tiny model with -`scripts/chat.py --check`. Each turn must give the text of a fresh run, and a saved cache must give -the same text in a new session. - -## The Vx code - -| File | What it does | +| Option | What it does | | --- | --- | -| `src/weights.vx` | Loads a weight file into GPU memory, for the kernels of `std::nn`. | -| `src/model.vx` | Makes the tensors and the KV cache once, and runs one token through all layers. | -| `src/prefill.vx` | Runs the prompt through all layers in chunks of tokens. | -| `src/attention.vx` | The attention of a generated token, with the positions split among blocks. | -| `src/tokenizer.vx` | Turns text into token ids and token ids into text, with a tokenizer file. | -| `src/session.vx` | Keeps the model and the KV cache, and answers the requests of `scripts/chat.py`. | -| `src/main.vx` | Generates tokens with greedy decoding, and prints text or the lines of `reference.py`. | - -A program imports the modules as `qwen::weights`, `qwen::model`, `qwen::attention`, `qwen::prefill`, -`qwen::tokenizer` and `qwen::session`, with `vxc --package qwen=src`. A program in another folder -names the `src` folder of this repository. - -The tests are in `tests/`. They need a Python 3 that has NumPy and ml_dtypes, and `FileCheck` from -LLVM or the Python port (`pip install numpy ml_dtypes filecheck`). `tests/run.sh` takes `vxc` and the -machine files from `$VX_HOME/current` when `VX_HOME` is set, else from the `vxc` on `PATH`, else -from `~/.vx/current`: +| `--prompt TEXT`, `--prompt-file FILE` | The prompt, as text. It needs `--tokenizer FILE`. | +| `--chat` | Puts the prompt in the chat format, and prints only the reply. | +| `--think` | With `--chat`, lets Qwen3.6 think before it replies. | +| `--steps N` | Generates at most N tokens. The program also stops at the end of the reply. | +| `--ignore-eos` | Does not stop at the end of the reply. | +| `--mtp K[,L]` | Drafts tokens with the MTP layer of Qwen3.6: up to K tokens while the model keeps most drafts (1 token otherwise), and up to L while it keeps almost all of them. | +| `--draft D[,M]` | Drafts up to D tokens from the context, after a match of the last tokens. With `--mtp`, a round drafts from the context only after a match of M tokens (16 by default). | +| `--tokens IDS`, `--lines` | The prompt as token ids, and the output as the lines of `scripts/reference.py`. | +| `--session` | Keeps the model and its cache between the turns of `scripts/chat.py`. | + +Drafts do not change the text: the model checks each draft, and keeps only the tokens that it +would generate without drafts. They make the program faster when the model keeps most of them. +`--draft` helps most when the reply repeats the prompt, as an edit of a file does. The benchmark +uses `--mtp 3,5 --draft 11` for Qwen3.6. The first comment of [`src/main.vx`](src/main.vx) +describes all the options. + +## Tests + +The tests need the packages of [`requirements-test.txt`](requirements-test.txt). They run on tiny +models with random weights, so they need no download: ```sh +pip install -r requirements-test.txt tests/run.sh ``` -`tests/print_weights.vx` also checks a real model. Its lines must equal those of -`reference.py --tensors`: - -```sh -vxc tests/print_weights.vx --package qwen=src --host default \ - --machine ~/.vx/current/fleet/m4-uma.vx -- qwen-0.5b.vxw -python3 scripts/reference.py qwen-0.5b.vxw --tensors -``` - -## The tokenizer - -`src/tokenizer.vx` is the byte-level BPE tokenizer of Qwen2 and Qwen3. It splits out the added -tokens, such as `<|im_start|>`, and applies Unicode NFC to the text between them. Then it splits -the text with the regex of the pre-tokenizer, and merges the bytes of each piece by the ranks of -tokenizer.json. `convert_tokenizer.py` describes the file and the steps. The file holds sorted -tables, so each lookup is a binary search in the mapped file. - -The tokenizer gives the ids of the `tokenizers` package of Hugging Face. On 21.5 MB of text, -`test_tokenizer.py` found the same ids for each of 4783 texts, with both the Qwen2.5-Coder and the -Qwen3-Coder tokenizer. The texts were this repository, Python, Rust and C++ sources, and 3000 texts -of random Unicode characters, marks, Hangul, emoji, white space and added tokens. The Vx program -encoded 3 MB of source files, 820,000 tokens, in about 2.4 seconds. - -The NFC step of `tokenizers` has the data of an old Unicode version. It does not know the -combining class of 120 marks that later versions added, and it does not make 21 newer composites. -`convert_tokenizer.py` leaves both out of its tables, so that the ids are the same. -`test_tokenizer.py` measures the two lists again, and fails when they change. +## Documentation -`tests/tokenize.vx` checks a tiny tokenizer from `make_tiny_tokenizer.py` against the ids that -`tokenizers` gave for it. So CI checks the tokenizer without a download. To compare with -`tokenizers` on a large corpus: - -```sh -QWEN_TOKENIZER_CORPUS_MB=40 python3 scripts/test_tokenizer.py -``` - -## The check of the Vx program - -`compare.py` compared the Vx program with `reference.py` over 64 greedy steps, after the prompt -`def fibonacci(n):` and a new line. Both chose the same tokens. - -| Model | Largest logit difference | +| File | What it has | | --- | --- | -| tiny model | 4.7e-05, over 16 steps | -| tiny model, Q4_0 | 4.8e-05, over 16 steps | -| tiny MoE model | 4.7e-05, over 16 steps | -| tiny MoE model, Q4_0 | 5.0e-05, over 16 steps | -| Qwen2.5-Coder-0.5B-Instruct | 5.3e-05 | -| Qwen2.5-Coder-7B-Instruct | 6.0e-05 | - -The tiny model runs in CI with `tests/generate.vx`. That test fails when RoPE uses another theta, -when a token runs at the wrong position, and when the two norms of a layer swap their weights. -For the tiny MoE model, it fails when the router reads the hidden state before its norm, when a -token uses one expert in place of two, and when the Q and K norms are missing or swapped. - -## The check of the reference - -`check_against_mlx.py` compared the reference with MLX in float32 over a 5-token prompt and 32 -greedy steps. Both chose the same tokens. - -| Model | Largest logit difference | Time on an M4 | Peak memory | -| --- | --- | --- | --- | -| Qwen2.5-Coder-0.5B-Instruct | 8.7e-05 | 7 s | 5 GB | -| Qwen2.5-Coder-7B-Instruct | 6.3e-05 | 19 min | 15 GB | - -The check fails, as it should, when RoPE uses another theta, when the causal mask lets a token -see the next one, when the program does not add the Q, K and V bias, and when the converter swaps -K and V. - -For the tiny MoE model, `make_tiny_model.py --moe --hugging-face DIR` also writes the model as a -Hugging Face folder, which MLX reads: - -```sh -python3 scripts/make_tiny_model.py --moe --hugging-face tiny-moe tiny-moe.vxw -python3 scripts/check_against_mlx.py --tokens 17,200,3,95,41 tiny-moe tiny-moe.vxw -``` - -Over 32 greedy steps, both chose the same tokens, and the largest logit difference was 8.7e-06. -The check fails when the router chooses the smallest experts or one expert too few, or when it -does not scale the weights of the chosen experts to sum to 1. It also fails when an expert uses -the down matrix of the next expert, when the converter puts the up rows before the gate rows, or -when the Q and K norms are missing, swapped or after RoPE. +| [`docs/usage.md`](docs/usage.md) | The installation, the dense and the 30B models, sessions and the prompt cache, the scripts, the Vx code and the tests. | +| [`docs/weights.md`](docs/weights.md) | The fp8, Q4_0 and 6-bit formats, the importance matrix, and their perplexity. | +| [`docs/internals.md`](docs/internals.md) | The prompt in chunks, the attention of long contexts, and the tokenizer. | +| [`docs/checks.md`](docs/checks.md) | The checks of the Vx program against the NumPy reference, and of the reference against MLX. | +| [`docs/optimizations.md`](docs/optimizations.md) | A journal of the optimizations: what each one changed, and its measurements. | +| [`docs/benchmarks/`](docs/benchmarks) | The runs against llama.cpp, with their logs and scripts. | +| [`docs/vx-guides/`](docs/vx-guides) | System prompts that teach Qwen3-Coder to write Vx. | +| [`examples/`](examples/README.md) | The 30B model writes programs in Rust, C++ and Python, and a script compiles and checks each one. | + +The plan and its milestones are in [#5](https://github.com/vx-lang/qwen-vx/issues/5). diff --git a/THIRD_PARTY_NOTICES b/THIRD_PARTY_NOTICES new file mode 100644 index 0000000..4885cc6 --- /dev/null +++ b/THIRD_PARTY_NOTICES @@ -0,0 +1,59 @@ +Third-party notices +=================== + +The code of this repository is under the Apache License v2.0 with LLVM Exceptions (LICENSE). +Some of it follows the design of code from other projects. This file lists each such piece, the +files that hold it, and the license of the project that it comes from. + +The repository has no copy of another project's source files. The pieces below are written anew in +Vx, in MLIR that a script of this repository prints, or in Python, after the design of the named +upstream code. The upstream commit that each design was read from was not recorded. + + +1. llama.cpp (https://github.com/ggml-org/llama.cpp), MIT License +----------------------------------------------------------------- + +| Files | Follows | +| --- | --- | +| src/attention.vx (vec_attention), scripts/mlir_kernels/decode_attention.py | kernel_flash_attn_ext_vec and kernel_flash_attn_ext_vec_reduce, in ggml/src/ggml-metal/ggml-metal.metal of older releases and ggml/src/ggml-metal/kernels/fa_vec_*.metal in v1.0.0 | +| src/round.vx (round_attention), scripts/mlir_kernels/round_attention.py | the same kernels, for several queries in a row | +| src/prefill.vx (the attention of the prompt), scripts/mlir_kernels/flash_attention.py | kernel_flash_attn_ext, ggml/src/ggml-metal/kernels/fa_common.metal | +| src/prefill.vx (pf_mm_q4_set), scripts/mlir_kernels/expert_product.py | kernel_mul_mm_id, ggml/src/ggml-metal/kernels/mul_mm.metal | +| src/products.vx | the shape of a block of kernel_mul_mv_q4_0_f32 (2 SIMD groups of 4 rows), ggml/src/ggml-metal/kernels/mul_mv.metal | +| scripts/qwen_weights.py (Q4_0 codes) | the rounding of quantize_row_q4_0_ref and the search of quantize_row_q4_0_impl, ggml/src/ggml-quants.c | + +The Q4_0 format itself (a 4-bit code and an f16 scale for each 32 weights, a weight being +(code - 8) times the scale) is the Q4_0 of llama.cpp. + +The license of llama.cpp: + +MIT License + +Copyright (c) 2023-2026 The ggml authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +2. Model weights and tokenizers +------------------------------- + +The repository has no model weights and no tokenizer files. scripts/convert.py and +scripts/convert_tokenizer.py make the files that the program reads from a model of Hugging Face. +Each model has its own license, on its model card. The tests make tiny random models with +scripts/make_tiny_model.py and scripts/make_tiny_tokenizer.py. diff --git a/VX_VERSION b/VX_VERSION new file mode 100644 index 0000000..77cada2 --- /dev/null +++ b/VX_VERSION @@ -0,0 +1 @@ +v0.0.6 diff --git a/decode/README.md b/decode/README.md index 49c8895..e06e181 100644 --- a/decode/README.md +++ b/decode/README.md @@ -14,7 +14,7 @@ Qwen3-Coder-30B-A3B in Q4_0 on an M4 with 32 GB. ## Run them ```sh -vxc decode/profile_decode.vx --package qwen=src --host default \ +vxc -O2 decode/profile_decode.vx --package qwen=src --host default \ --machine ~/.vx/current/fleet/m4-uma.vx -- qwen3-30b-q4.vxw clang -O2 -fobjc-arc -framework Foundation -framework Metal decode/bandwidth.m -o bandwidth diff --git a/decode/profile_decode.vx b/decode/profile_decode.vx index b271a41..018492e 100644 --- a/decode/profile_decode.vx +++ b/decode/profile_decode.vx @@ -9,7 +9,7 @@ // out, after a warm-up. `skip` is a mask of the parts to leave out. The results of a run with a // part left out are wrong, but its time shows the cost of that part. See README.md. // -// vxc decode/profile_decode.vx --package qwen=src --host default \ +// vxc -O2 decode/profile_decode.vx --package qwen=src --host default \ // --machine ~/.vx/current/fleet/m4-uma.vx -- qwen3-30b-q4.vxw import core::convert; import std::nn; @@ -19,6 +19,8 @@ import qwen::attention; import qwen::weights; import qwen::model; import qwen::prefill; +import std::root; +import std::string; const NORMS : i32 = 1; const QKV : i32 = 2; @@ -148,8 +150,8 @@ fn print_part(m : i32, t : f64, part : f64) -> void { return; } -fn main(argc : i32, argv : *mut *mut i8) -> i32 { - let w = load_weights(unsafe { argv[1] }); +fn main(root : Root, args : Vec) -> i32 { + let w = load_weights(&root.files, args.get_ref(1)); assert(w.config.num_experts > 0 && w.layers[0].gate_up.dtype == U4, "give the Q4_0 file of the 30B MoE model"); let mut s = new_state(&w.config, 2048); let mut next = transfer(Tensor([1]), Memory::HBM); diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/.gitignore b/docs/benchmarks/2026-11-20-qwen36-m4/.gitignore new file mode 100644 index 0000000..5b81679 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/.gitignore @@ -0,0 +1,2 @@ +logs/ +__pycache__/ diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/README.md b/docs/benchmarks/2026-11-20-qwen36-m4/README.md new file mode 100644 index 0000000..ccbc492 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/README.md @@ -0,0 +1,365 @@ +# Qwen3.6-35B-A3B on an M4: qwen-vx against llama.cpp + +Run on 2026-11-20 and 2026-11-21, as `docs/benchmarking_policy.md` of the Vx repository asks. The +app is qwen-vx at the code of PR #98 (prefill kernels), compiled by vxc 0.0.5 with `-O2`. The +baseline is llama.cpp at commit b1b770d (2026-11-13), Release build, Metal. + +## Claims + +All numbers are for batch 1, greedy decoding (temperature 0), on an M4 MacBook Air with 32 GB. +The model is Qwen3.6-35B-A3B. Both files have the same Q4_0 matrices and a 6-bit output matrix +(6.5 against 6.5625 bits a weight). The token embedding is bf16 in the app and Q4_0 in llama.cpp, +and a token reads one row of it. The "held-out prompts" are 12 chat prompts of 35 to 1,668 tokens. +`make_prompts.py` wrote them for this run (commit 5f57020, 2026-11-20). The draft rule of the app +is older (commit 17ebe25, 2026-11-19), and table T chose the draft lengths on other prompts. + +- **Decode:** 44.5 against 38.3 generated tokens a second (1.16×), Qwen3.6-35B-A3B in Q4_0 with a + 6-bit output matrix, on the 12 held-out prompts, 512 generated tokens, on an M4 with 32 GB, batch + 1, against llama.cpp b1b770d (`llama-completion`). qwen-vx is faster on 12 of 12 prompts (1.16× + to 1.17×). +- **Decode after a long prompt:** 1.12× to 1.21× from 64 to 32,768 prompt tokens (table A), for + example 41.1 against 35.8 tokens a second after 8,192 tokens. +- **Prompt:** 492 against 404 prompt tokens a second (1.22×) for a prompt of 2,048 tokens, 453 + against 420 (1.08×) at 512, and 400 against 358 (1.12×) at 8,192 (table P, the app's runs after + its first run in a process). +- **Speculative decoding with drafts from the context:** 51.7 against 45.9 generated tokens a + second (1.12×), `qwen-vx --draft 7` against `llama-speculative-simple --spec-type ngram-mod`, on + the 12 held-out prompts. qwen-vx is faster on 10 of 12 prompts (0.61× to 1.49×). Against + `ngram-cache`: 51.7 against 41.3 (1.25×), faster on 11 of 12. + +Where qwen-vx is slower: + +- **Drafts from the MTP heads of the model.** llama.cpp with `--spec-type draft-mtp` (3 tokens) + makes 58.6 tokens a second, against 51.7 for `qwen-vx --draft 7` (qwen-vx is 0.88×). qwen-vx is + faster on 3 of 12 prompts, one of them (edit1) by 0.1%. The app cannot use the MTP heads yet. Its + drafts gain on edit prompts (13.19 ms against 15.64 ms a token), and lose on the other kinds. +- **A short first prompt.** A 64-token prompt takes 351 ms against 251 ms (table A). This is the + first prompt of the app's process, which includes the first launch of each kernel. + `llama-completion` runs a warm-up first. The run has no warm 64-token prompt of the app. +- Against `ngram-mod`, `qwen-vx --draft` is slower on 2 of 12 held-out prompts (down to 0.61×). + +## Setup + +What both sides share: + +| | | +| --- | --- | +| Machine | MacBook Air Mac16,12, Apple M4 (10-core CPU with 4 performance and 6 efficiency cores, 10-core GPU, Metal 4), 32 GB, no fan, on AC power | +| OS and GPU driver | macOS 27.0.1 (26A434). The GPU driver comes with the OS | +| Model | Qwen3.6-35B-A3B: 40 layers (30 Gated DeltaNet, 10 attention), 256 experts, 8 for each token (`weights.txt`) | +| Q4_0 matrices (4-bit codes, an f16 scale for each 32 weights) | attention q/k/v/gate/out, DeltaNet in and out, experts gate/up/down, shared expert gate/up/down. The bits are the same in both files | +| f32 tensors | norms, DeltaNet conv, A and dt bias | +| KV cache | f16 | +| DeltaNet state | f32 | +| Decoding | greedy (temperature 0), batch 1, end-of-text ignored, thinking off (`\n\n\n\n` in the prompt) | +| Prompts | the same chat text. The llama.cpp files have one more final newline, which `-f` drops. `make_prompts.py` counted the tokens with the `tokenizer.json` of the model (`prompts/tokens.csv`). llama.cpp read the same number of tokens in every run | +| Generated tokens | 256 (table A), 512 (tables T and C) | +| Order | 3 rounds, the order of the programs reversed in round 2 (table T: one run, the order reversed for each second prompt) | +| Idle check | before each run, `run.sh` waits until no process uses more than 20% of a CPU and the GPU shows at most 5%, then waits 30 s. It does not count the processes named claude, Terminal, WindowServer and kernel_task | + +What differs: + +| | qwen-vx | llama.cpp | +| --- | --- | --- | +| Program | `vxc -O2 src/main.vx`, vxc 0.0.5 (5b92da4f), the release | `llama-completion`, `llama-speculative-simple`, `llama-bench`, b1b770d, Release (`llama.cpp-build.txt`), with a 3-line patch to one clock of `llama-speculative-simple` (below) | +| Weight file | `Qwen3.6-35B-A3B-q4-q6.vxw`, 20,392,312,832 bytes, made by `scripts/convert.py` | `Qwen3.6-35B-A3B-Q4_0.gguf`, 19,715,053,888 bytes, made by `llama-quantize` from the BF16 GGUF of ggml-org | +| Token embedding | bf16 | Q4_0 | +| Output matrix | 6-bit codes, an f16 scale for each 32 weights (6.5 bits a weight) | Q6_K (6.5625 bits a weight) | +| Router and shared-expert gate | bf16 | f32 | +| Weight bytes read for each token | 1.819 GB | 1.865 GB | +| Compile | the app compiles before each run, out of the clock. A run of the app at 64 prompt tokens takes 105 to 108 s in `log.txt`, against 8 to 17 s for `llama-completion`. Most of this is the compile | none | +| Settings | `--host default` (the Mac that compiles the app), `--machine fleet/m4-uma.vx`. No "auto" setting | flash attention: on, which `run.sh` chose in place of the default "auto" (26.37 ms against 27.67 ms a token with it off, medians at 2,048 tokens). CPU threads: 4 (the default). ngram-mod: `n_match` 24, `n_min` 48, `n_max` 64 (the defaults). ngram-cache: 8 tokens, no cache files | +| Batch sizes of the prompt | chunks of up to 2,048 tokens (`CHUNK` of `src/prefill.vx`) | `-b 2048 -ub 512` (the defaults). `-b 4096` for `llama-speculative-simple`, except on the first 8 tuning prompts (`-b 2048`) | + +## The same work: bytes for each generated token + +A generated token reads one row of the embedding, the matrices of its 8 experts, all other weights, +the KV cache of the 10 attention layers (20,480 bytes for each earlier token), and the DeltaNet +and conv state of the 30 DeltaNet layers. The state is 30 × (32 × 128 × 128 + 3 × 8,192) f32 +values, read and written: 131.7 MB. The floor is the time to read these bytes at 120 GB/s, the +memory speed that Apple gives for the M4. The table counts the KV cache of the prompt only. Over 256 +generated tokens, the cache grows by 2.6 MB on average, which changes no number of the table by +more than 0.003 GB. + +| Prompt tokens | qwen-vx GB | floor ms | measured ms | GB/s | llama.cpp GB | floor ms | measured ms | GB/s | +| ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| 64 | 1.952 | 16.3 | 22.17 | 88 | 1.998 | 16.7 | 25.81 | 77 | +| 512 | 1.961 | 16.3 | 22.33 | 88 | 2.007 | 16.7 | 25.83 | 78 | +| 2,048 | 1.993 | 16.6 | 22.82 | 87 | 2.039 | 17.0 | 26.40 | 77 | +| 8,192 | 2.118 | 17.7 | 24.32 | 87 | 2.164 | 18.0 | 27.94 | 77 | +| 16,384 | 2.286 | 19.1 | 26.55 | 86 | 2.332 | 19.4 | 32.05 | 73 | +| 32,768 | 2.622 | 21.8 | 43.55 | 60 | 2.668 | 22.2 | 48.97 | 54 | + +The weight bytes come from `bytes_per_token.py` (output in `weights.txt`). The llama.cpp file reads +46 MB more for each token, 42 MB of it for the f32 router (2,048 × 256 × 40 × 2 more bytes). At 120 +GB/s, this is 0.4 ms, a tenth of the gap of 3.6 ms at 64 tokens. + +## The same quality + +The two files store three kinds of tensor in other formats. Two of these kinds have other values. +The outputs of the checks are in `weights.txt`. + +- **The same bits.** `compare_bits.py` checked the 320 Q4_0 matrices of the 40 layers: experts + gate, up and down, shared expert gate, up and down, and the matrices of attention or DeltaNet. + Each holds the codes and scales of the GGUF file. llama.cpp splits the joined input matrices + (attention q, k and v. DeltaNet qkv, gate, beta and alpha). Their rows are the same rows in + another order. The DeltaNet output matrix has the same value heads in another order. A run with + one code or scale changed in 8 matrices reported exactly these 8. +- **The router and the shared-expert gate** have the same values: the GGUF stores the bf16 values + as f32. +- **The token embedding and the output matrix differ** (bf16 against Q4_0, 6-bit codes against + Q6_K). One program, `scripts/reference.py` (NumPy, f32), measured both sets of weights. The + llama.cpp set is the app's file with these two tensors taken from the GGUF and widened to f32. + The texts are the first 512 tokens of three files: `docs/benchmarking_policy.md` of Vx at + 643f63b5b, and two files of qwen-vx at 3d56b14 (`perplexity.py`): + +| Text | Perplexity, qwen-vx weights | Perplexity, llama.cpp weights | KL divergence (llama.cpp from qwen-vx) | Same most likely token | +| --- | ---: | ---: | ---: | ---: | +| `docs/benchmarking_policy.md` (English) | 11.935 | 12.131 | 0.0123 | 94.7% | +| `src/speculate.vx` (Vx) | 7.357 | 7.356 | 0.0051 | 96.1% | +| `scripts/qwen_weights.py` (Python) | 7.124 | 7.157 | 0.0070 | 96.5% | + +The app's weights give a lower perplexity on two texts, and a perplexity higher by 0.001 on +`src/speculate.vx`. The greedy texts of the two programs are the same on 3 of the 12 held-out +prompts (edit1, edit2, write1). On the others they differ after 0 to 1,807 characters (`summary.md`). +The weights pick another most likely token at 3.5% to 5.3% of the positions above, and the two +programs also differ in their kernels. + +## Results + +The full tables are in `summary.md`, and each run is a row of `runs.csv`. + +### Table A: generated tokens after a prompt + +256 generated tokens after a prompt of 64 to 32,768 tokens, 3 runs. ms for each generated token: +the median, and the fastest and slowest run. The prompt time is that of the first prompt of a +process. + +| Prompt tokens | qwen-vx ms | llama.cpp ms | qwen-vx tok/s | llama.cpp tok/s | llama.cpp ms / qwen-vx ms | qwen-vx prompt ms | llama.cpp prompt ms | +| ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| 64 | 22.17 (22.14-22.17) | 25.81 (25.63-26.19) | 45.1 | 38.7 | 1.164 | 351 (338-366) | 251 (251-252) | +| 512 | 22.33 (22.29-22.36) | 25.83 (25.81-25.85) | 44.8 | 38.7 | 1.157 | 1180 (1174-1203) | 1217 (1216-1217) | +| 2,048 | 22.82 (22.79-22.84) | 26.40 (26.36-26.53) | 43.8 | 37.9 | 1.157 | 4160 (4157-4168) | 5050 (5044-5056) | +| 8,192 | 24.32 (24.30-24.33) | 27.94 (27.86-27.98) | 41.1 | 35.8 | 1.149 | 18850 (18830-18928) | 22577 (22550-22622) | +| 16,384 | 26.55 (26.54-26.65) | 32.05 (32.02-32.16) | 37.7 | 31.2 | 1.207 | 45572 (45432-45955) | 53550 (53046-53562) | +| 32,768 | 43.55 (43.39-47.50) | 48.97 (48.38-55.01) | 23.0 | 20.4 | 1.124 | 129143 (128628-134961) | 138361 (138249-149488) | + +`llama-bench` with the same file, the mean of 5 repetitions as it prints them: tg128 39.09, 38.25, +35.77, 27.83 and 19.68 tokens a second at depth 0, 2,048, 8,192, 16,384 and 32,768. + +### Table P: the prompt + +Prompt tokens a second: the median, and the slowest and fastest run. qwen-vx ran the prompt 3 +times in each of 3 processes. "First run" has the 3 first runs, which include the first launch of +each kernel. "Later runs" has the other 6. `llama-completion` ran the prompt once in each of 3 +processes, after its warm-up. `llama-bench` gives the mean and the standard deviation of 5 +repetitions. + +| Prompt tokens | qwen-vx first run | qwen-vx later runs | llama-completion | llama-bench | +| ---: | ---: | ---: | ---: | ---: | +| 512 | 433 (433-436) | 453 (450-454) | 420 (419-421) | 426.29 ± 3.15 | +| 2,048 | 492 (491-493) | 492 (490-494) | 404 (396-406) | 404.80 ± 3.25 | +| 8,192 | 433 (429-433) | 400 (394-411) | 358 (355-361) | 343.12 ± 5.44 | + +At 8,192 tokens, the later runs of the app are slower than its first run. This run does not show +why. The slowest `llama-completion` run at 2,048 tokens (396) started while `clang++` used a whole +CPU (`log.txt`, P.llama.ctx2048.r3). + +### Table C: the 12 held-out prompts + +512 generated tokens, 3 rounds. ms for each generated token: the geometric mean over the prompts of +each kind, and the fastest and slowest run. + +| Kind | Prompt tokens | qwen-vx | qwen-vx --draft 7 | llama-completion | ngram-cache | ngram-mod | draft-mtp (3) | +| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | +| edit | 1286, 1605, 1668 | 22.60 (22.49-22.71) | 13.19 (11.45-15.91) | 26.30 (26.11-26.68) | 14.13 (11.98-18.33) | 11.50 (6.88-20.41) | 15.64 (15.15-16.15) | +| complete | 1044, 1086, 1288 | 22.49 (22.41-22.60) | 21.89 (20.27-22.81) | 26.22 (26.10-26.50) | 27.31 (20.96-31.67) | 27.63 (26.33-30.30) | 17.30 (16.22-18.15) | +| write | 35, 44, 52 | 22.26 (22.21-22.35) | 21.79 (20.74-22.44) | 25.79 (25.66-25.94) | 28.91 (26.37-32.53) | 26.35 (25.98-27.36) | 15.92 (14.90-16.48) | +| explain | 1257, 1330, 1503 | 22.56 (22.51-22.69) | 22.31 (21.48-22.86) | 26.22 (26.15-26.29) | 30.77 (27.97-32.53) | 26.88 (26.44-27.73) | 19.74 (18.14-20.77) | +| all 12 | | 22.48 (22.21-22.71) | 19.36 (11.45-22.86) | 26.13 (25.66-26.68) | 24.20 (11.98-32.53) | 21.78 (6.88-30.30) | 17.08 (14.90-20.77) | + +The ratios over the 12 prompts, from the mean of the 3 runs of each prompt. A ratio above 1 means +that the first program is faster. + +| Programs | Geometric mean | Faster on | Smallest | Largest | +| --- | ---: | ---: | ---: | ---: | +| qwen-vx against llama-completion | 1.162 | 12 of 12 | 1.16 | 1.17 | +| qwen-vx --draft against qwen-vx | 1.161 | 7 of 12 | 0.99 | 1.96 | +| qwen-vx --draft against llama-completion | 1.350 | 12 of 12 | 1.15 | 2.29 | +| qwen-vx --draft against ngram-cache | 1.250 | 11 of 12 | 0.98 | 1.45 | +| qwen-vx --draft against ngram-mod | 1.125 | 10 of 12 | 0.61 | 1.49 | +| qwen-vx --draft against draft-mtp | 0.882 | 3 of 12 | 0.73 | 1.35 | +| ngram-cache against llama-completion | 1.080 | 4 of 12 | 0.79 | 2.12 | +| ngram-mod against llama-completion | 1.200 | 3 of 12 | 0.87 | 3.77 | +| draft-mtp against llama-completion | 1.530 | 12 of 12 | 1.28 | 1.70 | + +30 runs of table C, all in rounds 2 and 3, started while the GPU showed 6% to 15%. The busiest +other process at these starts was WindowServer or launchd. Each of these runs is within -0.8% to ++2.3% of the mean of the other 2 rounds of its case. The summary keeps them. + +## Speculative decoding + +| | qwen-vx --draft | ngram-cache | ngram-mod | draft-mtp | +| --- | --- | --- | --- | --- | +| Source of the drafts | the context: the longest earlier match of its end | the context: short n-grams with counts | the context: hashed n-grams | extra heads: the MTP heads of the model (1.06 GB GGUF) | +| Largest draft | 7 tokens (`--draft 7`, chosen in table T) | 8 tokens (fixed in llama.cpp) | 64 tokens (`n_max`, the default) | 3 tokens (`--spec-draft-n-max 3`, chosen in table T) | +| Accepted / drafted, table C round 1 | 1520 / 1785 (85%) | 3154 / 3154 as printed (see below) | 1274 / 1274 as printed (see below) | 4394 / 5360 (82%) | +| Accepted tokens for each check | 4.79 (edit 6.49, complete 2.95, write 2.53, explain 2.51) | not printed | not printed | not printed | +| Same text as without drafts | 72 of 72 runs in T, 36 of 36 in C | 8 of 12 in T, 27 of 36 in C | 8 of 12 in T, 24 of 36 in C | 42 of 60 in T, 21 of 36 in C | + +Temperature 0 everywhere. + +**qwen-vx `--draft`** gives each position of a check the bits of a plain step, so its text is the +text of plain qwen-vx in every run. It drafts nothing below a 6-token match, 1 token for a match of +6 or 7, 4 for 8 to 11, and 7 from 12. After 2 checks that accept nothing, it drafts again only after a +longer match. `--draft N` caps this rule, so `--draft 9`, `11` and `15` make the drafts of +`--draft 7`: table T has the same draft counts for them on every prompt. + +**llama.cpp with drafts writes other text in some runs.** 36 of the 108 runs with drafts in table +C, and 26 of the 84 in table T, leave the text of `llama-completion`. None has an error line, and +the text stays coherent (for example ", Dict" against "\n\nSOURCE"). On 3 tuning prompts, +ngram-mod, ngram-cache and every MTP length leave the text at the same character. This points to a +near tie that the shape of the batches changes. The summary keeps these runs. `summary.md` lists +each one, with the number of equal characters at the start of the two texts. + +**The acceptance of the n-gram drafts of llama.cpp is not comparable.** This model has a recurrent +state. For ngram-cache and ngram-mod, `llama-speculative-simple` cannot drop rejected tokens from +its memory. On a partial accept, it loads a checkpoint and checks the accepted tokens again as a +new draft. Its counts leave out the first check, so they show 100%. The time includes both checks. +draft-mtp keeps a copy of the recurrent state for each draft position, so it uses no checkpoints +(none of its 96 logs has the line "speculative decoding will use checkpoints", and all 96 logs of +ngram-cache and ngram-mod have it). Its counts are comparable. + +**The draft programs of llama.cpp stop after the check that passes `-n 512`.** They decoded 513 to +577 tokens. Their speed is the decode time divided by the decoded tokens. + +### Table T: the draft lengths + +The 12 tuning prompts (`prompts/twelve/`) are other prompts of the same 4 kinds. One run each, 512 +generated tokens. ms for each generated token, the geometric mean over the 12 prompts: + +| Program | Draft lengths and ms | +| --- | --- | +| qwen-vx --draft | 3: 19.39, 5: 19.04, **7: 18.90**, 9: 18.92, 11: 18.91, 15: 18.96 | +| draft-mtp | 1: 21.62, 2: 19.11, **3: 18.15**, 4: 18.21, 6: 19.22 | +| no drafts, ngram-cache, ngram-mod | qwen-vx 22.59, llama-completion 26.16, ngram-cache 24.38, ngram-mod 19.76 | + +For draft-mtp, 3 and 4 are 0.3% apart. The 4 settings of the app that make the same drafts (7, 9, +11, 15) spread over 0.3% too. So table T does not separate 3 from 4. The choice is 3 also on the 7 +prompts where every MTP length kept the text of llama-completion (18.20 ms, against 18.40 for 4). + +## Where the gain comes from + +This run measures the app as a whole. It does not measure each change on its own. Two side +measurements: + +- Flash attention gives llama.cpp 1.30 ms a token at 2,048 tokens (26.37 against 27.67 ms, the + medians of 3 runs each, logs `fa-*`). +- The compile before each run of the app: 3 runs that compiled first gave 22.14, 22.19 and 22.31 + ms a token, and 3 runs of one kept executable gave 22.09, 22.15 and 22.07 ms (512 prompt + tokens, 256 steps, `extra.tar.xz`). The means differ by 0.5%, and the ranges touch. + +## Limits + +- One machine, a fanless MacBook Air. A fanless Mac can slow its clock under a long load. The + programs run interleaved, in a reversed order in round 2, so that a slow period does not fall on + one program only. +- Batch 1 and greedy decoding only. No serving numbers (section 6 of the policy). +- Decode to 32,768 prompt tokens. Prompt speed to 8,192 tokens in table P. Table A gives the time of + the first prompt of a process to 32,768 tokens. +- Table T has one run of each case. +- The run does not split the gain of the app into its changes. +- `llama-lookup` is not in the benchmark. In the short test of `run.sh` (`extra.tar.xz`, `lookup/`), + its text differs from that of `llama-completion`, and its log has errors from `llama_decode`: + it cannot remove rejected tokens from a recurrent state. `llama-speculative-simple --spec-type + ngram-cache` uses the same n-gram cache with checkpoints. +- `llama-speculative-simple` has a 3-line patch (`llama-timing.patch`). Without it, the program + stops the clock of the prompt before the GPU ends the prompt, and counts the rest of the prompt + in the time of the generated tokens (on edit1, 0.77 s of 1,799 prompt tokens, `extra.tar.xz`, + `speculative-clock/`). The patch waits for the GPU before it stops the clock. The other programs + have no patch. +- The two weight files differ in the token embedding and the output matrix. The perplexity check + above compares the two files with one program. +- ngram-cache and ngram-mod keep the settings of llama.cpp. ngram-cache always drafts 8 tokens. +- llama.cpp does not print its number of checks, so the accepted tokens for each check are only + for the app. +- The prompts are code tasks in 4 kinds. Other text can give other draft gains. +- The run started 3 times (below). The first 8 tuning prompts of `llama-speculative-simple` ran with + `-b 2048`, the others with `-b 4096`. The batch size sets only how the prompt goes to the model. +- The restart wrote over the logs of the first 4 runs of edit3 in table T (below). + +## How the run went + +1. 16:12 on 2026-11-20, all stages. At 22:11, `llama-speculative-simple` refused the tuning prompt + edit3 (2,251 tokens): "the prompt exceeds the batch size (2251 tokens, batch 2048)". I stopped the + run. The stages fa, bench, A and P and the first 8 tuning prompts come from this start. +2. 22:13: `STAGES=T PROMPTS="edit3 complete3 write3 explain3" FA=on`, with `-b 4096` for + `llama-speculative-simple`. This change was not committed yet, so `env.txt` names ef7c58a. The + `run.sh` that ran differs from ef7c58a only in this line, which commit 69adc71 committed. All + runs of edit3 ran again, so the programs of that prompt ran together. `parse.py --choose` then + found no MTP length with the text of llama-completion on all 12 prompts, and stopped. +3. 23:59: `STAGES=C FA=on DRAFT=7 MTP_N=3`, the draft lengths of table T with all runs counted. It + ended at 05:31 on 2026-11-21. After this start, `parse.py` changed to keep the runs of llama.cpp + with other text (commit 806bfe0). Stage C of `run.sh` does not call `parse.py`. + +`log.txt` keeps the 4 lines of the first edit3 runs: vx and completion (exit code 0), ngram and cache +(exit code 1). The restart wrote over their logs, so `runs.csv` has no rows for them, and the error +message above comes from the log before the restart. `parse.py` uses the last line of each run. + +## Commands + +llama.cpp: + + git clone https://github.com/ggml-org/llama.cpp && cd llama.cpp && git checkout b1b770d + git apply /path/to/qwen-vx/docs/benchmarks/2026-11-20-qwen36-m4/llama-timing.patch + cmake -B build -DCMAKE_BUILD_TYPE=Release -DLLAMA_CURL=OFF -DLLAMA_BUILD_MTMD=OFF \ + -DLLAMA_BUILD_UI=OFF -DLLAMA_BUILD_TESTS=OFF + cmake --build build -j 8 + +The model files: + + hf download Qwen/Qwen3.6-35B-A3B --local-dir ~/models/Qwen3.6-35B-A3B + python3 scripts/convert.py --q4 --q6-lm-head ~/models/Qwen3.6-35B-A3B Qwen3.6-35B-A3B-q4-q6.vxw + python3 scripts/convert_tokenizer.py ~/models/Qwen3.6-35B-A3B Qwen3.6-35B-A3B.vxt + hf download ggml-org/Qwen3.6-35B-A3B-GGUF Qwen3.6-35B-A3B-BF16.gguf mtp-Qwen3.6-35B-A3B-Q4_0.gguf + llama-quantize Qwen3.6-35B-A3B-BF16.gguf Qwen3.6-35B-A3B-Q4_0.gguf Q4_0 + +The run, under `caffeinate -dims`, on an idle Mac, from the root of this repository: + + export OUT=docs/benchmarks/2026-11-20-qwen36-m4 VXC=~/.vx/current/bin/vxc FLEET=~/.vx/current/fleet \ + VXW=Qwen3.6-35B-A3B-q4-q6.vxw VXT=Qwen3.6-35B-A3B.vxt GGUF=Qwen3.6-35B-A3B-Q4_0.gguf \ + MTP=mtp-Qwen3.6-35B-A3B-Q4_0.gguf LB=llama.cpp/build/bin + caffeinate -dims $OUT/run.sh + python3 $OUT/parse.py $OUT + +This run used the first command, then the two restarts above: + + STAGES=T PROMPTS="edit3 complete3 write3 explain3" FA=on caffeinate -dims $OUT/run.sh + STAGES=C FA=on DRAFT=7 MTP_N=3 caffeinate -dims $OUT/run.sh + +`run.sh` prints each command line in the log of its run. `make_prompts.py` wrote `prompts/`. + +The checks of the weight files, on the CPU, from the root of this repository, with a checkout of +Vx at 643f63b5b in `$VX`: + + python3 $OUT/bytes_per_token.py $VXW $GGUF scripts llama.cpp/gguf-py + python3 $OUT/compare_bits.py $VXW $GGUF scripts llama.cpp/gguf-py + python3 $OUT/perplexity.py $VXW $GGUF scripts llama.cpp/gguf-py ~/models/Qwen3.6-35B-A3B \ + $VX/docs/benchmarking_policy.md src/speculate.vx scripts/qwen_weights.py --max-tokens 512 + +## Files + +- `run.sh`, `parse.py`, `make_prompts.py`, `prompts/`: the script, the parser and the inputs. +- `env.txt`: the machine, OS, versions, files and settings, written at each start of `run.sh`. +- `log.txt`: one line for each run, with its start, end, exit code, the busiest other process and + the GPU use at the start. +- `logs.tar.xz`: the output of each run (`tar -xJf logs.tar.xz` gives `logs/`, 33 MB). + `parse.py` gives the same `summary.md` and `runs.csv` from it. +- `runs.csv`, `summary.md`: written by `parse.py`. +- `llama-timing.patch`, `llama.cpp.diff`, `llama.cpp-build.txt`: the patch, the diff of the + llama.cpp source that ran, and its build settings. +- `bytes_per_token.py`, `compare_bits.py`, `perplexity.py`, `weights.txt`: the checks of the + weight files, and their output. +- `extra.tar.xz`: the side measurements (`extra/INDEX.txt` lists them): the short test of + `llama-lookup`, the runs of `llama-speculative-simple` with and without the patch, the compile + runs of the app, and the test of `-b 4096` on edit3. diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/bytes_per_token.py b/docs/benchmarks/2026-11-20-qwen36-m4/bytes_per_token.py new file mode 100755 index 0000000..3117823 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/bytes_per_token.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +"""Bytes of weights that one generated token reads, in the app's weight file and in a GGUF file. + + python3 bytes_per_token.py APP.vxw MODEL.gguf QWEN_VX/scripts LLAMA/gguf-py + +A token reads one row of the token embedding, the matrices of the 8 experts it routes to (of 256), +and every other tensor whole. + +Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +See LICENSE for license information. +SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +""" +import re +import sys +from collections import defaultdict + +vxw, gguf_path, qwen_scripts, gguf_py = sys.argv[1:5] +sys.path.insert(0, qwen_scripts) +sys.path.insert(0, gguf_py) +import qwen_weights # noqa: E402 +from gguf import GGUFReader # noqa: E402 + +TOP, EXPERTS = 8, 256 + + +def share(name, vocab): + if re.search(r"(^|\.)(embed|token_embd)", name): + return 1 / vocab + if re.search(r"(experts|_exps)", name): + return TOP / EXPERTS + return 1.0 + + +config, tensors = qwen_weights.read_weight_file(vxw) +vocab = config["vocab_size"] +print("config:", {k: config[k] for k in sorted(config) if not isinstance(config[k], (list, dict))}) +sums = defaultdict(float) +for name, (_, array) in tensors.items(): + kind = re.sub(r"^layers\.\d+\.", "", name) + sums[kind] += array.nbytes * share(name, vocab) +print(f"app: {sum(sums.values()) / 1e9:.3f} GB per token, file {sum(a.nbytes for _, a in tensors.values()) / 1e9:.3f} GB") +for k, v in sorted(sums.items(), key=lambda kv: -kv[1])[:14]: + print(f" {k}: {v / 1e6:.1f} MB") + +sums = defaultdict(float) +ts = GGUFReader(gguf_path).tensors +for t in ts: + kind = re.sub(r"^blk\.\d+\.", "", t.name) + sums[kind] += t.n_bytes * share(t.name, vocab) +print(f"gguf: {sum(sums.values()) / 1e9:.3f} GB per token, file {sum(t.n_bytes for t in ts) / 1e9:.3f} GB") +for k, v in sorted(sums.items(), key=lambda kv: -kv[1])[:14]: + print(f" {k}: {v / 1e6:.1f} MB") diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/compare_bits.py b/docs/benchmarks/2026-11-20-qwen36-m4/compare_bits.py new file mode 100755 index 0000000..ebe8a29 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/compare_bits.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Check that every Q4_0 matrix of the app's weight file holds the bits of the GGUF file, in all layers. + + python3 compare_bits.py APP.vxw MODEL.gguf QWEN_VX/scripts LLAMA/gguf-py + +llama.cpp splits the joined input matrices, and orders the value heads of the DeltaNet output +matrix in another way. The check allows these orders and nothing else. + +Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +See LICENSE for license information. +SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +""" +import sys + +import numpy as np + +vxw, gguf_path, qwen_scripts, gguf_py = sys.argv[1:5] +sys.path.insert(0, qwen_scripts) +sys.path.insert(0, gguf_py) +import qwen_weights # noqa: E402 +from gguf import GGUFReader # noqa: E402 + +config, ours = qwen_weights.read_weight_file(vxw) +theirs = {t.name: t for t in GGUFReader(gguf_path).tensors} +hidden, inter = config["hidden_size"], config["moe_intermediate_size"] + + +def our_rows(name): + """Codes [rows, blocks, 32] and scale bits [rows, blocks] of one of our Q4_0 matrices.""" + codes = qwen_weights.unpack_u4(np.asarray(ours[name][1])) + scales = np.asarray(ours[name + ".scale"][1]).view(np.uint16) + return codes.reshape(len(codes), -1, 32), scales.reshape(len(codes), -1) + + +def their_rows(name, cols): + t = theirs[name] + assert t.tensor_type.name == "Q4_0", f"{name} is {t.tensor_type.name}" + raw = np.asarray(t.data).reshape(-1, cols // 32, 18) + scales = raw[..., :2].copy().view(np.uint16)[..., 0] + qs = raw[..., 2:] + return np.concatenate([qs & 15, qs >> 4], axis=-1), scales + + +def same(a, b): + return a[0].shape == b[0].shape and np.array_equal(a[0], b[0]) and np.array_equal(a[1], b[1]) + + +def same_rows(a, parts): + """Whether the rows of the parts, together, are the rows of a in some order.""" + def keys(x): + flat = np.concatenate([x[0].reshape(len(x[0]), -1).astype(np.uint16), x[1]], axis=1) + return {row.tobytes() for row in flat}, len(flat) + mine, n = keys(a) + found = set() + total = 0 + for p in parts: + k, m = keys(p) + found |= k + total += m + return n == total == len(mine) and found == mine + + +checked, failed = 0, [] +for layer in range(config["num_layers"]): + L, B = f"layers.{layer}.", f"blk.{layer}." + results = {} + codes, scales = our_rows(L + "experts_gate_up") + experts = len(codes) // (2 * inter) + codes = codes.reshape(experts, 2, inter, -1, 32) + scales = scales.reshape(experts, 2, inter, -1) + for i, part in enumerate(("gate", "up")): + c, s = their_rows(f"{B}ffn_{part}_exps.weight", hidden) + results[f"experts {part}"] = same((codes[:, i].reshape(c.shape), scales[:, i].reshape(s.shape)), (c, s)) + results["experts down"] = same(our_rows(L + "experts_down"), their_rows(B + "ffn_down_exps.weight", inter)) + sh = our_rows(L + "shared_gate_up") + half = len(sh[0]) // 2 + results["shared gate"] = same((sh[0][:half], sh[1][:half]), their_rows(B + "ffn_gate_shexp.weight", hidden)) + results["shared up"] = same((sh[0][half:], sh[1][half:]), their_rows(B + "ffn_up_shexp.weight", hidden)) + down = our_rows(L + "shared_down") + results["shared down"] = same(down, their_rows(B + "ffn_down_shexp.weight", down[0].shape[1] * 32)) + if qwen_weights.has_full_attention(config, layer): + results["qkv"] = same_rows(our_rows(L + "qkv"), [their_rows(f"{B}attn_{p}.weight", hidden) for p in "qkv"]) + out = our_rows(L + "attn_out") + results["attn out"] = same(out, their_rows(B + "attn_output.weight", out[0].shape[1] * 32)) + else: + parts = [their_rows(B + n + ".weight", hidden) for n in ("attn_qkv", "attn_gate", "ssm_beta", "ssm_alpha")] + results["linear in"] = same_rows(our_rows(L + "linear_in"), parts) + c, s = our_rows(L + "linear_out") + tc, ts = their_rows(B + "ssm_out.weight", c.shape[1] * 32) + heads = 32 + per = c.shape[1] // heads + # Our value head 2k is their head k, and our head 2k + 1 is their head 16 + k. + order = [h // 2 if h % 2 == 0 else heads // 2 + h // 2 for h in range(heads)] + tc = tc.reshape(len(tc), heads, per, 32)[:, order].reshape(c.shape) + ts = ts.reshape(len(ts), heads, per)[:, order].reshape(s.shape) + results["linear out"] = same((c, s), (tc, ts)) + for k, v in results.items(): + checked += 1 + if not v: + failed.append(f"layer {layer} {k}") +print(f"{checked} matrices checked in {config['num_layers']} layers, {len(failed)} differ: {failed}") diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/env.txt b/docs/benchmarks/2026-11-20-qwen36-m4/env.txt new file mode 100644 index 0000000..e70046c --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/env.txt @@ -0,0 +1,61 @@ +date: Fri Nov 20 16:12:05 PST 2026, stages: fa bench A P T C +machine: Mac16,12, Apple M4, 32 GB + Chipset Model: Apple M4 + Total Number of Cores: 10 + Metal Support: Metal 4 +macOS: 27.0.1 (26A434) +power: Now drawing from 'AC Power' +vxc: vxc 0.0.5 (5b92da4f) +qwen-vx: ef7c58aaba5bd095f0399a2ec2e579354d4026b3 benchmark: date the folder of the Qwen3.6 benchmark, changed files: 0 +llama.cpp: version: 1.0.0-dev (build 1, commit b1b770d) built with AppleClang 21.0.0.21000334 for Darwin arm64 +llama.cpp source: b1b770d90d94cad9e9ea5b993bdbc383a522fb28, changes: 1 file changed, 3 insertions(+) +GGUF: /Users/adityak/models/gguf/qwen36/Qwen3.6-35B-A3B-Q4_0.gguf 19715053888 bytes +MTP GGUF: /Users/adityak/models/gguf/qwen36-draft/mtp-Qwen3.6-35B-A3B-Q4_0.gguf 1060038720 bytes +app weights: /Users/adityak/models/Qwen3.6-35B-A3B-q4-q6.vxw 20392312832 bytes +app tokenizer: /Users/adityak/models/Qwen3.6-35B-A3B.vxt 6853664 bytes +rounds: 3, cool: 30 s, prompt runs: 3 +contexts: 64 512 2048 8192 16384 32768, prompt contexts: 512 2048 8192, generated tokens: 256 and 512 +prompts: edit1 complete1 write1 explain1 edit2 complete2 write2 explain2 edit3 complete3 write3 explain3 +draft lengths tried: app 3 5 7 9 11 15, MTP 1 2 3 4 6 +flash attention: on 26.37 ms, off 27.67 ms (medians at 2,048 tokens); chosen: on +date: Fri Nov 20 22:13:36 PST 2026, stages: T +machine: Mac16,12, Apple M4, 32 GB + Chipset Model: Apple M4 + Total Number of Cores: 10 + Metal Support: Metal 4 +macOS: 27.0.1 (26A434) +power: Now drawing from 'AC Power' +vxc: vxc 0.0.5 (5b92da4f) +qwen-vx: ef7c58aaba5bd095f0399a2ec2e579354d4026b3 benchmark: date the folder of the Qwen3.6 benchmark, changed files: 0 +llama.cpp: version: 1.0.0-dev (build 1, commit b1b770d) built with AppleClang 21.0.0.21000334 for Darwin arm64 +llama.cpp source: b1b770d90d94cad9e9ea5b993bdbc383a522fb28, changes: 1 file changed, 3 insertions(+) +GGUF: /Users/adityak/models/gguf/qwen36/Qwen3.6-35B-A3B-Q4_0.gguf 19715053888 bytes +MTP GGUF: /Users/adityak/models/gguf/qwen36-draft/mtp-Qwen3.6-35B-A3B-Q4_0.gguf 1060038720 bytes +app weights: /Users/adityak/models/Qwen3.6-35B-A3B-q4-q6.vxw 20392312832 bytes +app tokenizer: /Users/adityak/models/Qwen3.6-35B-A3B.vxt 6853664 bytes +rounds: 3, cool: 30 s, prompt runs: 3 +contexts: 64 512 2048 8192 16384 32768, prompt contexts: 512 2048 8192, generated tokens: 256 and 512 +prompts: edit3 complete3 write3 explain3 +draft lengths tried: app 3 5 7 9 11 15, MTP 1 2 3 4 6 +flash attention: given by FA; chosen: on +date: Fri Nov 20 23:59:05 PST 2026, stages: C +machine: Mac16,12, Apple M4, 32 GB + Chipset Model: Apple M4 + Total Number of Cores: 10 + Metal Support: Metal 4 +macOS: 27.0.1 (26A434) +power: Now drawing from 'AC Power' +vxc: vxc 0.0.5 (5b92da4f) +qwen-vx: ef7c58aaba5bd095f0399a2ec2e579354d4026b3 benchmark: date the folder of the Qwen3.6 benchmark, changed files: 0 +llama.cpp: version: 1.0.0-dev (build 1, commit b1b770d) built with AppleClang 21.0.0.21000334 for Darwin arm64 +llama.cpp source: b1b770d90d94cad9e9ea5b993bdbc383a522fb28, changes: 1 file changed, 3 insertions(+) +GGUF: /Users/adityak/models/gguf/qwen36/Qwen3.6-35B-A3B-Q4_0.gguf 19715053888 bytes +MTP GGUF: /Users/adityak/models/gguf/qwen36-draft/mtp-Qwen3.6-35B-A3B-Q4_0.gguf 1060038720 bytes +app weights: /Users/adityak/models/Qwen3.6-35B-A3B-q4-q6.vxw 20392312832 bytes +app tokenizer: /Users/adityak/models/Qwen3.6-35B-A3B.vxt 6853664 bytes +rounds: 3, cool: 30 s, prompt runs: 3 +contexts: 64 512 2048 8192 16384 32768, prompt contexts: 512 2048 8192, generated tokens: 256 and 512 +prompts: edit1 complete1 write1 explain1 edit2 complete2 write2 explain2 edit3 complete3 write3 explain3 +draft lengths tried: app 3 5 7 9 11 15, MTP 1 2 3 4 6 +flash attention: given by FA; chosen: on +draft lengths given: DRAFT=7 MTP_N=3 diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/extra.tar.xz b/docs/benchmarks/2026-11-20-qwen36-m4/extra.tar.xz new file mode 100644 index 0000000..3c4d029 Binary files /dev/null and b/docs/benchmarks/2026-11-20-qwen36-m4/extra.tar.xz differ diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/llama-timing.patch b/docs/benchmarks/2026-11-20-qwen36-m4/llama-timing.patch new file mode 100644 index 0000000..30232c6 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/llama-timing.patch @@ -0,0 +1,14 @@ +diff --git a/examples/speculative-simple/speculative-simple.cpp b/examples/speculative-simple/speculative-simple.cpp +index e4a878b..4ddd972 100644 +--- a/examples/speculative-simple/speculative-simple.cpp ++++ b/examples/speculative-simple/speculative-simple.cpp +@@ -155,6 +155,9 @@ int main(int argc, char ** argv) { + + common_prompt_checkpoint ckpt; + ++ // Wait for the GPU, so that the time of the prompt is not counted in the time of the first tokens. ++ llama_synchronize(ctx_tgt); ++ + const auto t_enc_end = ggml_time_us(); + + const auto t_dec_start = ggml_time_us(); diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/llama.cpp-build.txt b/docs/benchmarks/2026-11-20-qwen36-m4/llama.cpp-build.txt new file mode 100644 index 0000000..3995d6e --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/llama.cpp-build.txt @@ -0,0 +1,13 @@ +The build of llama.cpp that ran, from build/CMakeCache.txt (b1b770d with llama-timing.patch): +CMAKE_BUILD_TYPE:STRING=Release +CMAKE_CXX_COMPILER:FILEPATH=/usr/bin/c++ +CMAKE_C_COMPILER:FILEPATH=/usr/bin/cc +GGML_METAL:BOOL=ON +GGML_METAL_EMBED_LIBRARY:BOOL=ON +GGML_NATIVE:BOOL=ON +LLAMA_BUILD_MTMD:BOOL=OFF +LLAMA_BUILD_TESTS:BOOL=OFF +LLAMA_BUILD_UI:BOOL=OFF +LLAMA_CURL:UNINITIALIZED=OFF + +Build times of the binaries (2026-11-20): llama-bench 12:42, llama-completion 12:43, llama-speculative-simple 15:25 (after the patch). diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/llama.cpp.diff b/docs/benchmarks/2026-11-20-qwen36-m4/llama.cpp.diff new file mode 100644 index 0000000..30232c6 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/llama.cpp.diff @@ -0,0 +1,14 @@ +diff --git a/examples/speculative-simple/speculative-simple.cpp b/examples/speculative-simple/speculative-simple.cpp +index e4a878b..4ddd972 100644 +--- a/examples/speculative-simple/speculative-simple.cpp ++++ b/examples/speculative-simple/speculative-simple.cpp +@@ -155,6 +155,9 @@ int main(int argc, char ** argv) { + + common_prompt_checkpoint ckpt; + ++ // Wait for the GPU, so that the time of the prompt is not counted in the time of the first tokens. ++ llama_synchronize(ctx_tgt); ++ + const auto t_enc_end = ggml_time_us(); + + const auto t_dec_start = ggml_time_us(); diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/log.txt b/docs/benchmarks/2026-11-20-qwen36-m4/log.txt new file mode 100644 index 0000000..d4ad765 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/log.txt @@ -0,0 +1,467 @@ +fa-on.ctx2048.r1 start=2026-11-20T16:12:36 end=2026-11-20T16:12:57 rc=0 busy=[airportd] gpu=1% +fa-off.ctx2048.r1 start=2026-11-20T16:13:37 end=2026-11-20T16:13:51 rc=0 busy=[mediaanalysisd] gpu=1% +fa-off.ctx2048.r2 start=2026-11-20T16:14:31 end=2026-11-20T16:14:44 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +fa-on.ctx2048.r2 start=2026-11-20T16:15:24 end=2026-11-20T16:15:37 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +fa-on.ctx2048.r3 start=2026-11-20T16:16:17 end=2026-11-20T16:16:30 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +fa-off.ctx2048.r3 start=2026-11-20T16:17:10 end=2026-11-20T16:17:24 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +flash attention: on 26.37 ms, off 27.67 ms (medians at 2,048 tokens); chosen: on +llama-bench-pp start=2026-11-20T16:18:04 end=2026-11-20T16:21:05 rc=0 busy=[airportd] gpu=0% +llama-bench-tg start=2026-11-20T16:21:45 end=2026-11-20T16:27:33 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +A.vx.ctx64.r1 start=2026-11-20T16:28:14 end=2026-11-20T16:30:02 rc=0 busy=[Brave] gpu=0% +A.llama.ctx64.r1 start=2026-11-20T16:30:42 end=2026-11-20T16:30:59 rc=0 busy=[bash] gpu=0% +A.vx.ctx512.r1 start=2026-11-20T16:31:39 end=2026-11-20T16:33:23 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +A.llama.ctx512.r1 start=2026-11-20T16:34:03 end=2026-11-20T16:34:21 rc=0 busy=[1.1 awk] gpu=0% +A.vx.ctx2048.r1 start=2026-11-20T16:35:01 end=2026-11-20T16:36:50 rc=0 busy=[loginwindow] gpu=0% +A.llama.ctx2048.r1 start=2026-11-20T16:37:30 end=2026-11-20T16:37:52 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +A.vx.ctx8192.r1 start=2026-11-20T16:38:32 end=2026-11-20T16:40:37 rc=0 busy=[airportd] gpu=0% +A.llama.ctx8192.r1 start=2026-11-20T16:41:17 end=2026-11-20T16:41:56 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +A.vx.ctx16384.r1 start=2026-11-20T16:42:37 end=2026-11-20T16:44:59 rc=0 busy=[bash] gpu=0% +A.llama.ctx16384.r1 start=2026-11-20T16:45:39 end=2026-11-20T16:46:51 rc=0 busy=[contextstored] gpu=0% +A.vx.ctx32768.r1 start=2026-11-20T16:47:31 end=2026-11-20T16:51:31 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +A.llama.ctx32768.r1 start=2026-11-20T16:52:11 end=2026-11-20T16:54:52 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +A.llama.ctx64.r2 start=2026-11-20T16:55:32 end=2026-11-20T16:55:40 rc=0 busy=[syspolicyd] gpu=0% +A.vx.ctx64.r2 start=2026-11-20T16:56:20 end=2026-11-20T16:58:05 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +A.llama.ctx512.r2 start=2026-11-20T16:58:45 end=2026-11-20T16:59:02 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +A.vx.ctx512.r2 start=2026-11-20T16:59:43 end=2026-11-20T17:01:29 rc=0 busy=[airportd] gpu=0% +A.llama.ctx2048.r2 start=2026-11-20T17:02:10 end=2026-11-20T17:02:31 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +A.vx.ctx2048.r2 start=2026-11-20T17:03:11 end=2026-11-20T17:05:00 rc=0 busy=[mediaanalysisd] gpu=0% +A.llama.ctx8192.r2 start=2026-11-20T17:05:40 end=2026-11-20T17:06:19 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +A.vx.ctx8192.r2 start=2026-11-20T17:06:59 end=2026-11-20T17:09:03 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +A.llama.ctx16384.r2 start=2026-11-20T17:09:44 end=2026-11-20T17:10:55 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +A.vx.ctx16384.r2 start=2026-11-20T17:11:45 end=2026-11-20T17:14:26 rc=0 busy=[airportd] gpu=1% +A.llama.ctx32768.r2 start=2026-11-20T17:15:06 end=2026-11-20T17:17:59 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +A.vx.ctx32768.r2 start=2026-11-20T17:18:39 end=2026-11-20T17:22:43 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +A.vx.ctx64.r3 start=2026-11-20T17:23:24 end=2026-11-20T17:25:09 rc=0 busy=[dasd] gpu=0% +A.llama.ctx64.r3 start=2026-11-20T17:25:49 end=2026-11-20T17:26:05 rc=0 busy=[launchd] gpu=0% +A.vx.ctx512.r3 start=2026-11-20T17:26:45 end=2026-11-20T17:28:38 rc=0 busy=[bash] gpu=0% +A.llama.ctx512.r3 start=2026-11-20T17:29:18 end=2026-11-20T17:29:36 rc=0 busy=[launchd] gpu=1% +A.vx.ctx2048.r3 start=2026-11-20T17:30:26 end=2026-11-20T17:32:05 rc=0 busy=[mDNSResponder] gpu=0% +A.llama.ctx2048.r3 start=2026-11-20T17:32:45 end=2026-11-20T17:33:07 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +A.vx.ctx8192.r3 start=2026-11-20T17:33:47 end=2026-11-20T17:35:52 rc=0 busy=[mediaanalysisd] gpu=0% +A.llama.ctx8192.r3 start=2026-11-20T17:36:32 end=2026-11-20T17:37:11 rc=0 busy=[airportd] gpu=0% +A.vx.ctx16384.r3 start=2026-11-20T17:37:52 end=2026-11-20T17:40:32 rc=0 busy=[airportd] gpu=0% +A.llama.ctx16384.r3 start=2026-11-20T17:41:12 end=2026-11-20T17:42:24 rc=0 busy=[mdworker_shared] gpu=0% +A.vx.ctx32768.r3 start=2026-11-20T17:43:04 end=2026-11-20T17:47:11 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=1% +A.llama.ctx32768.r3 start=2026-11-20T17:47:51 end=2026-11-20T17:50:32 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +P.vx.ctx512.r1 start=2026-11-20T17:51:12 end=2026-11-20T17:52:55 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +P.llama.ctx512.r1 start=2026-11-20T17:53:35 end=2026-11-20T17:53:46 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +P.vx.ctx2048.r1 start=2026-11-20T17:54:26 end=2026-11-20T17:56:19 rc=0 busy=[airportd] gpu=1% +P.llama.ctx2048.r1 start=2026-11-20T17:57:00 end=2026-11-20T17:57:14 rc=0 busy=[airportd] gpu=0% +P.vx.ctx8192.r1 start=2026-11-20T17:57:55 end=2026-11-20T18:00:33 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +P.llama.ctx8192.r1 start=2026-11-20T18:01:13 end=2026-11-20T18:01:46 rc=0 busy=[airportd] gpu=0% +P.llama.ctx512.r2 start=2026-11-20T18:02:26 end=2026-11-20T18:02:28 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=1% +P.vx.ctx512.r2 start=2026-11-20T18:03:19 end=2026-11-20T18:05:09 rc=0 busy=[launchd] gpu=0% +P.llama.ctx2048.r2 start=2026-11-20T18:05:49 end=2026-11-20T18:06:04 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +P.vx.ctx2048.r2 start=2026-11-20T18:06:44 end=2026-11-20T18:08:36 rc=0 busy=[airportd] gpu=0% +P.llama.ctx8192.r2 start=2026-11-20T18:09:16 end=2026-11-20T18:09:48 rc=0 busy=[mediaanalysisd] gpu=0% +P.vx.ctx8192.r2 start=2026-11-20T18:10:29 end=2026-11-20T18:13:16 rc=0 busy=[mediaanalysisd] gpu=1% +P.vx.ctx512.r3 start=2026-11-20T18:13:56 end=2026-11-20T18:15:39 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +P.llama.ctx512.r3 start=2026-11-20T18:16:20 end=2026-11-20T18:16:31 rc=0 busy=[clocksyncd] gpu=1% +P.vx.ctx2048.r3 start=2026-11-20T18:17:11 end=2026-11-20T18:19:11 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=1% +P.llama.ctx2048.r3 start=2026-11-20T18:19:51 end=2026-11-20T18:20:08 rc=0 busy=[99.0 clang++] gpu=1% +P.vx.ctx8192.r3 start=2026-11-20T18:29:41 end=2026-11-20T18:32:30 rc=0 busy=[parentalcontrolsd] gpu=1% +P.llama.ctx8192.r3 start=2026-11-20T18:33:10 end=2026-11-20T18:33:43 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=1% +T.edit1.r1.vx start=2026-11-20T18:34:23 end=2026-11-20T18:36:18 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=1% +T.edit1.r1.completion start=2026-11-20T18:37:08 end=2026-11-20T18:37:36 rc=0 busy=[bash] gpu=0% +T.edit1.r1.ngram start=2026-11-20T18:38:16 end=2026-11-20T18:38:28 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=1% +T.edit1.r1.cache start=2026-11-20T18:39:08 end=2026-11-20T18:39:20 rc=0 busy=[mediaanalysisd] gpu=0% +T.edit1.r1.vxdraft3 start=2026-11-20T18:40:00 end=2026-11-20T18:41:51 rc=0 busy=[loginwindow] gpu=0% +T.edit1.r1.vxdraft5 start=2026-11-20T18:42:31 end=2026-11-20T18:44:21 rc=0 busy=[Brave] gpu=1% +T.edit1.r1.vxdraft7 start=2026-11-20T18:45:02 end=2026-11-20T18:47:01 rc=0 busy=[loginwindow] gpu=0% +T.edit1.r1.vxdraft9 start=2026-11-20T18:47:41 end=2026-11-20T18:49:41 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.edit1.r1.vxdraft11 start=2026-11-20T18:50:21 end=2026-11-20T18:52:10 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.edit1.r1.vxdraft15 start=2026-11-20T18:52:51 end=2026-11-20T18:54:41 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.edit1.r1.mtp1 start=2026-11-20T18:55:21 end=2026-11-20T18:55:47 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.edit1.r1.mtp2 start=2026-11-20T18:56:27 end=2026-11-20T18:56:42 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.edit1.r1.mtp3 start=2026-11-20T18:57:22 end=2026-11-20T18:57:36 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +T.edit1.r1.mtp4 start=2026-11-20T18:58:17 end=2026-11-20T18:58:30 rc=0 busy=[mdworker_shared] gpu=1% +T.edit1.r1.mtp6 start=2026-11-20T18:59:10 end=2026-11-20T18:59:23 rc=0 busy=[secd] gpu=0% +T.complete1.r1.mtp6 start=2026-11-20T19:00:04 end=2026-11-20T19:00:21 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.complete1.r1.mtp4 start=2026-11-20T19:01:01 end=2026-11-20T19:01:18 rc=0 busy=[loginwindow] gpu=0% +T.complete1.r1.mtp3 start=2026-11-20T19:01:58 end=2026-11-20T19:02:14 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.complete1.r1.mtp2 start=2026-11-20T19:02:54 end=2026-11-20T19:03:10 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.complete1.r1.mtp1 start=2026-11-20T19:03:50 end=2026-11-20T19:04:08 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.complete1.r1.vxdraft15 start=2026-11-20T19:04:58 end=2026-11-20T19:06:50 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.complete1.r1.vxdraft11 start=2026-11-20T19:07:30 end=2026-11-20T19:09:32 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.complete1.r1.vxdraft9 start=2026-11-20T19:10:13 end=2026-11-20T19:12:06 rc=0 busy=[Brave] gpu=0% +T.complete1.r1.vxdraft7 start=2026-11-20T19:12:46 end=2026-11-20T19:14:38 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.complete1.r1.vxdraft5 start=2026-11-20T19:15:28 end=2026-11-20T19:17:31 rc=0 busy=[airportd] gpu=0% +T.complete1.r1.vxdraft3 start=2026-11-20T19:18:11 end=2026-11-20T19:20:14 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.complete1.r1.cache start=2026-11-20T19:20:54 end=2026-11-20T19:21:23 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.complete1.r1.ngram start=2026-11-20T19:22:03 end=2026-11-20T19:22:22 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.complete1.r1.completion start=2026-11-20T19:23:02 end=2026-11-20T19:23:21 rc=0 busy=[loginwindow] gpu=1% +T.complete1.r1.vx start=2026-11-20T19:24:01 end=2026-11-20T19:25:46 rc=0 busy=[loginwindow] gpu=1% +T.write1.r1.vx start=2026-11-20T19:26:26 end=2026-11-20T19:28:15 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.write1.r1.completion start=2026-11-20T19:29:05 end=2026-11-20T19:29:28 rc=0 busy=[secd] gpu=0% +T.write1.r1.ngram start=2026-11-20T19:30:18 end=2026-11-20T19:30:33 rc=0 busy=[launchd] gpu=1% +T.write1.r1.cache start=2026-11-20T19:31:13 end=2026-11-20T19:31:31 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=1% +T.write1.r1.vxdraft3 start=2026-11-20T19:32:11 end=2026-11-20T19:34:00 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +T.write1.r1.vxdraft5 start=2026-11-20T19:34:41 end=2026-11-20T19:36:33 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.write1.r1.vxdraft7 start=2026-11-20T19:37:13 end=2026-11-20T19:39:14 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.write1.r1.vxdraft9 start=2026-11-20T19:39:54 end=2026-11-20T19:41:46 rc=0 busy=[dasd] gpu=0% +T.write1.r1.vxdraft11 start=2026-11-20T19:42:26 end=2026-11-20T19:44:25 rc=0 busy=[airportd] gpu=0% +T.write1.r1.vxdraft15 start=2026-11-20T19:45:05 end=2026-11-20T19:46:56 rc=0 busy=[secd] gpu=0% +T.write1.r1.mtp1 start=2026-11-20T19:47:36 end=2026-11-20T19:47:58 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.write1.r1.mtp2 start=2026-11-20T19:48:38 end=2026-11-20T19:48:49 rc=0 busy=[WindowServer] gpu=0% +T.write1.r1.mtp3 start=2026-11-20T19:49:49 end=2026-11-20T19:49:59 rc=0 busy=[WindowServer] gpu=2% +T.write1.r1.mtp4 start=2026-11-20T19:50:39 end=2026-11-20T19:50:49 rc=0 busy=[airportd] gpu=1% +T.write1.r1.mtp6 start=2026-11-20T19:51:29 end=2026-11-20T19:51:40 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.explain1.r1.mtp6 start=2026-11-20T19:52:20 end=2026-11-20T19:52:37 rc=0 busy=[bash] gpu=0% +T.explain1.r1.mtp4 start=2026-11-20T19:53:17 end=2026-11-20T19:53:32 rc=0 busy=[secd] gpu=0% +T.explain1.r1.mtp3 start=2026-11-20T19:54:12 end=2026-11-20T19:54:27 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.explain1.r1.mtp2 start=2026-11-20T19:55:07 end=2026-11-20T19:55:23 rc=0 busy=[WindowServer] gpu=0% +T.explain1.r1.mtp1 start=2026-11-20T19:56:03 end=2026-11-20T19:56:19 rc=0 busy=[Brave] gpu=0% +T.explain1.r1.vxdraft15 start=2026-11-20T19:56:59 end=2026-11-20T19:59:03 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.explain1.r1.vxdraft11 start=2026-11-20T19:59:43 end=2026-11-20T20:01:37 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.explain1.r1.vxdraft9 start=2026-11-20T20:02:17 end=2026-11-20T20:04:12 rc=0 busy=[secd] gpu=1% +T.explain1.r1.vxdraft7 start=2026-11-20T20:04:52 end=2026-11-20T20:06:47 rc=0 busy=[airportd] gpu=0% +T.explain1.r1.vxdraft5 start=2026-11-20T20:07:27 end=2026-11-20T20:09:29 rc=0 busy=[apsd] gpu=0% +T.explain1.r1.vxdraft3 start=2026-11-20T20:10:10 end=2026-11-20T20:12:12 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.explain1.r1.cache start=2026-11-20T20:12:52 end=2026-11-20T20:13:22 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.explain1.r1.ngram start=2026-11-20T20:14:02 end=2026-11-20T20:14:20 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.explain1.r1.completion start=2026-11-20T20:15:00 end=2026-11-20T20:15:18 rc=0 busy=[WindowServer] gpu=0% +T.explain1.r1.vx start=2026-11-20T20:15:58 end=2026-11-20T20:17:52 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.edit2.r1.vx start=2026-11-20T20:18:32 end=2026-11-20T20:20:26 rc=0 busy=[Brave] gpu=1% +T.edit2.r1.completion start=2026-11-20T20:21:06 end=2026-11-20T20:21:33 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.edit2.r1.ngram start=2026-11-20T20:22:13 end=2026-11-20T20:22:22 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.edit2.r1.cache start=2026-11-20T20:23:02 end=2026-11-20T20:23:14 rc=0 busy=[WindowServer] gpu=3% +T.edit2.r1.vxdraft3 start=2026-11-20T20:23:54 end=2026-11-20T20:25:42 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=4% +T.edit2.r1.vxdraft5 start=2026-11-20T20:26:22 end=2026-11-20T20:28:12 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=1% +T.edit2.r1.vxdraft7 start=2026-11-20T20:28:52 end=2026-11-20T20:30:58 rc=0 busy=[WindowServer] gpu=1% +T.edit2.r1.vxdraft9 start=2026-11-20T20:31:38 end=2026-11-20T20:33:38 rc=0 busy=[PerfPowerServices] gpu=1% +T.edit2.r1.vxdraft11 start=2026-11-20T20:34:28 end=2026-11-20T20:36:24 rc=0 busy=[airportd] gpu=1% +T.edit2.r1.vxdraft15 start=2026-11-20T20:37:05 end=2026-11-20T20:38:53 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.edit2.r1.mtp1 start=2026-11-20T20:39:33 end=2026-11-20T20:39:58 rc=0 busy=[WindowServer] gpu=1% +T.edit2.r1.mtp2 start=2026-11-20T20:40:38 end=2026-11-20T20:40:53 rc=0 busy=[WindowServer] gpu=1% +T.edit2.r1.mtp3 start=2026-11-20T20:41:33 end=2026-11-20T20:41:46 rc=0 busy=[WindowServer] gpu=1% +T.edit2.r1.mtp4 start=2026-11-20T20:42:26 end=2026-11-20T20:42:39 rc=0 busy=[WindowServer] gpu=1% +T.edit2.r1.mtp6 start=2026-11-20T20:43:20 end=2026-11-20T20:43:32 rc=0 busy=[WindowServer] gpu=1% +T.complete2.r1.mtp6 start=2026-11-20T20:44:12 end=2026-11-20T20:44:31 rc=0 busy=[WindowServer] gpu=1% +T.complete2.r1.mtp4 start=2026-11-20T20:45:11 end=2026-11-20T20:45:28 rc=0 busy=[WindowServer] gpu=1% +T.complete2.r1.mtp3 start=2026-11-20T20:46:08 end=2026-11-20T20:46:24 rc=0 busy=[WindowServer] gpu=0% +T.complete2.r1.mtp2 start=2026-11-20T20:47:05 end=2026-11-20T20:47:21 rc=0 busy=[WindowServer] gpu=0% +T.complete2.r1.mtp1 start=2026-11-20T20:48:01 end=2026-11-20T20:48:18 rc=0 busy=[WindowServer] gpu=0% +T.complete2.r1.vxdraft15 start=2026-11-20T20:48:59 end=2026-11-20T20:50:53 rc=0 busy=[WindowServer] gpu=0% +T.complete2.r1.vxdraft11 start=2026-11-20T20:55:55 end=2026-11-20T20:57:49 rc=0 busy=[WindowServer] gpu=0% +T.complete2.r1.vxdraft9 start=2026-11-20T20:58:29 end=2026-11-20T21:00:25 rc=0 busy=[WindowServer] gpu=0% +T.complete2.r1.vxdraft7 start=2026-11-20T21:01:05 end=2026-11-20T21:03:10 rc=0 busy=[WindowServer] gpu=0% +T.complete2.r1.vxdraft5 start=2026-11-20T21:03:50 end=2026-11-20T21:05:45 rc=0 busy=[WindowServer] gpu=0% +T.complete2.r1.vxdraft3 start=2026-11-20T21:06:25 end=2026-11-20T21:08:21 rc=0 busy=[WindowServer] gpu=1% +T.complete2.r1.cache start=2026-11-20T21:09:01 end=2026-11-20T21:09:31 rc=0 busy=[airportd] gpu=1% +T.complete2.r1.ngram start=2026-11-20T21:10:12 end=2026-11-20T21:10:31 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +T.complete2.r1.completion start=2026-11-20T21:11:11 end=2026-11-20T21:11:30 rc=0 busy=[mdworker_shared] gpu=0% +T.complete2.r1.vx start=2026-11-20T21:12:10 end=2026-11-20T21:14:05 rc=0 busy=[mDNSResponder] gpu=0% +T.write2.r1.vx start=2026-11-20T21:14:45 end=2026-11-20T21:16:38 rc=0 busy=[airportd] gpu=1% +T.write2.r1.completion start=2026-11-20T21:17:28 end=2026-11-20T21:17:51 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +T.write2.r1.ngram start=2026-11-20T21:18:31 end=2026-11-20T21:18:46 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=1% +T.write2.r1.cache start=2026-11-20T21:19:26 end=2026-11-20T21:19:43 rc=0 busy=[WindowServer] gpu=1% +T.write2.r1.vxdraft3 start=2026-11-20T21:20:24 end=2026-11-20T21:22:23 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +T.write2.r1.vxdraft5 start=2026-11-20T21:23:04 end=2026-11-20T21:24:53 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.write2.r1.vxdraft7 start=2026-11-20T21:25:33 end=2026-11-20T21:27:24 rc=0 busy=[Google] gpu=0% +T.write2.r1.vxdraft9 start=2026-11-20T21:28:04 end=2026-11-20T21:30:04 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.write2.r1.vxdraft11 start=2026-11-20T21:30:44 end=2026-11-20T21:32:35 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.write2.r1.vxdraft15 start=2026-11-20T21:33:16 end=2026-11-20T21:35:18 rc=0 busy=[WindowServer] gpu=2% +T.write2.r1.mtp1 start=2026-11-20T21:35:58 end=2026-11-20T21:36:20 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +T.write2.r1.mtp2 start=2026-11-20T21:37:00 end=2026-11-20T21:37:12 rc=0 busy=[WindowServer] gpu=0% +T.write2.r1.mtp3 start=2026-11-20T21:37:53 end=2026-11-20T21:38:05 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.write2.r1.mtp4 start=2026-11-20T21:38:45 end=2026-11-20T21:38:57 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +T.write2.r1.mtp6 start=2026-11-20T21:39:37 end=2026-11-20T21:39:50 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +T.explain2.r1.mtp6 start=2026-11-20T21:40:30 end=2026-11-20T21:40:49 rc=0 busy=[bash] gpu=1% +T.explain2.r1.mtp4 start=2026-11-20T21:41:29 end=2026-11-20T21:41:46 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +T.explain2.r1.mtp3 start=2026-11-20T21:42:26 end=2026-11-20T21:42:43 rc=0 busy=[1.3 ps] gpu=0% +T.explain2.r1.mtp2 start=2026-11-20T21:43:23 end=2026-11-20T21:43:40 rc=0 busy=[airportd] gpu=0% +T.explain2.r1.mtp1 start=2026-11-20T21:44:20 end=2026-11-20T21:44:37 rc=0 busy=[clocksyncd] gpu=1% +T.explain2.r1.vxdraft15 start=2026-11-20T21:45:17 end=2026-11-20T21:47:20 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +T.explain2.r1.vxdraft11 start=2026-11-20T21:48:00 end=2026-11-20T21:50:05 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.explain2.r1.vxdraft9 start=2026-11-20T21:50:45 end=2026-11-20T21:52:49 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.explain2.r1.vxdraft7 start=2026-11-20T21:53:29 end=2026-11-20T21:55:32 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +T.explain2.r1.vxdraft5 start=2026-11-20T21:56:13 end=2026-11-20T21:58:08 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.explain2.r1.vxdraft3 start=2026-11-20T21:58:58 end=2026-11-20T22:01:02 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.explain2.r1.cache start=2026-11-20T22:01:42 end=2026-11-20T22:02:11 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +T.explain2.r1.ngram start=2026-11-20T22:02:51 end=2026-11-20T22:03:10 rc=0 busy=[WindowServer] gpu=1% +T.explain2.r1.completion start=2026-11-20T22:03:50 end=2026-11-20T22:04:09 rc=0 busy=[WindowServer] gpu=0% +T.explain2.r1.vx start=2026-11-20T22:04:49 end=2026-11-20T22:06:44 rc=0 busy=[WindowServer] gpu=1% +T.edit3.r1.vx start=2026-11-20T22:07:25 end=2026-11-20T22:09:22 rc=0 busy=[WindowServer] gpu=1% +T.edit3.r1.completion start=2026-11-20T22:10:02 end=2026-11-20T22:10:31 rc=0 busy=[WindowServer] gpu=1% +T.edit3.r1.ngram start=2026-11-20T22:11:11 end=2026-11-20T22:11:12 rc=1 busy=[mdworker_shared] gpu=0% +T.edit3.r1.cache start=2026-11-20T22:11:52 end=2026-11-20T22:11:54 rc=1 busy=[WindowServer] gpu=2% +flash attention: given by FA; chosen: on +T.edit3.r1.vx start=2026-11-20T22:14:07 end=2026-11-20T22:16:04 rc=0 busy=[corespotlightd] gpu=3% +T.edit3.r1.completion start=2026-11-20T22:16:44 end=2026-11-20T22:17:13 rc=0 busy=[WindowServer] gpu=1% +T.edit3.r1.ngram start=2026-11-20T22:17:53 end=2026-11-20T22:18:04 rc=0 busy=[WindowServer] gpu=2% +T.edit3.r1.cache start=2026-11-20T22:18:45 end=2026-11-20T22:18:58 rc=0 busy=[WindowServer] gpu=1% +T.edit3.r1.vxdraft3 start=2026-11-20T22:19:38 end=2026-11-20T22:21:28 rc=0 busy=[WindowServer] gpu=2% +T.edit3.r1.vxdraft5 start=2026-11-20T22:22:09 end=2026-11-20T22:23:59 rc=0 busy=[networkserviceproxy] gpu=1% +T.edit3.r1.vxdraft7 start=2026-11-20T22:24:39 end=2026-11-20T22:26:31 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +T.edit3.r1.vxdraft9 start=2026-11-20T22:27:11 end=2026-11-20T22:29:21 rc=0 busy=[WindowServer] gpu=1% +T.edit3.r1.vxdraft11 start=2026-11-20T22:30:01 end=2026-11-20T22:31:52 rc=0 busy=[WindowServer] gpu=1% +T.edit3.r1.vxdraft15 start=2026-11-20T22:32:32 end=2026-11-20T22:34:20 rc=0 busy=[WindowServer] gpu=1% +T.edit3.r1.mtp1 start=2026-11-20T22:35:00 end=2026-11-20T22:35:27 rc=0 busy=[WindowServer] gpu=1% +T.edit3.r1.mtp2 start=2026-11-20T22:36:07 end=2026-11-20T22:36:24 rc=0 busy=[WindowServer] gpu=1% +T.edit3.r1.mtp3 start=2026-11-20T22:37:04 end=2026-11-20T22:37:19 rc=0 busy=[WindowServer] gpu=0% +T.edit3.r1.mtp4 start=2026-11-20T22:37:59 end=2026-11-20T22:38:15 rc=0 busy=[WindowServer] gpu=1% +T.edit3.r1.mtp6 start=2026-11-20T22:38:55 end=2026-11-20T22:39:09 rc=0 busy=[WindowServer] gpu=1% +T.complete3.r1.mtp6 start=2026-11-20T22:39:49 end=2026-11-20T22:40:06 rc=0 busy=[WindowServer] gpu=0% +T.complete3.r1.mtp4 start=2026-11-20T22:40:46 end=2026-11-20T22:41:02 rc=0 busy=[WindowServer] gpu=1% +T.complete3.r1.mtp3 start=2026-11-20T22:41:42 end=2026-11-20T22:41:58 rc=0 busy=[WindowServer] gpu=1% +T.complete3.r1.mtp2 start=2026-11-20T22:42:38 end=2026-11-20T22:42:54 rc=0 busy=[PerfPowerServices] gpu=0% +T.complete3.r1.mtp1 start=2026-11-20T22:43:34 end=2026-11-20T22:43:50 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +T.complete3.r1.vxdraft15 start=2026-11-20T22:44:30 end=2026-11-20T22:46:26 rc=0 busy=[WindowServer] gpu=1% +T.complete3.r1.vxdraft11 start=2026-11-20T22:47:06 end=2026-11-20T22:49:01 rc=0 busy=[WindowServer] gpu=1% +T.complete3.r1.vxdraft9 start=2026-11-20T22:49:41 end=2026-11-20T22:51:46 rc=0 busy=[WindowServer] gpu=0% +T.complete3.r1.vxdraft7 start=2026-11-20T22:52:26 end=2026-11-20T22:54:18 rc=0 busy=[WindowServer] gpu=0% +T.complete3.r1.vxdraft5 start=2026-11-20T22:54:59 end=2026-11-20T22:56:53 rc=0 busy=[WindowServer] gpu=0% +T.complete3.r1.vxdraft3 start=2026-11-20T22:57:33 end=2026-11-20T22:59:36 rc=0 busy=[WindowServer] gpu=0% +T.complete3.r1.cache start=2026-11-20T23:00:16 end=2026-11-20T23:00:45 rc=0 busy=[WindowServer] gpu=1% +T.complete3.r1.ngram start=2026-11-20T23:01:25 end=2026-11-20T23:01:44 rc=0 busy=[airportd] gpu=1% +T.complete3.r1.completion start=2026-11-20T23:02:24 end=2026-11-20T23:02:42 rc=0 busy=[WindowServer] gpu=1% +T.complete3.r1.vx start=2026-11-20T23:03:23 end=2026-11-20T23:05:19 rc=0 busy=[WindowServer] gpu=1% +T.write3.r1.vx start=2026-11-20T23:06:00 end=2026-11-20T23:07:51 rc=0 busy=[WindowServer] gpu=1% +T.write3.r1.completion start=2026-11-20T23:08:31 end=2026-11-20T23:08:54 rc=0 busy=[networkserviceproxy] gpu=0% +T.write3.r1.ngram start=2026-11-20T23:09:34 end=2026-11-20T23:09:49 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +T.write3.r1.cache start=2026-11-20T23:10:29 end=2026-11-20T23:10:47 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.write3.r1.vxdraft3 start=2026-11-20T23:11:27 end=2026-11-20T23:13:27 rc=0 busy=[airportd] gpu=0% +T.write3.r1.vxdraft5 start=2026-11-20T23:14:07 end=2026-11-20T23:16:11 rc=0 busy=[WiFiAgent] gpu=0% +T.write3.r1.vxdraft7 start=2026-11-20T23:16:52 end=2026-11-20T23:18:51 rc=0 busy=[WindowServer] gpu=1% +T.write3.r1.vxdraft9 start=2026-11-20T23:19:31 end=2026-11-20T23:21:24 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +T.write3.r1.vxdraft11 start=2026-11-20T23:22:04 end=2026-11-20T23:23:55 rc=0 busy=[airportd] gpu=0% +T.write3.r1.vxdraft15 start=2026-11-20T23:24:36 end=2026-11-20T23:26:35 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +T.write3.r1.mtp1 start=2026-11-20T23:27:15 end=2026-11-20T23:27:36 rc=0 busy=[WindowServer] gpu=1% +T.write3.r1.mtp2 start=2026-11-20T23:28:16 end=2026-11-20T23:28:27 rc=0 busy=[WindowServer] gpu=1% +T.write3.r1.mtp3 start=2026-11-20T23:29:07 end=2026-11-20T23:29:18 rc=0 busy=[WindowServer] gpu=1% +T.write3.r1.mtp4 start=2026-11-20T23:29:58 end=2026-11-20T23:30:08 rc=0 busy=[WindowServer] gpu=0% +T.write3.r1.mtp6 start=2026-11-20T23:30:48 end=2026-11-20T23:31:00 rc=0 busy=[WindowServer] gpu=1% +T.explain3.r1.mtp6 start=2026-11-20T23:31:40 end=2026-11-20T23:31:57 rc=0 busy=[WindowServer] gpu=1% +T.explain3.r1.mtp4 start=2026-11-20T23:32:37 end=2026-11-20T23:32:53 rc=0 busy=[WindowServer] gpu=1% +T.explain3.r1.mtp3 start=2026-11-20T23:33:33 end=2026-11-20T23:33:49 rc=0 busy=[WindowServer] gpu=1% +T.explain3.r1.mtp2 start=2026-11-20T23:34:29 end=2026-11-20T23:34:46 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +T.explain3.r1.mtp1 start=2026-11-20T23:35:26 end=2026-11-20T23:35:44 rc=0 busy=[airportd] gpu=0% +T.explain3.r1.vxdraft15 start=2026-11-20T23:36:24 end=2026-11-20T23:38:19 rc=0 busy=[bash] gpu=1% +T.explain3.r1.vxdraft11 start=2026-11-20T23:38:59 end=2026-11-20T23:40:54 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.explain3.r1.vxdraft9 start=2026-11-20T23:41:34 end=2026-11-20T23:43:35 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +T.explain3.r1.vxdraft7 start=2026-11-20T23:44:15 end=2026-11-20T23:46:19 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=3% +T.explain3.r1.vxdraft5 start=2026-11-20T23:46:59 end=2026-11-20T23:48:53 rc=0 busy=[bash] gpu=0% +T.explain3.r1.vxdraft3 start=2026-11-20T23:49:33 end=2026-11-20T23:51:28 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +T.explain3.r1.cache start=2026-11-20T23:52:08 end=2026-11-20T23:52:38 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=1% +T.explain3.r1.ngram start=2026-11-20T23:53:28 end=2026-11-20T23:53:47 rc=0 busy=[talagentd] gpu=0% +T.explain3.r1.completion start=2026-11-20T23:54:27 end=2026-11-20T23:54:46 rc=0 busy=[WindowServer] gpu=1% +T.explain3.r1.vx start=2026-11-20T23:55:26 end=2026-11-20T23:57:30 rc=0 busy=[WindowServer] gpu=1% +flash attention: given by FA; chosen: on +draft lengths given: DRAFT=7 MTP_N=3 +C.edit1.r1.vx start=2026-11-20T23:59:36 end=2026-11-21T00:01:39 rc=0 busy=[WindowServer] gpu=1% +C.edit1.r1.vxdraft7 start=2026-11-21T00:02:19 end=2026-11-21T00:04:10 rc=0 busy=[launchd] gpu=1% +C.edit1.r1.completion start=2026-11-21T00:05:00 end=2026-11-21T00:05:27 rc=0 busy=[WindowServer] gpu=1% +C.edit1.r1.cache start=2026-11-21T00:06:07 end=2026-11-21T00:06:22 rc=0 busy=[WindowServer] gpu=3% +C.edit1.r1.ngram start=2026-11-21T00:07:02 end=2026-11-21T00:07:18 rc=0 busy=[secd] gpu=2% +C.edit1.r1.mtp3 start=2026-11-21T00:07:58 end=2026-11-21T00:08:13 rc=0 busy=[PerfPowerServices] gpu=0% +C.complete1.r1.vx start=2026-11-21T00:08:53 end=2026-11-21T00:10:49 rc=0 busy=[WindowServer] gpu=1% +C.complete1.r1.vxdraft7 start=2026-11-21T00:11:29 end=2026-11-21T00:13:33 rc=0 busy=[WindowServer] gpu=0% +C.complete1.r1.completion start=2026-11-21T00:14:13 end=2026-11-21T00:14:39 rc=0 busy=[WindowServer] gpu=0% +C.complete1.r1.cache start=2026-11-21T00:15:19 end=2026-11-21T00:15:38 rc=0 busy=[WindowServer] gpu=1% +C.complete1.r1.ngram start=2026-11-21T00:16:19 end=2026-11-21T00:16:36 rc=0 busy=[WindowServer] gpu=1% +C.complete1.r1.mtp3 start=2026-11-21T00:17:16 end=2026-11-21T00:17:29 rc=0 busy=[WindowServer] gpu=0% +C.write1.r1.vx start=2026-11-21T00:18:10 end=2026-11-21T00:20:11 rc=0 busy=[WindowServer] gpu=1% +C.write1.r1.vxdraft7 start=2026-11-21T00:20:51 end=2026-11-21T00:22:43 rc=0 busy=[WindowServer] gpu=0% +C.write1.r1.completion start=2026-11-21T00:23:24 end=2026-11-21T00:23:47 rc=0 busy=[networkserviceproxy] gpu=0% +C.write1.r1.cache start=2026-11-21T00:24:27 end=2026-11-21T00:24:43 rc=0 busy=[WindowServer] gpu=0% +C.write1.r1.ngram start=2026-11-21T00:25:23 end=2026-11-21T00:25:38 rc=0 busy=[WindowServer] gpu=0% +C.write1.r1.mtp3 start=2026-11-21T00:26:18 end=2026-11-21T00:26:29 rc=0 busy=[launchd] gpu=0% +C.explain1.r1.vx start=2026-11-21T00:27:09 end=2026-11-21T00:29:03 rc=0 busy=[WindowServer] gpu=1% +C.explain1.r1.vxdraft7 start=2026-11-21T00:29:43 end=2026-11-21T00:31:37 rc=0 busy=[WindowServer] gpu=1% +C.explain1.r1.completion start=2026-11-21T00:32:17 end=2026-11-21T00:32:44 rc=0 busy=[WindowServer] gpu=1% +C.explain1.r1.cache start=2026-11-21T00:33:24 end=2026-11-21T00:33:46 rc=0 busy=[WindowServer] gpu=1% +C.explain1.r1.ngram start=2026-11-21T00:34:26 end=2026-11-21T00:34:44 rc=0 busy=[WindowServer] gpu=1% +C.explain1.r1.mtp3 start=2026-11-21T00:35:25 end=2026-11-21T00:35:41 rc=0 busy=[WindowServer] gpu=1% +C.edit2.r1.vx start=2026-11-21T00:36:21 end=2026-11-21T00:38:13 rc=0 busy=[WindowServer] gpu=0% +C.edit2.r1.vxdraft7 start=2026-11-21T00:38:53 end=2026-11-21T00:40:42 rc=0 busy=[WindowServer] gpu=0% +C.edit2.r1.completion start=2026-11-21T00:41:22 end=2026-11-21T00:41:48 rc=0 busy=[WindowServer] gpu=2% +C.edit2.r1.cache start=2026-11-21T00:42:28 end=2026-11-21T00:42:39 rc=0 busy=[WindowServer] gpu=3% +C.edit2.r1.ngram start=2026-11-21T00:43:20 end=2026-11-21T00:43:28 rc=0 busy=[WindowServer] gpu=0% +C.edit2.r1.mtp3 start=2026-11-21T00:44:08 end=2026-11-21T00:44:22 rc=0 busy=[WindowServer] gpu=0% +C.complete2.r1.vx start=2026-11-21T00:45:02 end=2026-11-21T00:47:05 rc=0 busy=[WindowServer] gpu=1% +C.complete2.r1.vxdraft7 start=2026-11-21T00:47:45 end=2026-11-21T00:49:56 rc=0 busy=[WindowServer] gpu=0% +C.complete2.r1.completion start=2026-11-21T00:50:36 end=2026-11-21T00:51:02 rc=0 busy=[WindowServer] gpu=1% +C.complete2.r1.cache start=2026-11-21T00:51:42 end=2026-11-21T00:52:02 rc=0 busy=[WindowServer] gpu=1% +C.complete2.r1.ngram start=2026-11-21T00:52:42 end=2026-11-21T00:53:00 rc=0 busy=[WindowServer] gpu=1% +C.complete2.r1.mtp3 start=2026-11-21T00:53:40 end=2026-11-21T00:53:54 rc=0 busy=[WindowServer] gpu=1% +C.write2.r1.vx start=2026-11-21T00:54:34 end=2026-11-21T00:56:35 rc=0 busy=[WindowServer] gpu=1% +C.write2.r1.vxdraft7 start=2026-11-21T00:57:15 end=2026-11-21T00:59:17 rc=0 busy=[WindowServer] gpu=0% +C.write2.r1.completion start=2026-11-21T00:59:57 end=2026-11-21T01:00:20 rc=0 busy=[WindowServer] gpu=0% +C.write2.r1.cache start=2026-11-21T01:01:01 end=2026-11-21T01:01:19 rc=0 busy=[WindowServer] gpu=0% +C.write2.r1.ngram start=2026-11-21T01:01:59 end=2026-11-21T01:02:14 rc=0 busy=[WindowServer] gpu=0% +C.write2.r1.mtp3 start=2026-11-21T01:02:54 end=2026-11-21T01:03:04 rc=0 busy=[talagentd] gpu=1% +C.explain2.r1.vx start=2026-11-21T01:03:44 end=2026-11-21T01:05:38 rc=0 busy=[WindowServer] gpu=1% +C.explain2.r1.vxdraft7 start=2026-11-21T01:06:28 end=2026-11-21T01:08:21 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +C.explain2.r1.completion start=2026-11-21T01:09:01 end=2026-11-21T01:09:28 rc=0 busy=[WindowServer] gpu=1% +C.explain2.r1.cache start=2026-11-21T01:10:08 end=2026-11-21T01:10:27 rc=0 busy=[mdworker_shared] gpu=1% +C.explain2.r1.ngram start=2026-11-21T01:11:07 end=2026-11-21T01:11:26 rc=0 busy=[WindowServer] gpu=0% +C.explain2.r1.mtp3 start=2026-11-21T01:12:06 end=2026-11-21T01:12:21 rc=0 busy=[cfprefsd] gpu=0% +C.edit3.r1.vx start=2026-11-21T01:13:01 end=2026-11-21T01:14:54 rc=0 busy=[WindowServer] gpu=0% +C.edit3.r1.vxdraft7 start=2026-11-21T01:15:34 end=2026-11-21T01:17:25 rc=0 busy=[WindowServer] gpu=0% +C.edit3.r1.completion start=2026-11-21T01:18:05 end=2026-11-21T01:18:32 rc=0 busy=[WindowServer] gpu=1% +C.edit3.r1.cache start=2026-11-21T01:19:13 end=2026-11-21T01:19:25 rc=0 busy=[WindowServer] gpu=2% +C.edit3.r1.ngram start=2026-11-21T01:20:05 end=2026-11-21T01:20:16 rc=0 busy=[WindowServer] gpu=0% +C.edit3.r1.mtp3 start=2026-11-21T01:20:56 end=2026-11-21T01:21:10 rc=0 busy=[WindowServer] gpu=1% +C.complete3.r1.vx start=2026-11-21T01:21:50 end=2026-11-21T01:23:45 rc=0 busy=[WindowServer] gpu=0% +C.complete3.r1.vxdraft7 start=2026-11-21T01:24:25 end=2026-11-21T01:26:36 rc=0 busy=[WindowServer] gpu=0% +C.complete3.r1.completion start=2026-11-21T01:27:16 end=2026-11-21T01:27:43 rc=0 busy=[WindowServer] gpu=0% +C.complete3.r1.cache start=2026-11-21T01:28:33 end=2026-11-21T01:28:48 rc=0 busy=[WindowServer] gpu=0% +C.complete3.r1.ngram start=2026-11-21T01:29:28 end=2026-11-21T01:29:48 rc=0 busy=[WindowServer] gpu=0% +C.complete3.r1.mtp3 start=2026-11-21T01:30:28 end=2026-11-21T01:30:42 rc=0 busy=[WindowServer] gpu=0% +C.write3.r1.vx start=2026-11-21T01:31:22 end=2026-11-21T01:33:13 rc=0 busy=[WindowServer] gpu=1% +C.write3.r1.vxdraft7 start=2026-11-21T01:33:54 end=2026-11-21T01:35:52 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.write3.r1.completion start=2026-11-21T01:36:33 end=2026-11-21T01:36:56 rc=0 busy=[airportd] gpu=0% +C.write3.r1.cache start=2026-11-21T01:37:36 end=2026-11-21T01:37:51 rc=0 busy=[Brave] gpu=0% +C.write3.r1.ngram start=2026-11-21T01:38:31 end=2026-11-21T01:38:46 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +C.write3.r1.mtp3 start=2026-11-21T01:39:26 end=2026-11-21T01:39:36 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.explain3.r1.vx start=2026-11-21T01:40:17 end=2026-11-21T01:42:10 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.explain3.r1.vxdraft7 start=2026-11-21T01:42:50 end=2026-11-21T01:44:45 rc=0 busy=[1.6 ps] gpu=0% +C.explain3.r1.completion start=2026-11-21T01:45:25 end=2026-11-21T01:45:51 rc=0 busy=[airportd] gpu=0% +C.explain3.r1.cache start=2026-11-21T01:46:32 end=2026-11-21T01:46:52 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.explain3.r1.ngram start=2026-11-21T01:47:32 end=2026-11-21T01:47:50 rc=0 busy=[Brave] gpu=1% +C.explain3.r1.mtp3 start=2026-11-21T01:48:31 end=2026-11-21T01:48:46 rc=0 busy=[airportd] gpu=1% +C.edit1.r2.mtp3 start=2026-11-21T01:49:26 end=2026-11-21T01:49:40 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +C.edit1.r2.ngram start=2026-11-21T01:50:20 end=2026-11-21T01:50:36 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=1% +C.edit1.r2.cache start=2026-11-21T01:51:16 end=2026-11-21T01:51:31 rc=0 busy=[WindowServer] gpu=0% +C.edit1.r2.completion start=2026-11-21T01:52:11 end=2026-11-21T01:52:30 rc=0 busy=[mdworker_shared] gpu=0% +C.edit1.r2.vxdraft7 start=2026-11-21T01:53:10 end=2026-11-21T01:55:11 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.edit1.r2.vx start=2026-11-21T01:55:51 end=2026-11-21T01:57:54 rc=0 busy=[airportd] gpu=0% +C.complete1.r2.mtp3 start=2026-11-21T01:58:34 end=2026-11-21T01:58:56 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +C.complete1.r2.ngram start=2026-11-21T01:59:37 end=2026-11-21T01:59:54 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.complete1.r2.cache start=2026-11-21T02:00:34 end=2026-11-21T02:00:54 rc=0 busy=[airportd] gpu=0% +C.complete1.r2.completion start=2026-11-21T02:01:34 end=2026-11-21T02:01:51 rc=0 busy=[Google] gpu=0% +C.complete1.r2.vxdraft7 start=2026-11-21T02:02:31 end=2026-11-21T02:04:35 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.complete1.r2.vx start=2026-11-21T02:05:15 end=2026-11-21T02:06:59 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.write1.r2.mtp3 start=2026-11-21T02:07:39 end=2026-11-21T02:07:58 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.write1.r2.ngram start=2026-11-21T02:08:38 end=2026-11-21T02:08:53 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +C.write1.r2.cache start=2026-11-21T02:09:33 end=2026-11-21T02:09:49 rc=0 busy=[Google] gpu=0% +C.write1.r2.completion start=2026-11-21T02:10:29 end=2026-11-21T02:10:44 rc=0 busy=[airportd] gpu=0% +C.write1.r2.vxdraft7 start=2026-11-21T02:11:24 end=2026-11-21T02:13:16 rc=0 busy=[WindowServer] gpu=1% +C.write1.r2.vx start=2026-11-21T02:13:56 end=2026-11-21T02:15:54 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +C.explain1.r2.mtp3 start=2026-11-21T02:16:34 end=2026-11-21T02:16:59 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.explain1.r2.ngram start=2026-11-21T02:17:40 end=2026-11-21T02:17:58 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.explain1.r2.cache start=2026-11-21T02:18:38 end=2026-11-21T02:19:00 rc=0 busy=[UserEventAgent] gpu=0% +C.explain1.r2.completion start=2026-11-21T02:19:40 end=2026-11-21T02:19:58 rc=0 busy=[dasd] gpu=0% +C.explain1.r2.vxdraft7 start=2026-11-21T02:20:38 end=2026-11-21T02:22:31 rc=0 busy=[Google] gpu=0% +C.explain1.r2.vx start=2026-11-21T02:23:11 end=2026-11-21T02:25:05 rc=0 busy=[airportd] gpu=0% +C.edit2.r2.mtp3 start=2026-11-21T02:25:46 end=2026-11-21T02:26:07 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.edit2.r2.ngram start=2026-11-21T02:26:58 end=2026-11-21T02:27:06 rc=0 busy=[WindowServer] gpu=0% +C.edit2.r2.cache start=2026-11-21T02:27:46 end=2026-11-21T02:27:57 rc=0 busy=[Brave] gpu=1% +C.edit2.r2.completion start=2026-11-21T02:28:37 end=2026-11-21T02:28:55 rc=0 busy=[ZoomUpdater] gpu=0% +C.edit2.r2.vxdraft7 start=2026-11-21T02:29:35 end=2026-11-21T02:31:22 rc=0 busy=[identityservicesd] gpu=0% +C.edit2.r2.vx start=2026-11-21T02:32:03 end=2026-11-21T02:33:56 rc=0 busy=[Brave] gpu=0% +C.complete2.r2.mtp3 start=2026-11-21T02:34:37 end=2026-11-21T02:34:59 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.complete2.r2.ngram start=2026-11-21T02:35:39 end=2026-11-21T02:35:57 rc=0 busy=[mediaanalysisd] gpu=0% +C.complete2.r2.cache start=2026-11-21T02:36:37 end=2026-11-21T02:36:57 rc=0 busy=[WindowServer] gpu=1% +C.complete2.r2.completion start=2026-11-21T02:37:37 end=2026-11-21T02:37:55 rc=0 busy=[WindowServer] gpu=1% +C.complete2.r2.vxdraft7 start=2026-11-21T02:38:35 end=2026-11-21T02:40:37 rc=0 busy=[Brave] gpu=4% +C.complete2.r2.vx start=2026-11-21T02:41:17 end=2026-11-21T02:43:09 rc=0 busy=[networkserviceproxy] gpu=1% +C.write2.r2.mtp3 start=2026-11-21T02:43:49 end=2026-11-21T02:44:08 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +C.write2.r2.ngram start=2026-11-21T02:44:49 end=2026-11-21T02:45:03 rc=0 busy=[launchd] gpu=0% +C.write2.r2.cache start=2026-11-21T02:45:44 end=2026-11-21T02:46:02 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.write2.r2.completion start=2026-11-21T02:47:02 end=2026-11-21T02:47:17 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=1% +C.write2.r2.vxdraft7 start=2026-11-21T02:47:57 end=2026-11-21T02:49:49 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.write2.r2.vx start=2026-11-21T02:50:29 end=2026-11-21T02:52:29 rc=0 busy=[UserEventAgent] gpu=2% +C.explain2.r2.mtp3 start=2026-11-21T02:53:09 end=2026-11-21T02:53:33 rc=0 busy=[WindowServer] gpu=1% +C.explain2.r2.ngram start=2026-11-21T02:54:13 end=2026-11-21T02:54:31 rc=0 busy=[WindowServer] gpu=1% +C.explain2.r2.cache start=2026-11-21T02:55:11 end=2026-11-21T02:55:30 rc=0 busy=[WindowServer] gpu=1% +C.explain2.r2.completion start=2026-11-21T02:56:11 end=2026-11-21T02:56:29 rc=0 busy=[WindowServer] gpu=0% +C.explain2.r2.vxdraft7 start=2026-11-21T02:57:09 end=2026-11-21T02:59:04 rc=0 busy=[WindowServer] gpu=1% +C.explain2.r2.vx start=2026-11-21T03:00:05 end=2026-11-21T03:01:58 rc=0 busy=[WindowServer] gpu=15% +C.edit3.r2.mtp3 start=2026-11-21T03:02:49 end=2026-11-21T03:03:11 rc=0 busy=[WindowServer] gpu=1% +C.edit3.r2.ngram start=2026-11-21T03:03:51 end=2026-11-21T03:04:02 rc=0 busy=[WindowServer] gpu=1% +C.edit3.r2.cache start=2026-11-21T03:04:42 end=2026-11-21T03:04:54 rc=0 busy=[WindowServer] gpu=1% +C.edit3.r2.completion start=2026-11-21T03:05:44 end=2026-11-21T03:06:03 rc=0 busy=[WindowServer] gpu=2% +C.edit3.r2.vxdraft7 start=2026-11-21T03:06:43 end=2026-11-21T03:08:33 rc=0 busy=[WindowServer] gpu=2% +C.edit3.r2.vx start=2026-11-21T03:09:13 end=2026-11-21T03:11:08 rc=0 busy=[WindowServer] gpu=7% +C.complete3.r2.mtp3 start=2026-11-21T03:11:48 end=2026-11-21T03:12:11 rc=0 busy=[launchd] gpu=2% +C.complete3.r2.ngram start=2026-11-21T03:12:51 end=2026-11-21T03:13:11 rc=0 busy=[WindowServer] gpu=2% +C.complete3.r2.cache start=2026-11-21T03:13:51 end=2026-11-21T03:14:06 rc=0 busy=[WindowServer] gpu=2% +C.complete3.r2.completion start=2026-11-21T03:14:46 end=2026-11-21T03:15:04 rc=0 busy=[WindowServer] gpu=2% +C.complete3.r2.vxdraft7 start=2026-11-21T03:15:44 end=2026-11-21T03:17:47 rc=0 busy=[WindowServer] gpu=2% +C.complete3.r2.vx start=2026-11-21T03:18:27 end=2026-11-21T03:20:19 rc=0 busy=[WindowServer] gpu=6% +C.write3.r2.mtp3 start=2026-11-21T03:20:59 end=2026-11-21T03:21:17 rc=0 busy=[WindowServer] gpu=1% +C.write3.r2.ngram start=2026-11-21T03:21:57 end=2026-11-21T03:22:12 rc=0 busy=[WindowServer] gpu=1% +C.write3.r2.cache start=2026-11-21T03:22:53 end=2026-11-21T03:23:07 rc=0 busy=[WindowServer] gpu=1% +C.write3.r2.completion start=2026-11-21T03:23:58 end=2026-11-21T03:24:12 rc=0 busy=[WindowServer] gpu=1% +C.write3.r2.vxdraft7 start=2026-11-21T03:24:53 end=2026-11-21T03:26:42 rc=0 busy=[WindowServer] gpu=1% +C.write3.r2.vx start=2026-11-21T03:27:22 end=2026-11-21T03:29:15 rc=0 busy=[WindowServer] gpu=8% +C.explain3.r2.mtp3 start=2026-11-21T03:29:55 end=2026-11-21T03:30:20 rc=0 busy=[WindowServer] gpu=1% +C.explain3.r2.ngram start=2026-11-21T03:31:00 end=2026-11-21T03:31:18 rc=0 busy=[WindowServer] gpu=2% +C.explain3.r2.cache start=2026-11-21T03:32:08 end=2026-11-21T03:32:29 rc=0 busy=[WindowServer] gpu=8% +C.explain3.r2.completion start=2026-11-21T03:33:09 end=2026-11-21T03:33:27 rc=0 busy=[WindowServer] gpu=7% +C.explain3.r2.vxdraft7 start=2026-11-21T03:34:07 end=2026-11-21T03:36:03 rc=0 busy=[WindowServer] gpu=6% +C.explain3.r2.vx start=2026-11-21T03:36:43 end=2026-11-21T03:38:46 rc=0 busy=[WindowServer] gpu=1% +C.edit1.r3.vx start=2026-11-21T03:39:26 end=2026-11-21T03:41:21 rc=0 busy=[WindowServer] gpu=6% +C.edit1.r3.vxdraft7 start=2026-11-21T03:42:01 end=2026-11-21T03:43:53 rc=0 busy=[WindowServer] gpu=8% +C.edit1.r3.completion start=2026-11-21T03:44:44 end=2026-11-21T03:45:12 rc=0 busy=[WindowServer] gpu=1% +C.edit1.r3.cache start=2026-11-21T03:45:52 end=2026-11-21T03:46:06 rc=0 busy=[WindowServer] gpu=1% +C.edit1.r3.ngram start=2026-11-21T03:46:47 end=2026-11-21T03:47:02 rc=0 busy=[WindowServer] gpu=1% +C.edit1.r3.mtp3 start=2026-11-21T03:47:43 end=2026-11-21T03:47:57 rc=0 busy=[WindowServer] gpu=1% +C.complete1.r3.vx start=2026-11-21T03:48:47 end=2026-11-21T03:50:40 rc=0 busy=[WindowServer] gpu=1% +C.complete1.r3.vxdraft7 start=2026-11-21T03:51:20 end=2026-11-21T03:53:14 rc=0 busy=[WindowServer] gpu=8% +C.complete1.r3.completion start=2026-11-21T03:53:54 end=2026-11-21T03:54:20 rc=0 busy=[WindowServer] gpu=1% +C.complete1.r3.cache start=2026-11-21T03:55:00 end=2026-11-21T03:55:20 rc=0 busy=[WindowServer] gpu=3% +C.complete1.r3.ngram start=2026-11-21T03:56:00 end=2026-11-21T03:56:17 rc=0 busy=[WindowServer] gpu=2% +C.complete1.r3.mtp3 start=2026-11-21T03:56:57 end=2026-11-21T03:57:11 rc=0 busy=[WindowServer] gpu=1% +C.write1.r3.vx start=2026-11-21T03:57:51 end=2026-11-21T04:00:10 rc=0 busy=[WindowServer] gpu=1% +C.write1.r3.vxdraft7 start=2026-11-21T04:00:50 end=2026-11-21T04:02:52 rc=0 busy=[WindowServer] gpu=1% +C.write1.r3.completion start=2026-11-21T04:03:42 end=2026-11-21T04:04:05 rc=0 busy=[WindowServer] gpu=1% +C.write1.r3.cache start=2026-11-21T04:04:45 end=2026-11-21T04:05:01 rc=0 busy=[WindowServer] gpu=1% +C.write1.r3.ngram start=2026-11-21T04:05:41 end=2026-11-21T04:05:56 rc=0 busy=[WindowServer] gpu=1% +C.write1.r3.mtp3 start=2026-11-21T04:06:46 end=2026-11-21T04:06:57 rc=0 busy=[WindowServer] gpu=1% +C.explain1.r3.vx start=2026-11-21T04:07:47 end=2026-11-21T04:09:51 rc=0 busy=[WindowServer] gpu=1% +C.explain1.r3.vxdraft7 start=2026-11-21T04:10:51 end=2026-11-21T04:12:45 rc=0 busy=[WindowServer] gpu=1% +C.explain1.r3.completion start=2026-11-21T04:13:26 end=2026-11-21T04:13:52 rc=0 busy=[WindowServer] gpu=7% +C.explain1.r3.cache start=2026-11-21T04:14:43 end=2026-11-21T04:15:04 rc=0 busy=[WindowServer] gpu=1% +C.explain1.r3.ngram start=2026-11-21T04:15:44 end=2026-11-21T04:16:03 rc=0 busy=[WindowServer] gpu=1% +C.explain1.r3.mtp3 start=2026-11-21T04:16:43 end=2026-11-21T04:16:59 rc=0 busy=[WindowServer] gpu=1% +C.edit2.r3.vx start=2026-11-21T04:17:50 end=2026-11-21T04:19:42 rc=0 busy=[WindowServer] gpu=1% +C.edit2.r3.vxdraft7 start=2026-11-21T04:20:22 end=2026-11-21T04:22:21 rc=0 busy=[WindowServer] gpu=12% +C.edit2.r3.completion start=2026-11-21T04:23:01 end=2026-11-21T04:23:27 rc=0 busy=[WindowServer] gpu=6% +C.edit2.r3.cache start=2026-11-21T04:24:08 end=2026-11-21T04:24:19 rc=0 busy=[WindowServer] gpu=8% +C.edit2.r3.ngram start=2026-11-21T04:24:59 end=2026-11-21T04:25:07 rc=0 busy=[WindowServer] gpu=1% +C.edit2.r3.mtp3 start=2026-11-21T04:25:47 end=2026-11-21T04:26:00 rc=0 busy=[WindowServer] gpu=2% +C.complete2.r3.vx start=2026-11-21T04:26:50 end=2026-11-21T04:28:57 rc=0 busy=[WindowServer] gpu=1% +C.complete2.r3.vxdraft7 start=2026-11-21T04:29:58 end=2026-11-21T04:32:00 rc=0 busy=[dasd] gpu=1% +C.complete2.r3.completion start=2026-11-21T04:32:50 end=2026-11-21T04:33:17 rc=0 busy=[WindowServer] gpu=1% +C.complete2.r3.cache start=2026-11-21T04:33:57 end=2026-11-21T04:34:17 rc=0 busy=[WindowServer] gpu=1% +C.complete2.r3.ngram start=2026-11-21T04:34:57 end=2026-11-21T04:35:15 rc=0 busy=[airportd] gpu=1% +C.complete2.r3.mtp3 start=2026-11-21T04:35:55 end=2026-11-21T04:36:09 rc=0 busy=[WindowServer] gpu=1% +C.write2.r3.vx start=2026-11-21T04:36:49 end=2026-11-21T04:38:40 rc=0 busy=[WindowServer] gpu=1% +C.write2.r3.vxdraft7 start=2026-11-21T04:39:20 end=2026-11-21T04:41:20 rc=0 busy=[WindowServer] gpu=6% +C.write2.r3.completion start=2026-11-21T04:42:01 end=2026-11-21T04:42:24 rc=0 busy=[WindowServer] gpu=7% +C.write2.r3.cache start=2026-11-21T04:43:04 end=2026-11-21T04:43:22 rc=0 busy=[WindowServer] gpu=8% +C.write2.r3.ngram start=2026-11-21T04:44:02 end=2026-11-21T04:44:17 rc=0 busy=[WindowServer] gpu=6% +C.write2.r3.mtp3 start=2026-11-21T04:44:57 end=2026-11-21T04:45:08 rc=0 busy=[WindowServer] gpu=1% +C.explain2.r3.vx start=2026-11-21T04:45:58 end=2026-11-21T04:47:52 rc=0 busy=[WindowServer] gpu=1% +C.explain2.r3.vxdraft7 start=2026-11-21T04:48:42 end=2026-11-21T04:50:35 rc=0 busy=[WindowServer] gpu=1% +C.explain2.r3.completion start=2026-11-21T04:51:15 end=2026-11-21T04:51:42 rc=0 busy=[WindowServer] gpu=8% +C.explain2.r3.cache start=2026-11-21T04:52:42 end=2026-11-21T04:53:01 rc=0 busy=[WindowServer] gpu=1% +C.explain2.r3.ngram start=2026-11-21T04:53:42 end=2026-11-21T04:54:00 rc=0 busy=[WindowServer] gpu=1% +C.explain2.r3.mtp3 start=2026-11-21T04:54:41 end=2026-11-21T04:54:55 rc=0 busy=[WindowServer] gpu=1% +C.edit3.r3.vx start=2026-11-21T04:55:45 end=2026-11-21T04:57:29 rc=0 busy=[WindowServer] gpu=1% +C.edit3.r3.vxdraft7 start=2026-11-21T04:58:09 end=2026-11-21T05:00:08 rc=0 busy=[WindowServer] gpu=6% +C.edit3.r3.completion start=2026-11-21T05:00:49 end=2026-11-21T05:01:16 rc=0 busy=[launchd] gpu=1% +C.edit3.r3.cache start=2026-11-21T05:01:56 end=2026-11-21T05:02:08 rc=0 busy=[WindowServer] gpu=1% +C.edit3.r3.ngram start=2026-11-21T05:02:58 end=2026-11-21T05:03:09 rc=0 busy=[WindowServer] gpu=1% +C.edit3.r3.mtp3 start=2026-11-21T05:03:49 end=2026-11-21T05:04:03 rc=0 busy=[WindowServer] gpu=1% +C.complete3.r3.vx start=2026-11-21T05:04:43 end=2026-11-21T05:06:36 rc=0 busy=[WindowServer] gpu=1% +C.complete3.r3.vxdraft7 start=2026-11-21T05:07:16 end=2026-11-21T05:09:08 rc=0 busy=[WindowServer] gpu=8% +C.complete3.r3.completion start=2026-11-21T05:09:58 end=2026-11-21T05:10:25 rc=0 busy=[WindowServer] gpu=1% +C.complete3.r3.cache start=2026-11-21T05:11:05 end=2026-11-21T05:11:20 rc=0 busy=[WindowServer] gpu=8% +C.complete3.r3.ngram start=2026-11-21T05:12:00 end=2026-11-21T05:12:20 rc=0 busy=[WindowServer] gpu=5% +C.complete3.r3.mtp3 start=2026-11-21T05:13:00 end=2026-11-21T05:13:14 rc=0 busy=[WindowServer] gpu=5% +C.write3.r3.vx start=2026-11-21T05:13:54 end=2026-11-21T05:15:55 rc=0 busy=[WindowServer] gpu=1% +C.write3.r3.vxdraft7 start=2026-11-21T05:16:46 end=2026-11-21T05:18:35 rc=0 busy=[WindowServer] gpu=1% +C.write3.r3.completion start=2026-11-21T05:19:15 end=2026-11-21T05:19:38 rc=0 busy=[WindowServer] gpu=6% +C.write3.r3.cache start=2026-11-21T05:20:18 end=2026-11-21T05:20:33 rc=0 busy=[launchd] gpu=11% +C.write3.r3.ngram start=2026-11-21T05:21:13 end=2026-11-21T05:21:29 rc=0 busy=[WindowServer] gpu=8% +C.write3.r3.mtp3 start=2026-11-21T05:22:09 end=2026-11-21T05:22:19 rc=0 busy=[WindowServer] gpu=8% +C.explain3.r3.vx start=2026-11-21T05:22:59 end=2026-11-21T05:24:53 rc=0 busy=[WindowServer] gpu=1% +C.explain3.r3.vxdraft7 start=2026-11-21T05:25:44 end=2026-11-21T05:27:38 rc=0 busy=[mdworker_shared] gpu=1% +C.explain3.r3.completion start=2026-11-21T05:28:19 end=2026-11-21T05:28:45 rc=0 busy=[launchd] gpu=6% +C.explain3.r3.cache start=2026-11-21T05:29:25 end=2026-11-21T05:29:46 rc=0 busy=[WindowServer] gpu=6% +C.explain3.r3.ngram start=2026-11-21T05:30:26 end=2026-11-21T05:30:44 rc=0 busy=[WindowServer] gpu=11% +C.explain3.r3.mtp3 start=2026-11-21T05:31:24 end=2026-11-21T05:31:40 rc=0 busy=[WindowServer] gpu=7% +done 2026-11-21T05:31:40 diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/logs.tar.xz b/docs/benchmarks/2026-11-20-qwen36-m4/logs.tar.xz new file mode 100644 index 0000000..9e384e8 Binary files /dev/null and b/docs/benchmarks/2026-11-20-qwen36-m4/logs.tar.xz differ diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/make_prompts.py b/docs/benchmarks/2026-11-20-qwen36-m4/make_prompts.py new file mode 100755 index 0000000..4539cca --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/make_prompts.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +"""Write the prompts of this benchmark into prompts/ beside this script. + + python3 make_prompts.py MODEL_DIR VX_CHECKOUT + +MODEL_DIR is the Hugging Face folder of Qwen3.6-35B-A3B. VX_CHECKOUT is a clone of the Vx +repository. The script reads its files at two commits with `git show`, so the clone can be at any +commit. + +- context/ctxN.txt: the first N tokens of the sources of this app, at QWEN_VX_COMMIT. +- twelve/: the 12 prompts of scripts/make_draft_prompts.py, on Vx at TWELVE_COMMIT. Table T of + run.sh chooses the draft lengths with these prompts. +- heldout/: 12 other prompts of the same 4 kinds, on Vx at HELDOUT_COMMIT. The benchmark chooses + no setting with them. + +The prompts of twelve/ and heldout/ are chat text, as the chat template of Qwen3.6 writes it with +enable_thinking=false. The script checks this against the template. Each prompt is in vx/ and in +llama/. The -f option of llama.cpp drops the last new line of a file, so the llama/ copy has one +more new line at the end. prompts/tokens.csv gives the number of tokens of each prompt. + +Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +See LICENSE for license information. +SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +""" + +import csv +import pathlib +import subprocess +import sys + +HERE = pathlib.Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parents[2] / "scripts")) +import make_draft_prompts # noqa: E402 + +CONTEXTS = [64, 512, 2048, 8192, 16384, 32768] +QWEN_VX_COMMIT = "8b12928" +TWELVE_COMMIT = "7fb49be57" +HELDOUT_COMMIT = "9d7cf3a49" + + +class GitTree: + """The files of `repo` at `commit`, with the `/` and `read_text` of a pathlib.Path.""" + + def __init__(self, repo, commit, rel=""): + self.repo, self.commit, self.rel = repo, commit, rel + + def __truediv__(self, rel): + return GitTree(self.repo, self.commit, f"{self.rel}/{rel}" if self.rel else rel) + + def read_text(self): + cmd = ["git", "-C", str(self.repo), "show", f"{self.commit}:{self.rel}"] + return subprocess.run(cmd, check=True, capture_output=True, text=True).stdout + + +def chat(user): + return f"<|im_start|>user\n{user}<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" + + +def heldout_prompts(vx): + """12 prompts of the same kinds as those of make_draft_prompts.py, on other files and tasks.""" + + def source(rel): + return (vx / rel).read_text() + + def head(rel, share=0.6): + lines = source(rel).splitlines(keepends=True) + return "".join(lines[: int(len(lines) * share)]) + + def fenced(rel, text): + lang = {"py": "python", "rs": "rust", "c": "c"}[rel.rsplit(".", 1)[1]] + return f"`{rel}`:\n\n```{lang}\n{text}```" + + edit = "Output the whole file, and change nothing else." + complete = ( + "This file stops in the middle. Continue it from exactly where it stops. " + "Output only the rest of the file." + ) + explain = "Explain what this code does, function by function." + e1 = "scripts/tools/differential_fuzz/generators/tensors.py" + e2 = "src/hir/check/host_waits.rs" + e3 = "utils/memalg/measure_link.c" + return { + "edit1": f"{fenced(e1, source(e1))}\n\nAdd a type hint to every function parameter and return value. {edit}", + "edit2": f"{fenced(e2, source(e2))}\n\nAdd a `///` doc comment above every function that has none. {edit}", + "edit3": f"{fenced(e3, source(e3))}\n\nAdd a one-line comment above every function that says what it does. {edit}", + "complete1": f"{fenced('src/hir/flatten/affine.rs', head('src/hir/flatten/affine.rs'))}\n\n{complete}", + "complete2": f"{fenced('utils/memalg/shakedown.py', head('utils/memalg/shakedown.py'))}\n\n{complete}", + "complete3": f"{fenced('stdlib/rust_core/src/io.rs', head('stdlib/rust_core/src/io.rs'))}\n\n{complete}", + "write1": "Write a Python function merge_intervals(intervals) that merges overlapping closed intervals " + "and returns them sorted. Add pytest tests for it, with empty input and touching intervals.", + "write2": "Write a C function `void reverse_words(char *s)` that reverses the order of the words in a " + "string in place, with single spaces between words. Add a main() that tests it.", + "write3": "Write a Rust struct Trie with new, insert, contains and starts_with for lowercase ASCII words. " + "Add unit tests.", + "explain1": f"{fenced('src/hir/places.rs', source('src/hir/places.rs'))}\n\n{explain}", + "explain2": f"{fenced('src/hir/check/drop_waits.rs', source('src/hir/check/drop_waits.rs'))}\n\n{explain}", + "explain3": f"{fenced('src/hir/decl_check/bounds.rs', source('src/hir/decl_check/bounds.rs'))}\n\n{explain}", + } + + +def app_sources(): + """The .vx files of src/ at QWEN_VX_COMMIT, one after the other, model.vx first.""" + repo = HERE.parents[2] + cmd = ["git", "-C", str(repo), "ls-tree", "--name-only", QWEN_VX_COMMIT, "src/"] + names = subprocess.run(cmd, check=True, capture_output=True, text=True).stdout.split() + names = sorted((n for n in names if n.endswith(".vx")), key=lambda n: (n != "src/model.vx", n)) + tree = GitTree(repo, QWEN_VX_COMMIT) + return "".join((tree / n).read_text() for n in names) + + +def first_tokens(tok, text, n): + """The text of the first n tokens of `text`. Asserts that this text has exactly those tokens.""" + ids = tok.encode(text, add_special_tokens=False).ids + assert len(ids) >= n, f"the sources have only {len(ids)} tokens, fewer than {n}" + cut = tok.decode(ids[:n], skip_special_tokens=False) + assert tok.encode(cut, add_special_tokens=False).ids == ids[:n], f"the first {n} tokens do not encode back to themselves" + return cut + + +def check_chat_format(model_dir, user): + from transformers import AutoTokenizer + + t = AutoTokenizer.from_pretrained(model_dir) + messages = [{"role": "user", "content": user}] + want = t.apply_chat_template(messages, tokenize=False, add_generation_prompt=True, enable_thinking=False) + assert chat(user) == want, f"the chat text differs from the template of {model_dir}:\n{want!r}" + + +def main(): + if len(sys.argv) != 3: + sys.exit(__doc__.split("\n\n")[1]) + from tokenizers import Tokenizer + + model_dir, vx = pathlib.Path(sys.argv[1]).expanduser(), pathlib.Path(sys.argv[2]).expanduser() + tok = Tokenizer.from_file(str(model_dir / "tokenizer.json")) + out = HERE / "prompts" + texts = {} + sources = app_sources() + for n in CONTEXTS: + texts[f"context/ctx{n}"] = first_tokens(tok, sources, n) + twelve = make_draft_prompts.prompts(GitTree(vx, TWELVE_COMMIT)) + check_chat_format(model_dir, twelve["write1"]) + for name, user in twelve.items(): + texts[f"twelve/{name}"] = chat(user) + for name, user in heldout_prompts(GitTree(vx, HELDOUT_COMMIT)).items(): + texts[f"heldout/{name}"] = chat(user) + rows = [] + for key, text in texts.items(): + kind, name = key.split("/") + for side, extra in (("vx", ""), ("llama", "\n")): + path = out / kind / side / f"{name}.txt" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text + extra) + rows.append({"prompt": key, "tokens": len(tok.encode(text, add_special_tokens=False).ids)}) + with open(out / "tokens.csv", "w", newline="") as f: + w = csv.DictWriter(f, ["prompt", "tokens"]) + w.writeheader() + w.writerows(rows) + print(len(texts), "prompts in", out) + + +if __name__ == "__main__": + main() diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/parse.py b/docs/benchmarks/2026-11-20-qwen36-m4/parse.py new file mode 100755 index 0000000..3a5ee85 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/parse.py @@ -0,0 +1,396 @@ +#!/usr/bin/env python3 +"""Read the logs of run.sh, and write runs.csv and summary.md. + + python3 parse.py OUT + python3 parse.py OUT --choose + +OUT is the folder that run.sh wrote. The token counts of the prompts come from prompts/tokens.csv. +A number is missing from a row when its log does not have it, for example after a failed run. +With --choose, the script prints the fastest draft length of each program in table T, as +DRAFT=… MTP_N=…, for run.sh. + +Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +See LICENSE for license information. +SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +""" + +import csv +import math +import re +import statistics +import sys +from collections import defaultdict +from pathlib import Path + +HERE = Path(__file__).resolve().parent +PROGRAMS = { + "vx": "qwen-vx", + "vxdraft": "qwen-vx --draft", + "completion": "llama-completion", + "cache": "llama.cpp ngram-cache", + "ngram": "llama.cpp ngram-mod", + "mtp": "llama.cpp draft-mtp", +} +# The variable of run.sh that takes the chosen draft length of each program. +CHOICES = {"vxdraft": "DRAFT", "mtp": "MTP_N"} +KINDS = ["edit", "complete", "write", "explain"] +SETS = {"T": "twelve", "C": "heldout"} + + +def num(pattern, text, cast=float): + m = re.search(pattern, text) + return cast(m[1]) if m else None + + +def parse_log(program, text): + """The numbers of one log. Times are in ms.""" + r = {} + if program.startswith("vx"): + r["ms_per_token"] = num(r"time ms_per_token=([0-9.]+)", text) + r["prompt_ms_per_token"] = num(r"time prompt_ms_per_token=([0-9.]+)", text) + r["prompt_runs_ms"] = [float(x) for x in re.findall(r"time prompt_ms=([0-9.]+)", text)] + m = re.search(r"rounds=(\d+) drafted=(\d+) accepted=(\d+)", text) + if m: + r["checks"], r["drafted"], r["accepted"] = int(m[1]), int(m[2]), int(m[3]) + elif program == "completion": + perf = r"common_perf_print: *" + r["ms_per_token"] = num(perf + r"eval time = *[0-9.]+ ms / *\d+ runs *\( *([0-9.]+) ms per token", text) + r["timed_tokens"] = num(perf + r"eval time = *[0-9.]+ ms / *(\d+) runs", text, int) + r["prompt_ms"] = num(perf + r"prompt eval time = *([0-9.]+) ms", text) + r["llama_prompt_tokens"] = num(perf + r"prompt eval time = *[0-9.]+ ms / *(\d+) tokens", text, int) + else: # llama-speculative-simple + m = re.search(r"decoded +(\d+) tokens in +([0-9.]+) seconds", text) + if m: + r["timed_tokens"] = int(m[1]) + r["ms_per_token"] = float(m[2]) * 1000 / int(m[1]) + m = re.search(r"encoded +(\d+) tokens in +([0-9.]+) seconds", text) + if m: + r["llama_prompt_tokens"], r["prompt_ms"] = int(m[1]), float(m[2]) * 1000 + r["drafted"] = num(r"n_drafted *= *(\d+)", text, int) + r["accepted"] = num(r"n_accept *= *(\d+)", text, int) + if not program.startswith("vx"): + r["threads"] = num(r"n_threads = (\d+)", text, int) + return r + + +LOG_LINE = re.compile(r"\d+\.\d+\.\d+\.\d+ [A-Z] ") + + +def answer(path): + """The text that a program wrote after the chat prompt, without the lines of times and drafts.""" + lines = path.read_text(errors="replace").split("\n") + start = next((i + 2 for i, line in enumerate(lines) if line == ""), None) + assert start is not None, f"{path} has no chat prompt" + out = [] + for line in lines[start:]: + if line.startswith("time ") or LOG_LINE.match(line): + break + out.append(re.sub(r"rounds=\d+ drafted=\d+ accepted=\d+;", "", line)) + return "\n".join(out).rstrip("\n") + + +def agree(a, b): + """The number of characters at the start of a and b that are the same.""" + n = 0 + while n < min(len(a), len(b)) and a[n] == b[n]: + n += 1 + return n + + +def read_rows(out): + tokens = {row["prompt"]: int(row["tokens"]) for row in csv.DictReader(open(HERE / "prompts" / "tokens.csv"))} + meta = {} + for line in open(out / "log.txt"): + m = re.match(r"(\S+) start=(\S+) end=(\S+) rc=(\d+) busy=\[(.*)\] gpu=(\d*)%", line) + if m: + meta[m[1]] = dict(start=m[2], end=m[3], rc=int(m[4]), busy=m[5], gpu=m[6]) + fa = re.search(r"flash attention:.*chosen: (\w+)", (out / "env.txt").read_text()) + rows = [] + for name, m in sorted(meta.items()): + if name.startswith("llama-bench"): + continue + parts = name.split(".") + setting = "" + if name.startswith("fa-"): # fa-on.ctx2048.r1 + table, prompt, rnd, program = "fa", f"context/{parts[1]}", parts[2], "completion" + elif parts[0] in ("A", "P"): # A.vx.ctx512.r1 + table, prompt, rnd = parts[0], f"context/{parts[2]}", parts[3] + program = "vx" if parts[1] == "vx" else "completion" + else: # T.edit1.r1.vxdraft7 + table, prompt, rnd = parts[0], f"{SETS[parts[0]]}/{parts[1]}", parts[2] + program, setting = re.fullmatch(r"([a-z]+)(\d*)", parts[3]).groups() + text = (out / "logs" / f"{name}.txt").read_text(errors="replace") + r = parse_log(program, text) + n = tokens[prompt] + if r.get("prompt_ms_per_token") is not None: + r["prompt_ms"] = r["prompt_ms_per_token"] * n + runs = r.get("prompt_runs_ms") or [] + flash = parts[0][3:] if table == "fa" else (fa[1] if fa and not program.startswith("vx") else "") + rows.append(dict( + table=table, prompt=prompt, kind=re.sub(r"\d", "", prompt.split("/")[1]), round=rnd[1:], + program=PROGRAMS[program], setting=setting, prompt_tokens=n, + llama_prompt_tokens=r.get("llama_prompt_tokens"), prompt_ms=r.get("prompt_ms"), + first_prompt_ms=runs[0] if runs else None, later_prompt_ms=" ".join(f"{x:.1f}" for x in runs[1:]), + ms_per_token=r.get("ms_per_token"), timed_tokens=r.get("timed_tokens"), checks=r.get("checks"), + drafted=r.get("drafted"), accepted=r.get("accepted"), flash_attn=flash, threads=r.get("threads"), + errors=len(re.findall(r"^\d+\.\d+\.\d+\.\d+ E ", text, re.M)), + log=f"logs/{name}.txt", **m, + )) + return rows + + +def write_csv(out, rows): + with open(out / "runs.csv", "w", newline="") as f: + w = csv.DictWriter(f, list(rows[0].keys()), lineterminator="\n") + w.writeheader() + for r in rows: + w.writerow({k: (f"{v:.4f}" if isinstance(v, float) else v) for k, v in r.items()}) + + +def geomean(xs): + return math.exp(sum(math.log(x) for x in xs) / len(xs)) + + +def spread(xs, fmt="{:.2f}"): + """The median, and the fastest and the slowest run.""" + return f"{fmt.format(statistics.median(xs))} ({fmt.format(min(xs))}-{fmt.format(max(xs))})" + + +def timed(rows, table, program=None, setting=None): + """The runs of the summary: no failed runs, no runs with error lines, and no runs of qwen-vx --draft + that wrote other text than qwen-vx. The summary keeps the runs of llama.cpp with drafts that wrote + other text: the shape of their batches changes the result at near ties. say_same_text lists them.""" + return [r for r in rows if r["table"] == table and r["rc"] == 0 and r["ms_per_token"] is not None + and not r["errors"] and not (r["program"] == PROGRAMS["vxdraft"] and r.get("same_text") is False) + and (program is None or r["program"] == program) and (setting is None or r["setting"] == setting)] + + +def tuning(rows): + """For each program and draft length of table T: the geometric mean over the prompts, if it ran on all.""" + prompts = {r["prompt"] for r in rows if r["table"] == "T"} + means = {} + for key in {(r["program"], r["setting"]) for r in timed(rows, "T")}: + rr = timed(rows, "T", *key) + if {r["prompt"] for r in rr} == prompts: + means[key] = geomean([r["ms_per_token"] for r in rr]) + return means + + +def choose(rows): + means = tuning(rows) + words = [] + for program, variable in CHOICES.items(): + options = {s: v for (p, s), v in means.items() if p == PROGRAMS[program]} + assert options, f"table T has no complete set of runs of {PROGRAMS[program]}" + words.append(f"{variable}={min(options, key=options.get)}") + return " ".join(words) + + +def plain_log(r): + """The log of the run without drafts of the same program, prompt and round, for a run with drafts.""" + if r["table"] not in SETS or r["program"] in (PROGRAMS["vx"], PROGRAMS["completion"]): + return None + plain = "vx" if r["program"] == PROGRAMS["vxdraft"] else "completion" + return re.sub(r"\.[a-z]+\d*\.txt$", f".{plain}.txt", r["log"]) + + +def mark_same_text(out, rows): + """Whether each run with drafts wrote the text of the run without drafts. qwen-vx --draft must + write the same text. A program of llama.cpp may generate a few more tokens with drafts, so its + text must start with the whole text of llama-completion. same_chars is the number of equal + characters at the start of the two texts.""" + for r in rows: + r["same_text"] = r["same_chars"] = "" + log = plain_log(r) + if log is None or r["rc"] != 0 or not (out / log).exists(): + continue + a, b = answer(out / log), answer(out / r["log"]) + r["same_text"] = a == b if r["program"] == PROGRAMS["vxdraft"] else b.startswith(a) + r["same_chars"] = agree(a, b) + + +def say_same_text(say, rows, table): + for p in PROGRAMS.values(): + rr = [r for r in rows if r["table"] == table and r["program"] == p and r["same_text"] != ""] + if rr: + vx = p == PROGRAMS["vxdraft"] + plain = "qwen-vx" if vx else "llama-completion" + differ = [r for r in rr if not r["same_text"]] + say(f"- {p}: the text of {plain} in {len(rr) - len(differ)} of {len(rr)} runs" + + (f". Other text, {'out of' if vx else 'in'} the summary (the number of equal characters " + f"at the start): " + ", ".join(f"{r['log']} ({r['same_chars']})" for r in differ) + if differ else "")) + + +def summary(out, rows): + lines = [] + say = lines.append + bad = [r["log"] for r in rows if r["rc"] != 0] + if bad: + say("Failed runs: " + ", ".join(bad)) + say("") + errors = [r["log"] for r in rows if r["errors"]] + if errors: + say("Runs with error lines, out of the summary: " + ", ".join(errors)) + say("") + wrong = sorted({r["prompt"] for r in rows if r["llama_prompt_tokens"] not in (None, r["prompt_tokens"])}) + if wrong: + say("llama.cpp read another number of tokens for: " + ", ".join(wrong)) + say("") + # Each start of run.sh adds these lines to env.txt. Show each line once. + lines += dict.fromkeys(line.strip() for line in open(out / "env.txt") + if line.startswith(("flash attention:", "draft lengths"))) + say("") + + say("## Table A: generated tokens after a prompt") + say("") + say("ms for each generated token: the median of the runs, and the fastest and slowest run. The prompt time " + "is that of the first prompt of a process.") + say("") + say("| Prompt tokens | qwen-vx ms | llama.cpp ms | qwen-vx tok/s | llama.cpp tok/s | llama.cpp ms / qwen-vx ms " + "| qwen-vx prompt ms | llama.cpp prompt ms |") + say("| ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |") + for prompt in sorted({r["prompt"] for r in rows if r["table"] == "A"}, key=lambda p: int(p.split("ctx")[1])): + a = [r for r in timed(rows, "A", "qwen-vx") if r["prompt"] == prompt] + b = [r for r in timed(rows, "A", "llama-completion") if r["prompt"] == prompt] + if not a or not b: + continue + ma, mb = statistics.median(r["ms_per_token"] for r in a), statistics.median(r["ms_per_token"] for r in b) + pa = [r["prompt_ms"] for r in a if r["prompt_ms"] is not None] + pb = [r["prompt_ms"] for r in b if r["prompt_ms"] is not None] + say(f"| {a[0]['prompt_tokens']:,} | {spread([r['ms_per_token'] for r in a])} " + f"| {spread([r['ms_per_token'] for r in b])} | {1000 / ma:.1f} | {1000 / mb:.1f} | {mb / ma:.3f} " + f"| {spread(pa, '{:.0f}') if pa else ''} | {spread(pb, '{:.0f}') if pb else ''} |") + say("") + + say("## Table P: the prompt") + say("") + say("Tokens of the prompt each second: the median of the runs, and the slowest and fastest run. qwen-vx ran " + "the prompt several times in one process. The first run includes the first launch of each kernel. " + "llama-completion ran the prompt once, after its warm-up.") + say("") + say("| Prompt tokens | qwen-vx first run | qwen-vx later runs | llama-completion |") + say("| ---: | ---: | ---: | ---: |") + for prompt in sorted({r["prompt"] for r in rows if r["table"] == "P"}, key=lambda p: int(p.split("ctx")[1])): + ok = [r for r in rows if r["table"] == "P" and r["rc"] == 0 and r["prompt"] == prompt] + n = ok[0]["prompt_tokens"] if ok else 0 + first = [n * 1000 / r["first_prompt_ms"] for r in ok if r["program"] == "qwen-vx" and r["first_prompt_ms"]] + later = [n * 1000 / float(x) for r in ok if r["program"] == "qwen-vx" for x in r["later_prompt_ms"].split()] + llama = [n * 1000 / r["prompt_ms"] for r in ok if r["program"] == "llama-completion" and r["prompt_ms"]] + say(f"| {n:,} | {spread(first, '{:.0f}') if first else ''} | {spread(later, '{:.0f}') if later else ''} " + f"| {spread(llama, '{:.0f}') if llama else ''} |") + say("") + + means = tuning(rows) + if means: + say("## Table T: draft lengths, on the 12 tuning prompts") + say("") + say("ms for each generated token: the geometric mean over the 12 prompts, one run each.") + say("") + say("| Program | Draft length | ms | accepted / drafted |") + say("| --- | ---: | ---: | ---: |") + for (program, setting), v in sorted(means.items(), key=lambda kv: (kv[0][0], int(kv[0][1] or 0))): + rr = timed(rows, "T", program, setting) + acc, dr = sum(r["accepted"] or 0 for r in rr), sum(r["drafted"] or 0 for r in rr) + say(f"| {program} | {setting} | {v:.2f} | {f'{acc} / {dr} ({100 * acc / dr:.0f}%)' if dr else ''} |") + say("") + say_same_text(say, rows, "T") + say("") + + programs = [p for p in PROGRAMS.values() if timed(rows, "C", p)] + if programs: + say("## Table C: the 12 held-out prompts") + say("") + say("ms for each generated token: the geometric mean over the prompts of each kind, and the fastest and " + "slowest run.") + say("") + say("| Kind | Prompt tokens | " + " | ".join(programs) + " |") + say("| --- | --- | " + " | ".join("---:" for _ in programs) + " |") + for kind in KINDS + [None]: + cells = [] + for p in programs: + xs = [r["ms_per_token"] for r in timed(rows, "C", p) if kind is None or r["kind"] == kind] + cells.append(f"{geomean(xs):.2f} ({min(xs):.2f}-{max(xs):.2f})" if xs else "") + counts = sorted({r["prompt_tokens"] for r in timed(rows, "C", "qwen-vx") if r["kind"] == kind}) + say(f"| {kind or 'all 12'} | {', '.join(map(str, counts))} | " + " | ".join(cells) + " |") + say("") + mean = {} + for p in programs: + by = defaultdict(list) + for r in timed(rows, "C", p): + by[r["prompt"]].append(r["ms_per_token"]) + mean[p] = {k: statistics.mean(v) for k, v in by.items()} + + def compare(a, b): + ks = [k for k in mean.get(a, {}) if k in mean.get(b, {})] + ratios = [mean[b][k] / mean[a][k] for k in ks] + if ratios: + say(f"- {a} against {b}: {geomean(ratios):.3f}, faster on {sum(x > 1 for x in ratios)} of " + f"{len(ratios)} prompts ({min(ratios):.2f} to {max(ratios):.2f})") + + compare("qwen-vx", "llama-completion") + for p in programs: + if p != "qwen-vx --draft": + compare("qwen-vx --draft", p) + for p in programs: + if p.startswith("llama.cpp "): + compare(p, "llama-completion") + say("") + say("### Drafts, table C, round 1") + say("") + drafters = [p for p in programs if p not in ("qwen-vx", "llama-completion")] + say("| Kind | " + " | ".join(f"{p} accepted / drafted" for p in drafters) + " |") + say("| --- | " + " | ".join("---:" for _ in drafters) + " |") + for kind in KINDS + [None]: + cells = [] + for p in drafters: + rr = [r for r in timed(rows, "C", p) if r["round"] == "1" and (kind is None or r["kind"] == kind)] + acc, dr = sum(r["accepted"] or 0 for r in rr), sum(r["drafted"] or 0 for r in rr) + checks = sum(r["checks"] or 0 for r in rr) + cells.append((f"{acc} / {dr} ({100 * acc / dr:.0f}%)" if dr else "") + + (f", {acc / checks:.2f} per check" if checks else "")) + say(f"| {kind or 'all 12'} | " + " | ".join(cells) + " |") + say("") + say_same_text(say, rows, "C") + say("") + say("### qwen-vx and llama-completion: where the text starts to differ") + say("") + say("The characters at the start of the generated text that are the same, round 1. The weight files " + "differ in the token embedding and the output matrix, so the greedy text of the two programs can differ.") + say("") + say("| Prompt | Same characters | Characters of llama-completion |") + say("| --- | ---: | ---: |") + for prompt in sorted({r["prompt"] for r in rows if r["table"] == "C"}): + pair = {r["program"]: r for r in rows if r["table"] == "C" and r["prompt"] == prompt and r["round"] == "1" + and r["rc"] == 0} + if PROGRAMS["vx"] in pair and PROGRAMS["completion"] in pair: + a = answer(out / pair[PROGRAMS["completion"]]["log"]) + say(f"| {prompt.split('/')[1]} | {agree(a, answer(out / pair[PROGRAMS['vx']]['log']))} | {len(a)} |") + say("") + + for name in ("llama-bench-pp", "llama-bench-tg"): + path = out / "logs" / f"{name}.txt" + if path.exists(): + say(f"## {name}") + say("") + lines += [line for line in path.read_text().splitlines() if line.startswith("|")] + say("") + (out / "summary.md").write_text("\n".join(lines) + "\n") + print("\n".join(lines)) + + +def main(): + if len(sys.argv) not in (2, 3) or sys.argv[2:] not in ([], ["--choose"]): + sys.exit(__doc__.split("\n\n")[1]) + out = Path(sys.argv[1]) + rows = read_rows(out) + mark_same_text(out, rows) + if sys.argv[2:] == ["--choose"]: + print(choose(rows)) + return + write_csv(out, rows) + summary(out, rows) + + +if __name__ == "__main__": + main() diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/perplexity.py b/docs/benchmarks/2026-11-20-qwen36-m4/perplexity.py new file mode 100755 index 0000000..95f1272 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/perplexity.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +"""Perplexity of the two weight sets of the Qwen3.6 benchmark, with one program: scripts/reference.py. + + python3 perplexity.py APP.vxw MODEL.gguf QWEN_VX/scripts LLAMA/gguf-py HF_MODEL_DIR TEXT... [--max-tokens N] + +The app's weight file and the GGUF hold the same Q4_0 matrices. They differ in the token +embedding (bf16 against Q4_0) and the output matrix (6-bit codes against Q6_K). The llama.cpp set +is the app's file with these two tensors taken from the GGUF, as float32. For each text, the script +prints the perplexity of each set, the mean KL divergence of the llama.cpp set from the app set, +and how often the two sets give the same most likely next token. + +Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +See LICENSE for license information. +SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +""" +import argparse +import sys +import time + +import numpy as np + +p = argparse.ArgumentParser() +p.add_argument("vxw") +p.add_argument("gguf") +p.add_argument("qwen_scripts") +p.add_argument("gguf_py") +p.add_argument("hf_dir") +p.add_argument("texts", nargs="+") +p.add_argument("--max-tokens", type=int, default=512) +args = p.parse_args() +sys.path.insert(0, args.qwen_scripts) +sys.path.insert(0, args.gguf_py) +import reference # noqa: E402 +from gguf import GGUFReader # noqa: E402 +from gguf.quants import dequantize # noqa: E402 +from tokenizers import Tokenizer # noqa: E402 + +app = reference.Model(args.vxw) +llama = reference.Model(args.vxw) +theirs = {t.name: t for t in GGUFReader(args.gguf).tensors} +for ours, name in (("embed", "token_embd.weight"), ("lm_head", "output.weight")): + t = theirs[name] + values = dequantize(np.asarray(t.data), t.tensor_type).astype(np.float32) + want = app.tensors[ours][1].shape[0], app.config["hidden_size"] + values = values.reshape(want) + llama.tensors[ours] = ("f32", values) + print(f"{ours}: {t.tensor_type.name} from the GGUF, {values.shape}", flush=True) + +tokenizer = Tokenizer.from_file(f"{args.hf_dir}/tokenizer.json") + + +def log_softmax(logits): + logits = logits.astype(np.float64) + logits -= logits.max(axis=-1, keepdims=True) + return logits - np.log(np.exp(logits).sum(axis=-1, keepdims=True)) + + +for path in args.texts: + tokens = tokenizer.encode(open(path).read()).ids[: args.max_tokens] + out = {} + for label, model in (("app", app), ("llama.cpp", llama)): + start = time.time() + out[label] = log_softmax(reference.forward(model, tokens, reference.Cache(model.config))) + print(f"{path}: {label} forward of {len(tokens)} tokens in {time.time() - start:.0f} s", flush=True) + next_tokens = np.asarray(tokens[1:]) + rows = np.arange(len(tokens) - 1) + a, b = out["app"][:-1], out["llama.cpp"][:-1] + ppl = {k: float(np.exp(-v[:-1][rows, next_tokens].mean())) for k, v in out.items()} + kl = float((np.exp(a) * (a - b)).sum(axis=-1).mean()) + top1 = float((a.argmax(axis=-1) == b.argmax(axis=-1)).mean()) + print(f"{path}: tokens={len(tokens)} perplexity app={ppl['app']:.4f} llama.cpp={ppl['llama.cpp']:.4f} " + f"kl={kl:.6f} same_top1={100 * top1:.2f}%", flush=True) diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/llama/ctx16384.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/llama/ctx16384.txt new file mode 100644 index 0000000..86bc604 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/llama/ctx16384.txt @@ -0,0 +1,902 @@ +//===- model.vx - Qwen app --------------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// One token of a Qwen2 or Qwen3 MoE decoder on the GPU, with the kernels of `std::nn`. `State` +// holds every tensor that a token writes, and the KV cache. It is made once, before the first +// token, so the token loop allocates nothing. +import core::convert; +import core::num; +import std::nn; +import std::vec; +import qwen::attention; +import qwen::products; +import qwen::q6; +import qwen::weights; + +/// The keys and the values of every position so far, for one layer: [max_seq, kv_heads, head_dim]. +/// They are f16, half the memory of f32. The kernels compute in f32, and round only what they +/// store here. +struct Cache { + k : Tensor, + v : Tensor, +} + +/// The tensors of a mixture-of-experts layer: the router's score of each expert, the chosen +/// experts and their weights, and the SwiGLU output of each chosen expert, [experts_per_token, +/// moe_intermediate_size]. +struct Experts { + router_logits : Tensor, + ids : Tensor, + weights : Tensor, + mlp : Tensor, +} + +/// The tensors that a token writes, in GPU memory, and one `Cache` for each layer. `cos` and `sin` +/// are [max_seq, head_dim / 2]. +struct State { + max_seq : i32, + x : Tensor, + xn : Tensor, + q : Tensor, + k : Tensor, + v : Tensor, + q_turned : Tensor, + attended : Tensor, + attention_parts : Tensor, + vec_parts : Tensor, + mlp : Tensor, + experts : Experts, + logits : Tensor, + cos : Tensor, + sin : Tensor, + caches : Vec, +} + +/// The state for up to `max_seq` positions. The angles of RoPE are computed in f64, as in +/// `reference.py`, and rounded to f32 once. +fn new_state(c : &Config, max_seq : i32) -> State { + assert(max_seq > 0 && max_seq <= c.max_positions, "max_seq must be between 1 and the max_positions of the model"); + let half = c.head_dim / 2; + let mut hcos = Tensor([max_seq, half]); + let mut hsin = Tensor([max_seq, half]); + for p in 0..max_seq { + for i in 0..half { + let angle = f64::from(p) / f64::powf(c.rope_theta, f64::from(2 * i) / f64::from(c.head_dim)); + hcos[p][i] = f64::cos(angle) as f32; + hsin[p][i] = f64::sin(angle) as f32; + } + } + // A dense model uses none of the tensors of the experts, so one value each is enough. + let experts = i32::max(c.num_experts, 1); + let chosen = i32::max(c.experts_per_token, 1); + let moe_inter = i32::max(c.moe_intermediate_size, 1); + // The flash attention of a prompt reads the cache in blocks of 64 positions. + let rows = (max_seq + 63) / 64 * 64; + let mut caches = Vec::new(); + for l in 0..c.num_layers { + caches.push(Cache { + k: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + }); + } + return State { + max_seq: max_seq, + x: transfer(Tensor([c.hidden_size]), Memory::HBM), + xn: transfer(Tensor([c.hidden_size]), Memory::HBM), + q: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + k: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + q_turned: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attended: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attention_parts: transfer(split_attention_scratch(max_seq, c.num_q_heads, c.num_kv_heads, c.head_dim), Memory::HBM), + vec_parts: transfer(vec_attention_scratch(c.num_q_heads), Memory::HBM), + mlp: transfer(Tensor([c.intermediate_size]), Memory::HBM), + experts: Experts { + router_logits: transfer(Tensor([experts]), Memory::HBM), + ids: transfer(Tensor([chosen]), Memory::HBM), + weights: transfer(Tensor([chosen]), Memory::HBM), + mlp: transfer(Tensor([chosen, moe_inter]), Memory::HBM), + }, + logits: transfer(Tensor([c.vocab_size]), Memory::HBM), + cos: transfer(hcos, Memory::HBM), + sin: transfer(hsin, Memory::HBM), + caches: caches, + }; +} + +/// y = m x, with the kernel for the dtype of `m`, which has `rows` x `cols` weights. +fn matvec(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U6 { + matvec_q6(y, &m.codes, &m.high, &m.group_scales, x, rows, cols); + } else if m.dtype == U4 { + nn_matvec_q4(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x. +fn matvec_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_matvec_q4_add(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_add(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec_add(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x, for x of [heads, head_dim]. +fn matvec_heads_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, heads : i32, head_dim : i32) -> void { + if m.dtype == U4 { + matvec_q4_heads_add_blocks(y, &m.codes, &m.group_scales, x, rows, heads, head_dim); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_heads_add(y, &m.codes, &m.scales, x, rows, heads, head_dim); + } else { + nn_matvec_heads_add(y, &m.bf16, x, rows, heads, head_dim); + } + return; +} + +/// The Q, K and V of x: m x + b, split by heads. +fn qkv(q : &mut Tensor, k : &mut Tensor, v : &mut Tensor, m : &WeightMatrix, b : &Tensor, x : &Tensor, c : &Config) -> void { + if m.dtype == U4 { + qkv_q4_blocks(q, k, v, &m.codes, &m.group_scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } else if m.dtype == F8E4M3 { + nn_qkv_fp8(q, k, v, &m.codes, &m.scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } else { + nn_qkv(q, k, v, &m.bf16, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } + return; +} + +/// The SwiGLU of a dense MLP, for the gate rows and then the up rows of `m`. +fn swiglu(out : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_swiglu_q4(out, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_swiglu_fp8(out, &m.codes, &m.scales, x, rows, cols); + } else { + nn_swiglu(out, &m.bf16, x, rows, cols); + } + return; +} + +/// The mixture of experts of a layer: the router chooses experts_per_token experts and their +/// weights, and x gets the sum of their outputs for xn, each times its weight. +fn add_experts(e : &mut Experts, x : &mut Tensor, xn : &Tensor, layer : &Layer, c : &Config) -> void { + let k = c.experts_per_token; + let inter = c.moe_intermediate_size; + nn_matvec(&mut e.router_logits, &layer.router, xn, c.num_experts, c.hidden_size); + nn_top_k(&mut e.ids, &mut e.weights, &e.router_logits, c.num_experts, k); + let gate_up = &layer.gate_up; + let down = &layer.down; + if gate_up.dtype == U4 { + moe_swiglu_q4_blocks(&mut e.mlp, &gate_up.codes, &gate_up.group_scales, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + moe_down_q4_add_blocks(x, &down.codes, &down.group_scales, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + } else { + assert(gate_up.dtype == BF16, "the experts of a mixture-of-experts model must be bf16 or Q4_0"); + nn_moe_swiglu(&mut e.mlp, &gate_up.bf16, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + nn_moe_down_add(x, &down.bf16, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + } + return; +} + +/// Runs the token in `token` at position `pos` through every layer. The hidden state of the +/// token is then in `s.x`, and its keys and values are in the caches. +fn run_layers(w : &Weights, s : &mut State, token : &Tensor, pos : i32) -> void { + let c = &w.config; + let eps = c.rms_norm_eps as f32; + assert(pos >= 0 && pos < s.max_seq, "the position is past the end of the KV cache"); + nn_embed(&mut s.x, &w.embed, token, c.hidden_size); + let mut l = 0; + for cache in s.caches.iter_mut() { + let layer = &w.layers[l]; + nn_rms_norm(&mut s.xn, &s.x, &layer.attn_norm, c.hidden_size, eps); + qkv(&mut s.q, &mut s.k, &mut s.v, &layer.qkv, &layer.qkv_bias, &s.xn, c); + if c.qk_norm { + norm_rope_and_store(&mut s.q_turned, &mut cache.k, &mut cache.v, &s.q, &s.k, &s.v, &layer.q_norm, &layer.k_norm, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.head_dim, eps); + } else { + rope_and_store(&mut s.q_turned, &mut cache.k, &mut cache.v, &s.q, &s.k, &s.v, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } + if c.head_dim == 128 { + vec_attention(&mut s.attended, &mut s.vec_parts, &s.q_turned, &cache.k, &cache.v, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } else { + split_attention(&mut s.attended, &mut s.attention_parts, &s.q_turned, &cache.k, &cache.v, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } + matvec_heads_add(&mut s.x, &layer.attn_out, &s.attended, c.hidden_size, c.num_q_heads, c.head_dim); + nn_rms_norm(&mut s.xn, &s.x, &layer.mlp_norm, c.hidden_size, eps); + if c.num_experts > 0 { + add_experts(&mut s.experts, &mut s.x, &s.xn, layer, c); + } else { + swiglu(&mut s.mlp, &layer.gate_up, &s.xn, c.intermediate_size, c.hidden_size); + matvec_add(&mut s.x, &layer.down, &s.mlp, c.hidden_size, c.intermediate_size); + } + l = l + 1; + } + return; +} + +/// The logits of the token whose hidden state is in `s.x`, and in `next` the index of the largest +/// one. Both stay in GPU memory. +fn predict(w : &Weights, s : &mut State, next : &mut Tensor) -> void { + let c = &w.config; + nn_rms_norm(&mut s.xn, &s.x, &w.final_norm, c.hidden_size, c.rms_norm_eps as f32); + if c.tied_embeddings { + nn_matvec(&mut s.logits, &w.embed, &s.xn, c.vocab_size, c.hidden_size); + } else { + matvec(&mut s.logits, &w.lm_head, &s.xn, c.vocab_size, c.hidden_size); + } + nn_argmax(next, &s.logits, c.vocab_size); + return; +} +//===- attention.vx - Qwen app ----------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// The attention of one generated token, with the positions split among blocks. This is a copy of +// `nn_attention` and its kernels from `std::nn` on Vx main (vx-lang/Vx#3216), with `split_` in place +// of `nn_` in their names. Vx v0.0.4 has the older `nn_attention`, which has one block for each head +// of Q, so its time grows with the number of positions. Remove this file, and call `nn_attention` +// of `std::nn`, when a Vx release has the new one (#4). +// +// `vec_attention`, for head_dim 128, has the design of llama.cpp's flash attention for one token +// (kernel_flash_attn_ext_vec and kernel_flash_attn_ext_vec_reduce), MIT License, Copyright (c) 2023-2026 +// The ggml authors. scripts/mlir_kernels/decode_attention.py writes its kernels: change that script, not +// the MLIR. +import core::num; +import std::nn; + +/// Attention of the token at position `pos` over rows 0 to `pos` of the KV cache, with a softmax +/// of the scores q . k / sqrt(head_dim). `part` is scratch space from `split_attention_scratch`. +/// +/// The blocks of the first kernel split the positions, 32 to a block below position 640 and 64 from +/// there on. A block serves the 8 heads of Q that share a head of K and V, so it reads each row of +/// the cache once for all 8. A second kernel merges the parts of the blocks for each head. +fn split_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_heads % kv_heads == 0, "split_attention: q_heads must be a multiple of kv_heads"); + assert(head_dim % 32 == 0 && head_dim <= 128, "split_attention: head_dim must be a multiple of 32, and at most 128"); + let mut n_pos = 32; + if pos >= 640 { + n_pos = 64; + } + assert(part.extent(0) >= kv_heads * ((q_heads / kv_heads + 7) / 8) && part.extent(1) >= (pos + n_pos) / n_pos && part.extent(2) >= 8 && part.extent(3) >= head_dim + 2, "split_attention: `part` is too small for this position. Make it with split_attention_scratch"); + if n_pos == 32 { + split_attention_parts_32(part, q, k_cache, v_cache, pos, q_heads, kv_heads, head_dim); + } else { + split_attention_parts_64(part, q, k_cache, v_cache, pos, q_heads, kv_heads, head_dim); + } + split_attention_merge(out, part, pos, n_pos, q_heads, kv_heads, head_dim); + return; +} + +/// Attention of the token at position `pos`, as `split_attention`, for head_dim 128, with the kernels of +/// llama.cpp's flash attention for one token. `vec_attention_parts` splits the blocks of 32 positions among +/// `nwg` SIMD groups for each head of Q: 32 of them, or 64 when each of 32 would have more than 2 blocks. +/// (llama.cpp goes on to 4 SIMD groups of 32 a block, but 128 parts are no faster here: their merge costs what +/// they save.) `vec_attention_merge` then merges the parts. `part` is scratch space from +/// `vec_attention_scratch`. +fn vec_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_heads % kv_heads == 0 && head_dim == 128, "vec_attention: q_heads must be a multiple of kv_heads, and head_dim 128"); + assert(part.extent(0) >= q_heads && part.extent(1) >= 128 && part.extent(2) == 132, "vec_attention: `part` is too small. Make it with vec_attention_scratch"); + let mut nwg = 32; + if 2 * nwg * 32 < pos + 1 { + nwg = nwg * 2; + } + vec_attention_parts(part, q, k_cache, v_cache, pos, q_heads, q_heads / kv_heads, nwg, 1.0 / (head_dim as f32).sqrt()); + vec_attention_merge(out, part, nwg, q_heads); + return; +} + +/// The scratch space of `vec_attention`, on the CPU: up to 128 parts for each head of Q, each the sum of V +/// (128 values), the largest score, and the sum of the weights. A part has 132 values, so that each starts +/// at a multiple of 16 bytes. +fn vec_attention_scratch(q_heads : i32) -> Tensor { + return Tensor([q_heads, 128, 132]); +} + +/// The parts of `vec_attention`, as llama.cpp's kernel_flash_attn_ext_vec. Block (h, w) is a SIMD group for +/// query head h. It does the blocks of 32 positions w, w + nwg, w + 2 nwg, ... up to `pos`, and writes +/// part[h][w]. Lane l owns values 4 l to 4 l + 3 of the head, so that the 32 lanes read a row of K or V in +/// one 256-byte load. For each row, the lanes add up their parts of q . k; then each lane keeps the score +/// of one row, and the lanes take the weights of the rows from each other for the sum of V. A part is the +/// sum of V, not divided, then the largest score and the sum of the weights. +fn vec_attention_parts(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, group : i32, nwg : i32, scale : f32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for w in 0..nwg across blocks { + let g = h / group; + let _d = mlir!( threads : 32, inputs : (%part = part : memref, %q = q : memref, %k3 = k_cache : memref, %v3 = v_cache : memref, %pos = pos : i32, %nwg = nwg : i32, %scale = scale : f32, %h = h : i32, %w = w : i32, %g = g : i32), returns : i32, dialects : ["arith", "memref", "scf", "gpu", "vector", "math"], ensures : [reads_only(q), reads_only(k_cache), reads_only(v_cache), writes_only(part[h][w])]) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %c4 = arith.constant 4 : index + %c32 = arith.constant 32 : index + %c128 = arith.constant 128 : index + %c129 = arith.constant 129 : index + %c32i = arith.constant 32 : i32 + %neg = arith.constant -3.0e38 : f32 + %zero = arith.constant 0.0 : f32 + %vz4 = arith.constant dense<0.0> : vector<4xf32> + %l = gpu.thread_id x + %l4 = arith.muli %l, %c4 : index + %hi = arith.index_cast %h : i32 to index + %wi = arith.index_cast %w : i32 to index + %gi = arith.index_cast %g : i32 to index + %posi = arith.index_cast %pos : i32 to index + %nwgi = arith.index_cast %nwg : i32 to index + %g128 = arith.muli %gi, %c128 : index + %kd = arith.addi %g128, %l4 : index + %P = memref.dim %k3, %c0 : memref + %KH = memref.dim %k3, %c1 : memref + %Wd = arith.muli %KH, %c128 : index + %k = memref.reinterpret_cast %k3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to memref> + %v = memref.reinterpret_cast %v3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to memref> + %qv = vector.load %q[%hi, %l4] {alignment = 16} : memref, vector<4xf32> + %scv = vector.broadcast %scale : f32 to vector<4xf32> + %qs = arith.mulf %qv, %scv : vector<4xf32> + %nkv = arith.addi %posi, %c32 : index + %chunks = arith.divui %nkv, %c32 : index + %st:3 = scf.for %ic = %wi to %chunks step %nwgi iter_args(%M = %neg, %S = %zero, %o = %vz4) -> (f32, f32, vector<4xf32>) { + %r0 = arith.muli %ic, %c32 : index + %my = scf.for %cc = %c0 to %c32 step %c1 iter_args(%m = %neg) -> (f32) { + %row = arith.addi %r0, %cc : index + %rowc = arith.minui %row, %posi : index + %kh = vector.load %k[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> + %kf = arith.extf %kh : vector<4xf16> to vector<4xf32> + %pr = arith.mulf %kf, %qs : vector<4xf32> + %pl = vector.reduction , %pr : vector<4xf32> into f32 + %sc = gpu.subgroup_reduce add %pl : (f32) -> f32 + %live = arith.cmpi ule, %row, %posi : index + %scm = arith.select %live, %sc, %neg : f32 + %mine = arith.cmpi eq, %cc, %l : index + %m2 = arith.select %mine, %scm, %m : f32 + scf.yield %m2 : f32 + } + %bm = gpu.subgroup_reduce maxnumf %my : (f32) -> f32 + %Mn = arith.maxnumf %M, %bm : f32 + %dm = arith.subf %M, %Mn : f32 + %ms = math.exp %dm : f32 + %dp = arith.subf %my, %Mn : f32 + %p = math.exp %dp : f32 + %bs = gpu.subgroup_reduce add %p : (f32) -> f32 + %Ss = arith.mulf %S, %ms : f32 + %Sn = arith.addf %Ss, %bs : f32 + %msv = vector.broadcast %ms : f32 to vector<4xf32> + %o1 = arith.mulf %o, %msv : vector<4xf32> + %o2 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%oa = %o1) -> (vector<4xf32>) { + %row = arith.addi %r0, %cc : index + %rowc = arith.minui %row, %posi : index + %vh = vector.load %v[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> + %vf = arith.extf %vh : vector<4xf16> to vector<4xf32> + %cci = arith.index_cast %cc : index to i32 + %pc, %pv = gpu.shuffle idx %p, %cci, %c32i : f32 + %pcv = vector.broadcast %pc : f32 to vector<4xf32> + %on = vector.fma %vf, %pcv, %oa : vector<4xf32> + scf.yield %on : vector<4xf32> + } + scf.yield %Mn, %Sn, %o2 : f32, f32, vector<4xf32> + } + vector.store %st#2, %part[%hi, %wi, %l4] : memref, vector<4xf32> + %lane0 = arith.cmpi eq, %l, %c0 : index + scf.if %lane0 { + memref.store %st#0, %part[%hi, %wi, %c128] : memref + memref.store %st#1, %part[%hi, %wi, %c129] : memref + } + macro.yield %h : i32 + }; + } + } + } + return; +} + +/// Merges the first `parts` parts of `vec_attention_parts` for each head of Q, as llama.cpp's +/// kernel_flash_attn_ext_vec_reduce. A block of 4 SIMD groups does one head: each lane weighs up to 4 parts, +/// and the SIMD groups add them up for 4 values of the head at a time. +fn vec_attention_merge(out : &mut Tensor, part : &Tensor, parts : i32, q_heads : i32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + let _d = mlir!( threads : 128, inputs : (%out = out : memref, %part = part : memref, %parts = parts : i32, %h = h : i32), returns : i32, dialects : ["arith", "memref", "scf", "gpu", "vector", "math"], ensures : [reads_only(part), writes_only(out[h])]) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %c2 = arith.constant 2 : index + %c3 = arith.constant 3 : index + %c4 = arith.constant 4 : index + %c16 = arith.constant 16 : index + %c32 = arith.constant 32 : index + %c64 = arith.constant 64 : index + %c96 = arith.constant 96 : index + %c128 = arith.constant 128 : index + %c129 = arith.constant 129 : index + %neg = arith.constant -3.0e38 : f32 + %zero = arith.constant 0.0 : f32 + %one = arith.constant 1.0 : f32 + %tid = gpu.thread_id x + %sg = arith.divui %tid, %c32 : index + %l = arith.remui %tid, %c32 : index + %hi = arith.index_cast %h : i32 to index + %np = arith.index_cast %parts : i32 to index + %last = arith.subi %np, %c1 : index + %p0 = arith.addi %l, %c0 : index + %live0 = arith.cmpi ult, %p0, %np : index + %pc0 = arith.minui %p0, %last : index + %mr0 = memref.load %part[%hi, %pc0, %c128] : memref + %m0 = arith.select %live0, %mr0, %neg : f32 + %p1 = arith.addi %l, %c32 : index + %live1 = arith.cmpi ult, %p1, %np : index + %pc1 = arith.minui %p1, %last : index + %mr1 = memref.load %part[%hi, %pc1, %c128] : memref + %m1 = arith.select %live1, %mr1, %neg : f32 + %p2 = arith.addi %l, %c64 : index + %live2 = arith.cmpi ult, %p2, %np : index + %pc2 = arith.minui %p2, %last : index + %mr2 = memref.load %part[%hi, %pc2, %c128] : memref + %m2 = arith.select %live2, %mr2, %neg : f32 + %p3 = arith.addi %l, %c96 : index + %live3 = arith.cmpi ult, %p3, %np : index + %pc3 = arith.minui %p3, %last : index + %mr3 = memref.load %part[%hi, %pc3, %c128] : memref + %m3 = arith.select %live3, %mr3, %neg : f32 + %m01 = arith.maxnumf %m0, %m1 : f32 + %m23 = arith.maxnumf %m2, %m3 : f32 + %mx = arith.maxnumf %m01, %m23 : f32 + %big = gpu.subgroup_reduce maxnumf %mx : (f32) -> f32 + %dm0 = arith.subf %m0, %big : f32 + %w0 = math.exp %dm0 : f32 + %s0 = memref.load %part[%hi, %pc0, %c129] : memref + %ws0 = arith.mulf %w0, %s0 : f32 + %wv0 = vector.broadcast %w0 : f32 to vector<4xf32> + %dm1 = arith.subf %m1, %big : f32 + %w1 = math.exp %dm1 : f32 + %s1 = memref.load %part[%hi, %pc1, %c129] : memref + %ws1 = arith.mulf %w1, %s1 : f32 + %wv1 = vector.broadcast %w1 : f32 to vector<4xf32> + %dm2 = arith.subf %m2, %big : f32 + %w2 = math.exp %dm2 : f32 + %s2 = memref.load %part[%hi, %pc2, %c129] : memref + %ws2 = arith.mulf %w2, %s2 : f32 + %wv2 = vector.broadcast %w2 : f32 to vector<4xf32> + %dm3 = arith.subf %m3, %big : f32 + %w3 = math.exp %dm3 : f32 + %s3 = memref.load %part[%hi, %pc3, %c129] : memref + %ws3 = arith.mulf %w3, %s3 : f32 + %wv3 = vector.broadcast %w3 : f32 to vector<4xf32> + %t01 = arith.addf %ws0, %ws1 : f32 + %t23 = arith.addf %ws2, %ws3 : f32 + %ts = arith.addf %t01, %t23 : f32 + %total = gpu.subgroup_reduce add %ts : (f32) -> f32 + %inv = arith.divf %one, %total : f32 + %lane0 = arith.cmpi eq, %l, %c0 : index + %sg4 = arith.muli %sg, %c4 : index + %vz4 = arith.constant dense<0.0> : vector<4xf32> + scf.for %n = %c0 to %c128 step %c16 { + %d = arith.addi %n, %sg4 : index + %x0 = vector.load %part[%hi, %pc0, %d] {alignment = 16} : memref, vector<4xf32> + %a0 = vector.fma %x0, %wv0, %vz4 : vector<4xf32> + %x1 = vector.load %part[%hi, %pc1, %d] {alignment = 16} : memref, vector<4xf32> + %a1 = vector.fma %x1, %wv1, %a0 : vector<4xf32> + %x2 = vector.load %part[%hi, %pc2, %d] {alignment = 16} : memref, vector<4xf32> + %a2 = vector.fma %x2, %wv2, %a1 : vector<4xf32> + %x3 = vector.load %part[%hi, %pc3, %d] {alignment = 16} : memref, vector<4xf32> + %a3 = vector.fma %x3, %wv3, %a2 : vector<4xf32> + %e0 = vector.extract %a3[0] : f32 from vector<4xf32> + %r0 = gpu.subgroup_reduce add %e0 : (f32) -> f32 + %o0 = arith.mulf %r0, %inv : f32 + %e1 = vector.extract %a3[1] : f32 from vector<4xf32> + %r1 = gpu.subgroup_reduce add %e1 : (f32) -> f32 + %o1 = arith.mulf %r1, %inv : f32 + %e2 = vector.extract %a3[2] : f32 from vector<4xf32> + %r2 = gpu.subgroup_reduce add %e2 : (f32) -> f32 + %o2 = arith.mulf %r2, %inv : f32 + %e3 = vector.extract %a3[3] : f32 from vector<4xf32> + %r3 = gpu.subgroup_reduce add %e3 : (f32) -> f32 + %o3 = arith.mulf %r3, %inv : f32 + scf.if %lane0 { + %d0 = arith.addi %d, %c0 : index + memref.store %o0, %out[%hi, %d0] : memref + %d1 = arith.addi %d, %c1 : index + memref.store %o1, %out[%hi, %d1] : memref + %d2 = arith.addi %d, %c2 : index + memref.store %o2, %out[%hi, %d2] : memref + %d3 = arith.addi %d, %c3 : index + memref.store %o3, %out[%hi, %d3] : memref + } + } + macro.yield %h : i32 + }; + } + } + return; +} + +/// The scratch space of `split_attention` for positions below `max_seq`, on the CPU. Transfer it to the +/// memory of the other tensors. Each block of positions writes the weighted sum of V for each of its +/// heads, then the largest score and the sum of the weights. +fn split_attention_scratch(max_seq : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> Tensor { + // 20 blocks of 32 positions below position 640, and blocks of 64 positions from there on. + let mut splits = (max_seq + 63) / 64; + if splits < 20 { + splits = 20; + } + return Tensor([kv_heads * ((q_heads / kv_heads + 7) / 8), splits, 8, head_dim + 2]); +} + +/// The parts of `split_attention` for blocks of 32 positions: 4 SIMD groups of 2 heads of Q. +fn split_attention_parts_32(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + let group = q_heads / kv_heads; + let tiles = (group + 7) / 8; + let scale = 1.0 / (head_dim as f32).sqrt(); + spawn on(Topology::Device) { + for gt in 0..kv_heads * tiles across blocks { + for c in 0..(pos + 32) / 32 across blocks { + let mut w = unsafe { Tensor::uninit() }; + let mut top = unsafe { + Tensor::uninit() + }; + let mut sums = unsafe { + Tensor::uninit() + }; + let g = gt / tiles; + let base = g * group + (gt - g * tiles) * 8; + let left = group - (gt - g * tiles) * 8; + for s in 0..4 across subgroups { + let first = base + s * 2; + let mut heads = left - s * 2; + if heads > 2 { + heads = 2; + } + // A head past the last one of the group reads the last one again, and its sums go nowhere. + let mut h0 = first + 0; + if 0 >= heads { + h0 = first + heads - 1; + } + let mut h1 = first + 1; + if 1 >= heads { + h1 = first + heads - 1; + } + for l in 0..32 across lanes(32) { + // The scores of the position of the lane, for each head. A position past `pos` reads row + // `pos`, and its score is -3e38. + let mut t0 = c * 32 + 0 + l; + if t0 > pos { + t0 = pos; + } + let mut dot0_0 : f32 = 0.0; + let mut dot0_1 : f32 = 0.0; + for d in 0..head_dim { + let k0 = k_cache[t0][g][d] as f32; + let q0 = q[h0][d]; + dot0_0 = dot0_0 + q0 * k0; + let q1 = q[h1][d]; + dot0_1 = dot0_1 + q1 * k0; + } + let mut s0_0 : f32 = -3.0e38; + if c * 32 + 0 + l <= pos { + s0_0 = dot0_0 * scale; + } + w[s][0][0 + l] = s0_0; + top[s][0][l] = s0_0; + let mut s0_1 : f32 = -3.0e38; + if c * 32 + 0 + l <= pos { + s0_1 = dot0_1 * scale; + } + w[s][1][0 + l] = s0_1; + top[s][1][l] = s0_1; + } + let big0 = lanes::max(&top[s][0], 32); + let big1 = lanes::max(&top[s][1], 32); + // The weight of each position, as exp(score - the largest score of the block). + for l in 0..32 across lanes(32) { + let e0_0 = (w[s][0][0 + l] - big0).fast_exp(); + w[s][0][0 + l] = e0_0; + sums[s][0][l] = e0_0; + let e0_1 = (w[s][1][0 + l] - big1).fast_exp(); + w[s][1][0 + l] = e0_1; + sums[s][1][l] = e0_1; + } + let total0 = lanes::sum(&sums[s][0], 32); + let total1 = lanes::sum(&sums[s][1], 32); + // The weighted sum of the rows of V. Lane l takes values l, l + 32, l + 64 and l + 96. + for l in 0..32 across lanes(32) { + let mut acc0_0 : f32 = 0.0; + let mut acc0_1 : f32 = 0.0; + let mut acc0_2 : f32 = 0.0; + let mut acc0_3 : f32 = 0.0; + let mut acc1_0 : f32 = 0.0; + let mut acc1_1 : f32 = 0.0; + let mut acc1_2 : f32 = 0.0; + let mut acc1_3 : f32 = 0.0; + // With head_dim below 128, values past it read others again, and their sums go nowhere. + let d0 = (0 + l) % head_dim; + let d1 = (32 + l) % head_dim; + let d2 = (64 + l) % head_dim; + let d3 = (96 + l) % head_dim; + let mut last = pos - c * 32; + if last > 31 { + last = 31; + } + for t in 0..last + 1 { + let row = c * 32 + t; + let v0 = v_cache[row][g][d0] as f32; + let v1 = v_cache[row][g][d1] as f32; + let v2 = v_cache[row][g][d2] as f32; + let v3 = v_cache[row][g][d3] as f32; + let w0 = w[s][0][t]; + acc0_0 = acc0_0 + w0 * v0; + acc0_1 = acc0_1 + w0 * v1; + acc0_2 = acc0_2 + w0 * v2; + acc0_3 = acc0_3 + w0 * v3; + let w1 = w[s][1][t]; + acc1_0 = acc1_0 + w1 * v0; + acc1_1 = acc1_1 + w1 * v1; + acc1_2 = acc1_2 + w1 * v2; + acc1_3 = acc1_3 + w1 * v3; + } + if 0 < heads { + if 0 < head_dim { + part[gt][c][s * 2 + 0][0 + l] = acc0_0; + } + if 32 < head_dim { + part[gt][c][s * 2 + 0][32 + l] = acc0_1; + } + if 64 < head_dim { + part[gt][c][s * 2 + 0][64 + l] = acc0_2; + } + if 96 < head_dim { + part[gt][c][s * 2 + 0][96 + l] = acc0_3; + } + } + if 1 < heads { + if 0 < head_dim { + part[gt][c][s * 2 + 1][0 + l] = acc1_0; + } + if 32 < head_dim { + part[gt][c][s * 2 + 1][32 + l] = acc1_1; + } + if 64 < head_dim { + part[gt][c][s * 2 + 1][64 + l] = acc1_2; + } + if 96 < head_dim { + part[gt][c][s * 2 + 1][96 + l] = acc1_3; + } + } + } + if 0 < heads { + part[gt][c][s * 2 + 0][head_dim] = big0; + part[gt][c][s * 2 + 0][head_dim + 1] = total0; + } + if 1 < heads { + part[gt][c][s * 2 + 1][head_dim] = big1; + part[gt][c][s * 2 + 1][head_dim + 1] = total1; + } + } + } + } + } + return; +} + +/// The parts of `split_attention` for blocks of 64 positions: 2 SIMD groups of 4 heads of Q. +fn split_attention_parts_64(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + let group = q_heads / kv_heads; + let tiles = (group + 7) / 8; + let scale = 1.0 / (head_dim as f32).sqrt(); + spawn on(Topology::Device) { + for gt in 0..kv_heads * tiles across blocks { + for c in 0..(pos + 64) / 64 across blocks { + let mut w = unsafe { Tensor::uninit() }; + let mut top = unsafe { + Tensor::uninit() + }; + let mut sums = unsafe { + Tensor::uninit() + }; + let g = gt / tiles; + let base = g * group + (gt - g * tiles) * 8; + let left = group - (gt - g * tiles) * 8; + for s in 0..2 across subgroups { + let first = base + s * 4; + let mut heads = left - s * 4; + if heads > 4 { + heads = 4; + } + // A head past the last one of the group reads the last one again, and its sums go nowhere. + let mut h0 = first + 0; + if 0 >= heads { + h0 = first + heads - 1; + } + let mut h1 = first + 1; + if 1 >= heads { + h1 = first + heads - 1; + } + let mut h2 = first + 2; + if 2 >= heads { + h2 = first + heads - 1; + } + let mut h3 = first + 3; + if 3 >= heads { + h3 = first + heads - 1; + } + for l in 0..32 across lanes(32) { + // The scores of each of the 2 positions of the lane, for each head. A position past `pos` reads row + // `pos`, and its score is -3e38. + let mut t0 = c * 64 + 0 + l; + if t0 > pos { + t0 = pos; + } + let mut dot0_0 : f32 = 0.0; + let mut dot0_1 : f32 = 0.0; + let mut dot0_2 : f32 = 0.0; + let mut dot0_3 : f32 = 0.0; + let mut t1 = c * 64 + 32 + l; + if t1 > pos { + t1 = pos; + } + let mut dot1_0 : f32 = 0.0; + let mut dot1_1 : f32 = 0.0; + let mut dot1_2 : f32 = 0.0; + let mut dot1_3 : f32 = 0.0; + for d in 0..head_dim { + let k0 = k_cache[t0][g][d] as f32; + let k1 = k_cache[t1][g][d] as f32; + let q0 = q[h0][d]; + dot0_0 = dot0_0 + q0 * k0; + dot1_0 = dot1_0 + q0 * k1; + let q1 = q[h1][d]; + dot0_1 = dot0_1 + q1 * k0; + dot1_1 = dot1_1 + q1 * k1; + let q2 = q[h2][d]; + dot0_2 = dot0_2 + q2 * k0; + dot1_2 = dot1_2 + q2 * k1; + let q3 = q[h3][d]; + dot0_3 = dot0_3 + q3 * k0; + dot1_3 = dot1_3 + q3 * k1; + } + let mut s0_0 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_0 = dot0_0 * scale; + } + w[s][0][0 + l] = s0_0; + let mut s1_0 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_0 = dot1_0 * scale; + } + w[s][0][32 + l] = s1_0; + top[s][0][l] = s0_0.max(s1_0); + let mut s0_1 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_1 = dot0_1 * scale; + } + w[s][1][0 + l] = s0_1; + let mut s1_1 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_1 = dot1_1 * scale; + } + w[s][1][32 + l] = s1_1; + top[s][1][l] = s0_1.max(s1_1); + let mut s0_2 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_2 = dot0_2 * scale; + } + w[s][2][0 + l] = s0_2; + let mut s1_2 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_2 = dot1_2 * scale; + } + w[s][2][32 + l] = s1_2; + top[s][2][l] = s0_2.max(s1_2); + let mut s0_3 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_3 = dot0_3 * scale; + } + w[s][3][0 + l] = s0_3; + let mut s1_3 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_3 = dot1_3 * scale; + } + w[s][3][32 + l] = s1_3; + top[s][3][l] = s0_3.max(s1_3); + } + let big0 = lanes::max(&top[s][0], 32); + let big1 = lanes::max(&top[s][1], 32); + let big2 = lanes::max(&top[s][2], 32); + let big3 = lanes::max(&top[s][3], 32); + // The weight of each position, as exp(score - the largest score of the block). + for l in 0..32 across lanes(32) { + let e0_0 = (w[s][0][0 + l] - big0).fast_exp(); + w[s][0][0 + l] = e0_0; + let e1_0 = (w[s][0][32 + l] - big0).fast_exp(); + w[s][0][32 + l] = e1_0; + sums[s][0][l] = e0_0 + e1_0; + let e0_1 = (w[s][1][0 + l] - big1).fast_exp(); + w[s][1][0 + l] = e0_1; + let e1_1 = (w[s][1][32 + l] - big1).fast_exp(); + w[s][1][32 + l] = e1_1; + sums[s][1][l] = e0_1 + e1_1; + let e0_2 = (w[s][2][0 + l] - big2).fast_exp(); + w[s][2][0 + l] = e0_2; + let e1_2 = (w[s][2][32 + l] - big2).fast_exp(); + w[s][2][32 + l] = e1_2; + sums[s][2][l] = e0_2 + e1_2; + let e0_3 = (w[s][3][0 + l] - big3).fast_exp(); + w[s][3][0 + l] = e0_3; + let e1_3 = (w[s][3][32 + l] - big3).fast_exp(); + w[s][3][32 + l] = e1_3; + sums[s][3][l] = e0_3 + e1_3; + } + let total0 = lanes::sum(&sums[s][0], 32); + let total1 = lanes::sum(&sums[s][1], 32); + let total2 = lanes::sum(&sums[s][2], 32); + let total3 = lanes::sum(&sums[s][3], 32); + // The weighted sum of the rows of V. Lane l takes values l, l + 32, l + 64 and l + 96. + for l in 0..32 across lanes(32) { + let mut acc0_0 : f32 = 0.0; + let mut acc0_1 : f32 = 0.0; + let mut acc0_2 : f32 = 0.0; + let mut acc0_3 : f32 = 0.0; + let mut acc1_0 : f32 = 0.0; + let mut acc1_1 : f32 = 0.0; + let mut acc1_2 : f32 = 0.0; + let mut acc1_3 : f32 = 0.0; + let mut acc2_0 : f32 = 0.0; + let mut acc2_1 : f32 = 0.0; + let mut acc2_2 : f32 = 0.0; + let mut acc2_3 : f32 = 0.0; + let mut acc3_0 : f32 = 0.0; + let mut acc3_1 : f32 = 0.0; + let mut acc3_2 : f32 = 0.0; + let mut acc3_3 : f32 = 0.0; + // With head_dim below 128, values past it read others again, and their sums go nowhere. + let d0 = (0 + l) % head_dim; + let d1 = (32 + l) % head_dim; + let d2 = (64 + l) % head_dim; + let d3 = (96 + l) % head_dim; + let mut last = pos - c * 64; + if last > 63 { + last = 63; + } + for t in 0..last + 1 { + let row = c * 64 + t; + let v0 = v_cache[row][g][d0] as f32; + let v1 = v_cache[row][g][d1] as f32; + let v2 = v_cache[row][g][d2] as f32; + let v3 = v_cache[row][g][d3] as f32; + let w0 = w[s][0][t]; + acc0_0 = acc0_0 + w0 * v0; + acc0_1 = acc0_1 + w0 * v1; + acc0_2 = acc0_2 + w0 * v2; + acc0_3 = acc0_3 + w0 * v3; + let w1 = w[s][1][t]; + acc1_0 = acc1_0 + w1 * v0; + acc1_1 = acc1_1 + w1 * v1; + acc1_2 = acc1_2 + w1 * v2; + acc1_3 = acc1_3 + w1 * v3; + let w2 = w[s][2][t]; + acc2_0 = acc2_0 + w2 * v0; + acc2_1 = acc2_1 + w2 * v1; + acc2_2 = acc2_2 + w2 * v2; + acc2_3 = acc2_3 + w2 * v3; + let w3 = w[s][3][t]; + acc3_0 = acc3_0 + w3 * v0; + acc3_1 = acc3_1 + w3 * v1; + acc3_2 = acc3_2 + w3 * v2; + acc3_3 = acc3_3 + w3 * v3 diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/llama/ctx2048.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/llama/ctx2048.txt new file mode 100644 index 0000000..90e3bb2 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/llama/ctx2048.txt @@ -0,0 +1,138 @@ +//===- model.vx - Qwen app --------------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// One token of a Qwen2 or Qwen3 MoE decoder on the GPU, with the kernels of `std::nn`. `State` +// holds every tensor that a token writes, and the KV cache. It is made once, before the first +// token, so the token loop allocates nothing. +import core::convert; +import core::num; +import std::nn; +import std::vec; +import qwen::attention; +import qwen::products; +import qwen::q6; +import qwen::weights; + +/// The keys and the values of every position so far, for one layer: [max_seq, kv_heads, head_dim]. +/// They are f16, half the memory of f32. The kernels compute in f32, and round only what they +/// store here. +struct Cache { + k : Tensor, + v : Tensor, +} + +/// The tensors of a mixture-of-experts layer: the router's score of each expert, the chosen +/// experts and their weights, and the SwiGLU output of each chosen expert, [experts_per_token, +/// moe_intermediate_size]. +struct Experts { + router_logits : Tensor, + ids : Tensor, + weights : Tensor, + mlp : Tensor, +} + +/// The tensors that a token writes, in GPU memory, and one `Cache` for each layer. `cos` and `sin` +/// are [max_seq, head_dim / 2]. +struct State { + max_seq : i32, + x : Tensor, + xn : Tensor, + q : Tensor, + k : Tensor, + v : Tensor, + q_turned : Tensor, + attended : Tensor, + attention_parts : Tensor, + vec_parts : Tensor, + mlp : Tensor, + experts : Experts, + logits : Tensor, + cos : Tensor, + sin : Tensor, + caches : Vec, +} + +/// The state for up to `max_seq` positions. The angles of RoPE are computed in f64, as in +/// `reference.py`, and rounded to f32 once. +fn new_state(c : &Config, max_seq : i32) -> State { + assert(max_seq > 0 && max_seq <= c.max_positions, "max_seq must be between 1 and the max_positions of the model"); + let half = c.head_dim / 2; + let mut hcos = Tensor([max_seq, half]); + let mut hsin = Tensor([max_seq, half]); + for p in 0..max_seq { + for i in 0..half { + let angle = f64::from(p) / f64::powf(c.rope_theta, f64::from(2 * i) / f64::from(c.head_dim)); + hcos[p][i] = f64::cos(angle) as f32; + hsin[p][i] = f64::sin(angle) as f32; + } + } + // A dense model uses none of the tensors of the experts, so one value each is enough. + let experts = i32::max(c.num_experts, 1); + let chosen = i32::max(c.experts_per_token, 1); + let moe_inter = i32::max(c.moe_intermediate_size, 1); + // The flash attention of a prompt reads the cache in blocks of 64 positions. + let rows = (max_seq + 63) / 64 * 64; + let mut caches = Vec::new(); + for l in 0..c.num_layers { + caches.push(Cache { + k: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + }); + } + return State { + max_seq: max_seq, + x: transfer(Tensor([c.hidden_size]), Memory::HBM), + xn: transfer(Tensor([c.hidden_size]), Memory::HBM), + q: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + k: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + q_turned: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attended: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attention_parts: transfer(split_attention_scratch(max_seq, c.num_q_heads, c.num_kv_heads, c.head_dim), Memory::HBM), + vec_parts: transfer(vec_attention_scratch(c.num_q_heads), Memory::HBM), + mlp: transfer(Tensor([c.intermediate_size]), Memory::HBM), + experts: Experts { + router_logits: transfer(Tensor([experts]), Memory::HBM), + ids: transfer(Tensor([chosen]), Memory::HBM), + weights: transfer(Tensor([chosen]), Memory::HBM), + mlp: transfer(Tensor([chosen, moe_inter]), Memory::HBM), + }, + logits: transfer(Tensor([c.vocab_size]), Memory::HBM), + cos: transfer(hcos, Memory::HBM), + sin: transfer(hsin, Memory::HBM), + caches: caches, + }; +} + +/// y = m x, with the kernel for the dtype of `m`, which has `rows` x `cols` weights. +fn matvec(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U6 { + matvec_q6(y, &m.codes, &m.high, &m.group_scales, x, rows, cols); + } else if m.dtype == U4 { + nn_matvec_q4(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x. +fn matvec_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_matvec_q4_add(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_add(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec_add(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x, for x of [heads, head_dim]. +fn matvec_heads_add(y : diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/llama/ctx32768.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/llama/ctx32768.txt new file mode 100644 index 0000000..893602a --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/llama/ctx32768.txt @@ -0,0 +1,1975 @@ +//===- model.vx - Qwen app --------------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// One token of a Qwen2 or Qwen3 MoE decoder on the GPU, with the kernels of `std::nn`. `State` +// holds every tensor that a token writes, and the KV cache. It is made once, before the first +// token, so the token loop allocates nothing. +import core::convert; +import core::num; +import std::nn; +import std::vec; +import qwen::attention; +import qwen::products; +import qwen::q6; +import qwen::weights; + +/// The keys and the values of every position so far, for one layer: [max_seq, kv_heads, head_dim]. +/// They are f16, half the memory of f32. The kernels compute in f32, and round only what they +/// store here. +struct Cache { + k : Tensor, + v : Tensor, +} + +/// The tensors of a mixture-of-experts layer: the router's score of each expert, the chosen +/// experts and their weights, and the SwiGLU output of each chosen expert, [experts_per_token, +/// moe_intermediate_size]. +struct Experts { + router_logits : Tensor, + ids : Tensor, + weights : Tensor, + mlp : Tensor, +} + +/// The tensors that a token writes, in GPU memory, and one `Cache` for each layer. `cos` and `sin` +/// are [max_seq, head_dim / 2]. +struct State { + max_seq : i32, + x : Tensor, + xn : Tensor, + q : Tensor, + k : Tensor, + v : Tensor, + q_turned : Tensor, + attended : Tensor, + attention_parts : Tensor, + vec_parts : Tensor, + mlp : Tensor, + experts : Experts, + logits : Tensor, + cos : Tensor, + sin : Tensor, + caches : Vec, +} + +/// The state for up to `max_seq` positions. The angles of RoPE are computed in f64, as in +/// `reference.py`, and rounded to f32 once. +fn new_state(c : &Config, max_seq : i32) -> State { + assert(max_seq > 0 && max_seq <= c.max_positions, "max_seq must be between 1 and the max_positions of the model"); + let half = c.head_dim / 2; + let mut hcos = Tensor([max_seq, half]); + let mut hsin = Tensor([max_seq, half]); + for p in 0..max_seq { + for i in 0..half { + let angle = f64::from(p) / f64::powf(c.rope_theta, f64::from(2 * i) / f64::from(c.head_dim)); + hcos[p][i] = f64::cos(angle) as f32; + hsin[p][i] = f64::sin(angle) as f32; + } + } + // A dense model uses none of the tensors of the experts, so one value each is enough. + let experts = i32::max(c.num_experts, 1); + let chosen = i32::max(c.experts_per_token, 1); + let moe_inter = i32::max(c.moe_intermediate_size, 1); + // The flash attention of a prompt reads the cache in blocks of 64 positions. + let rows = (max_seq + 63) / 64 * 64; + let mut caches = Vec::new(); + for l in 0..c.num_layers { + caches.push(Cache { + k: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + }); + } + return State { + max_seq: max_seq, + x: transfer(Tensor([c.hidden_size]), Memory::HBM), + xn: transfer(Tensor([c.hidden_size]), Memory::HBM), + q: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + k: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + q_turned: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attended: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attention_parts: transfer(split_attention_scratch(max_seq, c.num_q_heads, c.num_kv_heads, c.head_dim), Memory::HBM), + vec_parts: transfer(vec_attention_scratch(c.num_q_heads), Memory::HBM), + mlp: transfer(Tensor([c.intermediate_size]), Memory::HBM), + experts: Experts { + router_logits: transfer(Tensor([experts]), Memory::HBM), + ids: transfer(Tensor([chosen]), Memory::HBM), + weights: transfer(Tensor([chosen]), Memory::HBM), + mlp: transfer(Tensor([chosen, moe_inter]), Memory::HBM), + }, + logits: transfer(Tensor([c.vocab_size]), Memory::HBM), + cos: transfer(hcos, Memory::HBM), + sin: transfer(hsin, Memory::HBM), + caches: caches, + }; +} + +/// y = m x, with the kernel for the dtype of `m`, which has `rows` x `cols` weights. +fn matvec(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U6 { + matvec_q6(y, &m.codes, &m.high, &m.group_scales, x, rows, cols); + } else if m.dtype == U4 { + nn_matvec_q4(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x. +fn matvec_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_matvec_q4_add(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_add(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec_add(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x, for x of [heads, head_dim]. +fn matvec_heads_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, heads : i32, head_dim : i32) -> void { + if m.dtype == U4 { + matvec_q4_heads_add_blocks(y, &m.codes, &m.group_scales, x, rows, heads, head_dim); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_heads_add(y, &m.codes, &m.scales, x, rows, heads, head_dim); + } else { + nn_matvec_heads_add(y, &m.bf16, x, rows, heads, head_dim); + } + return; +} + +/// The Q, K and V of x: m x + b, split by heads. +fn qkv(q : &mut Tensor, k : &mut Tensor, v : &mut Tensor, m : &WeightMatrix, b : &Tensor, x : &Tensor, c : &Config) -> void { + if m.dtype == U4 { + qkv_q4_blocks(q, k, v, &m.codes, &m.group_scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } else if m.dtype == F8E4M3 { + nn_qkv_fp8(q, k, v, &m.codes, &m.scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } else { + nn_qkv(q, k, v, &m.bf16, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } + return; +} + +/// The SwiGLU of a dense MLP, for the gate rows and then the up rows of `m`. +fn swiglu(out : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_swiglu_q4(out, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_swiglu_fp8(out, &m.codes, &m.scales, x, rows, cols); + } else { + nn_swiglu(out, &m.bf16, x, rows, cols); + } + return; +} + +/// The mixture of experts of a layer: the router chooses experts_per_token experts and their +/// weights, and x gets the sum of their outputs for xn, each times its weight. +fn add_experts(e : &mut Experts, x : &mut Tensor, xn : &Tensor, layer : &Layer, c : &Config) -> void { + let k = c.experts_per_token; + let inter = c.moe_intermediate_size; + nn_matvec(&mut e.router_logits, &layer.router, xn, c.num_experts, c.hidden_size); + nn_top_k(&mut e.ids, &mut e.weights, &e.router_logits, c.num_experts, k); + let gate_up = &layer.gate_up; + let down = &layer.down; + if gate_up.dtype == U4 { + moe_swiglu_q4_blocks(&mut e.mlp, &gate_up.codes, &gate_up.group_scales, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + moe_down_q4_add_blocks(x, &down.codes, &down.group_scales, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + } else { + assert(gate_up.dtype == BF16, "the experts of a mixture-of-experts model must be bf16 or Q4_0"); + nn_moe_swiglu(&mut e.mlp, &gate_up.bf16, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + nn_moe_down_add(x, &down.bf16, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + } + return; +} + +/// Runs the token in `token` at position `pos` through every layer. The hidden state of the +/// token is then in `s.x`, and its keys and values are in the caches. +fn run_layers(w : &Weights, s : &mut State, token : &Tensor, pos : i32) -> void { + let c = &w.config; + let eps = c.rms_norm_eps as f32; + assert(pos >= 0 && pos < s.max_seq, "the position is past the end of the KV cache"); + nn_embed(&mut s.x, &w.embed, token, c.hidden_size); + let mut l = 0; + for cache in s.caches.iter_mut() { + let layer = &w.layers[l]; + nn_rms_norm(&mut s.xn, &s.x, &layer.attn_norm, c.hidden_size, eps); + qkv(&mut s.q, &mut s.k, &mut s.v, &layer.qkv, &layer.qkv_bias, &s.xn, c); + if c.qk_norm { + norm_rope_and_store(&mut s.q_turned, &mut cache.k, &mut cache.v, &s.q, &s.k, &s.v, &layer.q_norm, &layer.k_norm, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.head_dim, eps); + } else { + rope_and_store(&mut s.q_turned, &mut cache.k, &mut cache.v, &s.q, &s.k, &s.v, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } + if c.head_dim == 128 { + vec_attention(&mut s.attended, &mut s.vec_parts, &s.q_turned, &cache.k, &cache.v, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } else { + split_attention(&mut s.attended, &mut s.attention_parts, &s.q_turned, &cache.k, &cache.v, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } + matvec_heads_add(&mut s.x, &layer.attn_out, &s.attended, c.hidden_size, c.num_q_heads, c.head_dim); + nn_rms_norm(&mut s.xn, &s.x, &layer.mlp_norm, c.hidden_size, eps); + if c.num_experts > 0 { + add_experts(&mut s.experts, &mut s.x, &s.xn, layer, c); + } else { + swiglu(&mut s.mlp, &layer.gate_up, &s.xn, c.intermediate_size, c.hidden_size); + matvec_add(&mut s.x, &layer.down, &s.mlp, c.hidden_size, c.intermediate_size); + } + l = l + 1; + } + return; +} + +/// The logits of the token whose hidden state is in `s.x`, and in `next` the index of the largest +/// one. Both stay in GPU memory. +fn predict(w : &Weights, s : &mut State, next : &mut Tensor) -> void { + let c = &w.config; + nn_rms_norm(&mut s.xn, &s.x, &w.final_norm, c.hidden_size, c.rms_norm_eps as f32); + if c.tied_embeddings { + nn_matvec(&mut s.logits, &w.embed, &s.xn, c.vocab_size, c.hidden_size); + } else { + matvec(&mut s.logits, &w.lm_head, &s.xn, c.vocab_size, c.hidden_size); + } + nn_argmax(next, &s.logits, c.vocab_size); + return; +} +//===- attention.vx - Qwen app ----------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// The attention of one generated token, with the positions split among blocks. This is a copy of +// `nn_attention` and its kernels from `std::nn` on Vx main (vx-lang/Vx#3216), with `split_` in place +// of `nn_` in their names. Vx v0.0.4 has the older `nn_attention`, which has one block for each head +// of Q, so its time grows with the number of positions. Remove this file, and call `nn_attention` +// of `std::nn`, when a Vx release has the new one (#4). +// +// `vec_attention`, for head_dim 128, has the design of llama.cpp's flash attention for one token +// (kernel_flash_attn_ext_vec and kernel_flash_attn_ext_vec_reduce), MIT License, Copyright (c) 2023-2026 +// The ggml authors. scripts/mlir_kernels/decode_attention.py writes its kernels: change that script, not +// the MLIR. +import core::num; +import std::nn; + +/// Attention of the token at position `pos` over rows 0 to `pos` of the KV cache, with a softmax +/// of the scores q . k / sqrt(head_dim). `part` is scratch space from `split_attention_scratch`. +/// +/// The blocks of the first kernel split the positions, 32 to a block below position 640 and 64 from +/// there on. A block serves the 8 heads of Q that share a head of K and V, so it reads each row of +/// the cache once for all 8. A second kernel merges the parts of the blocks for each head. +fn split_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_heads % kv_heads == 0, "split_attention: q_heads must be a multiple of kv_heads"); + assert(head_dim % 32 == 0 && head_dim <= 128, "split_attention: head_dim must be a multiple of 32, and at most 128"); + let mut n_pos = 32; + if pos >= 640 { + n_pos = 64; + } + assert(part.extent(0) >= kv_heads * ((q_heads / kv_heads + 7) / 8) && part.extent(1) >= (pos + n_pos) / n_pos && part.extent(2) >= 8 && part.extent(3) >= head_dim + 2, "split_attention: `part` is too small for this position. Make it with split_attention_scratch"); + if n_pos == 32 { + split_attention_parts_32(part, q, k_cache, v_cache, pos, q_heads, kv_heads, head_dim); + } else { + split_attention_parts_64(part, q, k_cache, v_cache, pos, q_heads, kv_heads, head_dim); + } + split_attention_merge(out, part, pos, n_pos, q_heads, kv_heads, head_dim); + return; +} + +/// Attention of the token at position `pos`, as `split_attention`, for head_dim 128, with the kernels of +/// llama.cpp's flash attention for one token. `vec_attention_parts` splits the blocks of 32 positions among +/// `nwg` SIMD groups for each head of Q: 32 of them, or 64 when each of 32 would have more than 2 blocks. +/// (llama.cpp goes on to 4 SIMD groups of 32 a block, but 128 parts are no faster here: their merge costs what +/// they save.) `vec_attention_merge` then merges the parts. `part` is scratch space from +/// `vec_attention_scratch`. +fn vec_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_heads % kv_heads == 0 && head_dim == 128, "vec_attention: q_heads must be a multiple of kv_heads, and head_dim 128"); + assert(part.extent(0) >= q_heads && part.extent(1) >= 128 && part.extent(2) == 132, "vec_attention: `part` is too small. Make it with vec_attention_scratch"); + let mut nwg = 32; + if 2 * nwg * 32 < pos + 1 { + nwg = nwg * 2; + } + vec_attention_parts(part, q, k_cache, v_cache, pos, q_heads, q_heads / kv_heads, nwg, 1.0 / (head_dim as f32).sqrt()); + vec_attention_merge(out, part, nwg, q_heads); + return; +} + +/// The scratch space of `vec_attention`, on the CPU: up to 128 parts for each head of Q, each the sum of V +/// (128 values), the largest score, and the sum of the weights. A part has 132 values, so that each starts +/// at a multiple of 16 bytes. +fn vec_attention_scratch(q_heads : i32) -> Tensor { + return Tensor([q_heads, 128, 132]); +} + +/// The parts of `vec_attention`, as llama.cpp's kernel_flash_attn_ext_vec. Block (h, w) is a SIMD group for +/// query head h. It does the blocks of 32 positions w, w + nwg, w + 2 nwg, ... up to `pos`, and writes +/// part[h][w]. Lane l owns values 4 l to 4 l + 3 of the head, so that the 32 lanes read a row of K or V in +/// one 256-byte load. For each row, the lanes add up their parts of q . k; then each lane keeps the score +/// of one row, and the lanes take the weights of the rows from each other for the sum of V. A part is the +/// sum of V, not divided, then the largest score and the sum of the weights. +fn vec_attention_parts(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, group : i32, nwg : i32, scale : f32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for w in 0..nwg across blocks { + let g = h / group; + let _d = mlir!( threads : 32, inputs : (%part = part : memref, %q = q : memref, %k3 = k_cache : memref, %v3 = v_cache : memref, %pos = pos : i32, %nwg = nwg : i32, %scale = scale : f32, %h = h : i32, %w = w : i32, %g = g : i32), returns : i32, dialects : ["arith", "memref", "scf", "gpu", "vector", "math"], ensures : [reads_only(q), reads_only(k_cache), reads_only(v_cache), writes_only(part[h][w])]) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %c4 = arith.constant 4 : index + %c32 = arith.constant 32 : index + %c128 = arith.constant 128 : index + %c129 = arith.constant 129 : index + %c32i = arith.constant 32 : i32 + %neg = arith.constant -3.0e38 : f32 + %zero = arith.constant 0.0 : f32 + %vz4 = arith.constant dense<0.0> : vector<4xf32> + %l = gpu.thread_id x + %l4 = arith.muli %l, %c4 : index + %hi = arith.index_cast %h : i32 to index + %wi = arith.index_cast %w : i32 to index + %gi = arith.index_cast %g : i32 to index + %posi = arith.index_cast %pos : i32 to index + %nwgi = arith.index_cast %nwg : i32 to index + %g128 = arith.muli %gi, %c128 : index + %kd = arith.addi %g128, %l4 : index + %P = memref.dim %k3, %c0 : memref + %KH = memref.dim %k3, %c1 : memref + %Wd = arith.muli %KH, %c128 : index + %k = memref.reinterpret_cast %k3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to memref> + %v = memref.reinterpret_cast %v3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to memref> + %qv = vector.load %q[%hi, %l4] {alignment = 16} : memref, vector<4xf32> + %scv = vector.broadcast %scale : f32 to vector<4xf32> + %qs = arith.mulf %qv, %scv : vector<4xf32> + %nkv = arith.addi %posi, %c32 : index + %chunks = arith.divui %nkv, %c32 : index + %st:3 = scf.for %ic = %wi to %chunks step %nwgi iter_args(%M = %neg, %S = %zero, %o = %vz4) -> (f32, f32, vector<4xf32>) { + %r0 = arith.muli %ic, %c32 : index + %my = scf.for %cc = %c0 to %c32 step %c1 iter_args(%m = %neg) -> (f32) { + %row = arith.addi %r0, %cc : index + %rowc = arith.minui %row, %posi : index + %kh = vector.load %k[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> + %kf = arith.extf %kh : vector<4xf16> to vector<4xf32> + %pr = arith.mulf %kf, %qs : vector<4xf32> + %pl = vector.reduction , %pr : vector<4xf32> into f32 + %sc = gpu.subgroup_reduce add %pl : (f32) -> f32 + %live = arith.cmpi ule, %row, %posi : index + %scm = arith.select %live, %sc, %neg : f32 + %mine = arith.cmpi eq, %cc, %l : index + %m2 = arith.select %mine, %scm, %m : f32 + scf.yield %m2 : f32 + } + %bm = gpu.subgroup_reduce maxnumf %my : (f32) -> f32 + %Mn = arith.maxnumf %M, %bm : f32 + %dm = arith.subf %M, %Mn : f32 + %ms = math.exp %dm : f32 + %dp = arith.subf %my, %Mn : f32 + %p = math.exp %dp : f32 + %bs = gpu.subgroup_reduce add %p : (f32) -> f32 + %Ss = arith.mulf %S, %ms : f32 + %Sn = arith.addf %Ss, %bs : f32 + %msv = vector.broadcast %ms : f32 to vector<4xf32> + %o1 = arith.mulf %o, %msv : vector<4xf32> + %o2 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%oa = %o1) -> (vector<4xf32>) { + %row = arith.addi %r0, %cc : index + %rowc = arith.minui %row, %posi : index + %vh = vector.load %v[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> + %vf = arith.extf %vh : vector<4xf16> to vector<4xf32> + %cci = arith.index_cast %cc : index to i32 + %pc, %pv = gpu.shuffle idx %p, %cci, %c32i : f32 + %pcv = vector.broadcast %pc : f32 to vector<4xf32> + %on = vector.fma %vf, %pcv, %oa : vector<4xf32> + scf.yield %on : vector<4xf32> + } + scf.yield %Mn, %Sn, %o2 : f32, f32, vector<4xf32> + } + vector.store %st#2, %part[%hi, %wi, %l4] : memref, vector<4xf32> + %lane0 = arith.cmpi eq, %l, %c0 : index + scf.if %lane0 { + memref.store %st#0, %part[%hi, %wi, %c128] : memref + memref.store %st#1, %part[%hi, %wi, %c129] : memref + } + macro.yield %h : i32 + }; + } + } + } + return; +} + +/// Merges the first `parts` parts of `vec_attention_parts` for each head of Q, as llama.cpp's +/// kernel_flash_attn_ext_vec_reduce. A block of 4 SIMD groups does one head: each lane weighs up to 4 parts, +/// and the SIMD groups add them up for 4 values of the head at a time. +fn vec_attention_merge(out : &mut Tensor, part : &Tensor, parts : i32, q_heads : i32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + let _d = mlir!( threads : 128, inputs : (%out = out : memref, %part = part : memref, %parts = parts : i32, %h = h : i32), returns : i32, dialects : ["arith", "memref", "scf", "gpu", "vector", "math"], ensures : [reads_only(part), writes_only(out[h])]) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %c2 = arith.constant 2 : index + %c3 = arith.constant 3 : index + %c4 = arith.constant 4 : index + %c16 = arith.constant 16 : index + %c32 = arith.constant 32 : index + %c64 = arith.constant 64 : index + %c96 = arith.constant 96 : index + %c128 = arith.constant 128 : index + %c129 = arith.constant 129 : index + %neg = arith.constant -3.0e38 : f32 + %zero = arith.constant 0.0 : f32 + %one = arith.constant 1.0 : f32 + %tid = gpu.thread_id x + %sg = arith.divui %tid, %c32 : index + %l = arith.remui %tid, %c32 : index + %hi = arith.index_cast %h : i32 to index + %np = arith.index_cast %parts : i32 to index + %last = arith.subi %np, %c1 : index + %p0 = arith.addi %l, %c0 : index + %live0 = arith.cmpi ult, %p0, %np : index + %pc0 = arith.minui %p0, %last : index + %mr0 = memref.load %part[%hi, %pc0, %c128] : memref + %m0 = arith.select %live0, %mr0, %neg : f32 + %p1 = arith.addi %l, %c32 : index + %live1 = arith.cmpi ult, %p1, %np : index + %pc1 = arith.minui %p1, %last : index + %mr1 = memref.load %part[%hi, %pc1, %c128] : memref + %m1 = arith.select %live1, %mr1, %neg : f32 + %p2 = arith.addi %l, %c64 : index + %live2 = arith.cmpi ult, %p2, %np : index + %pc2 = arith.minui %p2, %last : index + %mr2 = memref.load %part[%hi, %pc2, %c128] : memref + %m2 = arith.select %live2, %mr2, %neg : f32 + %p3 = arith.addi %l, %c96 : index + %live3 = arith.cmpi ult, %p3, %np : index + %pc3 = arith.minui %p3, %last : index + %mr3 = memref.load %part[%hi, %pc3, %c128] : memref + %m3 = arith.select %live3, %mr3, %neg : f32 + %m01 = arith.maxnumf %m0, %m1 : f32 + %m23 = arith.maxnumf %m2, %m3 : f32 + %mx = arith.maxnumf %m01, %m23 : f32 + %big = gpu.subgroup_reduce maxnumf %mx : (f32) -> f32 + %dm0 = arith.subf %m0, %big : f32 + %w0 = math.exp %dm0 : f32 + %s0 = memref.load %part[%hi, %pc0, %c129] : memref + %ws0 = arith.mulf %w0, %s0 : f32 + %wv0 = vector.broadcast %w0 : f32 to vector<4xf32> + %dm1 = arith.subf %m1, %big : f32 + %w1 = math.exp %dm1 : f32 + %s1 = memref.load %part[%hi, %pc1, %c129] : memref + %ws1 = arith.mulf %w1, %s1 : f32 + %wv1 = vector.broadcast %w1 : f32 to vector<4xf32> + %dm2 = arith.subf %m2, %big : f32 + %w2 = math.exp %dm2 : f32 + %s2 = memref.load %part[%hi, %pc2, %c129] : memref + %ws2 = arith.mulf %w2, %s2 : f32 + %wv2 = vector.broadcast %w2 : f32 to vector<4xf32> + %dm3 = arith.subf %m3, %big : f32 + %w3 = math.exp %dm3 : f32 + %s3 = memref.load %part[%hi, %pc3, %c129] : memref + %ws3 = arith.mulf %w3, %s3 : f32 + %wv3 = vector.broadcast %w3 : f32 to vector<4xf32> + %t01 = arith.addf %ws0, %ws1 : f32 + %t23 = arith.addf %ws2, %ws3 : f32 + %ts = arith.addf %t01, %t23 : f32 + %total = gpu.subgroup_reduce add %ts : (f32) -> f32 + %inv = arith.divf %one, %total : f32 + %lane0 = arith.cmpi eq, %l, %c0 : index + %sg4 = arith.muli %sg, %c4 : index + %vz4 = arith.constant dense<0.0> : vector<4xf32> + scf.for %n = %c0 to %c128 step %c16 { + %d = arith.addi %n, %sg4 : index + %x0 = vector.load %part[%hi, %pc0, %d] {alignment = 16} : memref, vector<4xf32> + %a0 = vector.fma %x0, %wv0, %vz4 : vector<4xf32> + %x1 = vector.load %part[%hi, %pc1, %d] {alignment = 16} : memref, vector<4xf32> + %a1 = vector.fma %x1, %wv1, %a0 : vector<4xf32> + %x2 = vector.load %part[%hi, %pc2, %d] {alignment = 16} : memref, vector<4xf32> + %a2 = vector.fma %x2, %wv2, %a1 : vector<4xf32> + %x3 = vector.load %part[%hi, %pc3, %d] {alignment = 16} : memref, vector<4xf32> + %a3 = vector.fma %x3, %wv3, %a2 : vector<4xf32> + %e0 = vector.extract %a3[0] : f32 from vector<4xf32> + %r0 = gpu.subgroup_reduce add %e0 : (f32) -> f32 + %o0 = arith.mulf %r0, %inv : f32 + %e1 = vector.extract %a3[1] : f32 from vector<4xf32> + %r1 = gpu.subgroup_reduce add %e1 : (f32) -> f32 + %o1 = arith.mulf %r1, %inv : f32 + %e2 = vector.extract %a3[2] : f32 from vector<4xf32> + %r2 = gpu.subgroup_reduce add %e2 : (f32) -> f32 + %o2 = arith.mulf %r2, %inv : f32 + %e3 = vector.extract %a3[3] : f32 from vector<4xf32> + %r3 = gpu.subgroup_reduce add %e3 : (f32) -> f32 + %o3 = arith.mulf %r3, %inv : f32 + scf.if %lane0 { + %d0 = arith.addi %d, %c0 : index + memref.store %o0, %out[%hi, %d0] : memref + %d1 = arith.addi %d, %c1 : index + memref.store %o1, %out[%hi, %d1] : memref + %d2 = arith.addi %d, %c2 : index + memref.store %o2, %out[%hi, %d2] : memref + %d3 = arith.addi %d, %c3 : index + memref.store %o3, %out[%hi, %d3] : memref + } + } + macro.yield %h : i32 + }; + } + } + return; +} + +/// The scratch space of `split_attention` for positions below `max_seq`, on the CPU. Transfer it to the +/// memory of the other tensors. Each block of positions writes the weighted sum of V for each of its +/// heads, then the largest score and the sum of the weights. +fn split_attention_scratch(max_seq : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> Tensor { + // 20 blocks of 32 positions below position 640, and blocks of 64 positions from there on. + let mut splits = (max_seq + 63) / 64; + if splits < 20 { + splits = 20; + } + return Tensor([kv_heads * ((q_heads / kv_heads + 7) / 8), splits, 8, head_dim + 2]); +} + +/// The parts of `split_attention` for blocks of 32 positions: 4 SIMD groups of 2 heads of Q. +fn split_attention_parts_32(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + let group = q_heads / kv_heads; + let tiles = (group + 7) / 8; + let scale = 1.0 / (head_dim as f32).sqrt(); + spawn on(Topology::Device) { + for gt in 0..kv_heads * tiles across blocks { + for c in 0..(pos + 32) / 32 across blocks { + let mut w = unsafe { Tensor::uninit() }; + let mut top = unsafe { + Tensor::uninit() + }; + let mut sums = unsafe { + Tensor::uninit() + }; + let g = gt / tiles; + let base = g * group + (gt - g * tiles) * 8; + let left = group - (gt - g * tiles) * 8; + for s in 0..4 across subgroups { + let first = base + s * 2; + let mut heads = left - s * 2; + if heads > 2 { + heads = 2; + } + // A head past the last one of the group reads the last one again, and its sums go nowhere. + let mut h0 = first + 0; + if 0 >= heads { + h0 = first + heads - 1; + } + let mut h1 = first + 1; + if 1 >= heads { + h1 = first + heads - 1; + } + for l in 0..32 across lanes(32) { + // The scores of the position of the lane, for each head. A position past `pos` reads row + // `pos`, and its score is -3e38. + let mut t0 = c * 32 + 0 + l; + if t0 > pos { + t0 = pos; + } + let mut dot0_0 : f32 = 0.0; + let mut dot0_1 : f32 = 0.0; + for d in 0..head_dim { + let k0 = k_cache[t0][g][d] as f32; + let q0 = q[h0][d]; + dot0_0 = dot0_0 + q0 * k0; + let q1 = q[h1][d]; + dot0_1 = dot0_1 + q1 * k0; + } + let mut s0_0 : f32 = -3.0e38; + if c * 32 + 0 + l <= pos { + s0_0 = dot0_0 * scale; + } + w[s][0][0 + l] = s0_0; + top[s][0][l] = s0_0; + let mut s0_1 : f32 = -3.0e38; + if c * 32 + 0 + l <= pos { + s0_1 = dot0_1 * scale; + } + w[s][1][0 + l] = s0_1; + top[s][1][l] = s0_1; + } + let big0 = lanes::max(&top[s][0], 32); + let big1 = lanes::max(&top[s][1], 32); + // The weight of each position, as exp(score - the largest score of the block). + for l in 0..32 across lanes(32) { + let e0_0 = (w[s][0][0 + l] - big0).fast_exp(); + w[s][0][0 + l] = e0_0; + sums[s][0][l] = e0_0; + let e0_1 = (w[s][1][0 + l] - big1).fast_exp(); + w[s][1][0 + l] = e0_1; + sums[s][1][l] = e0_1; + } + let total0 = lanes::sum(&sums[s][0], 32); + let total1 = lanes::sum(&sums[s][1], 32); + // The weighted sum of the rows of V. Lane l takes values l, l + 32, l + 64 and l + 96. + for l in 0..32 across lanes(32) { + let mut acc0_0 : f32 = 0.0; + let mut acc0_1 : f32 = 0.0; + let mut acc0_2 : f32 = 0.0; + let mut acc0_3 : f32 = 0.0; + let mut acc1_0 : f32 = 0.0; + let mut acc1_1 : f32 = 0.0; + let mut acc1_2 : f32 = 0.0; + let mut acc1_3 : f32 = 0.0; + // With head_dim below 128, values past it read others again, and their sums go nowhere. + let d0 = (0 + l) % head_dim; + let d1 = (32 + l) % head_dim; + let d2 = (64 + l) % head_dim; + let d3 = (96 + l) % head_dim; + let mut last = pos - c * 32; + if last > 31 { + last = 31; + } + for t in 0..last + 1 { + let row = c * 32 + t; + let v0 = v_cache[row][g][d0] as f32; + let v1 = v_cache[row][g][d1] as f32; + let v2 = v_cache[row][g][d2] as f32; + let v3 = v_cache[row][g][d3] as f32; + let w0 = w[s][0][t]; + acc0_0 = acc0_0 + w0 * v0; + acc0_1 = acc0_1 + w0 * v1; + acc0_2 = acc0_2 + w0 * v2; + acc0_3 = acc0_3 + w0 * v3; + let w1 = w[s][1][t]; + acc1_0 = acc1_0 + w1 * v0; + acc1_1 = acc1_1 + w1 * v1; + acc1_2 = acc1_2 + w1 * v2; + acc1_3 = acc1_3 + w1 * v3; + } + if 0 < heads { + if 0 < head_dim { + part[gt][c][s * 2 + 0][0 + l] = acc0_0; + } + if 32 < head_dim { + part[gt][c][s * 2 + 0][32 + l] = acc0_1; + } + if 64 < head_dim { + part[gt][c][s * 2 + 0][64 + l] = acc0_2; + } + if 96 < head_dim { + part[gt][c][s * 2 + 0][96 + l] = acc0_3; + } + } + if 1 < heads { + if 0 < head_dim { + part[gt][c][s * 2 + 1][0 + l] = acc1_0; + } + if 32 < head_dim { + part[gt][c][s * 2 + 1][32 + l] = acc1_1; + } + if 64 < head_dim { + part[gt][c][s * 2 + 1][64 + l] = acc1_2; + } + if 96 < head_dim { + part[gt][c][s * 2 + 1][96 + l] = acc1_3; + } + } + } + if 0 < heads { + part[gt][c][s * 2 + 0][head_dim] = big0; + part[gt][c][s * 2 + 0][head_dim + 1] = total0; + } + if 1 < heads { + part[gt][c][s * 2 + 1][head_dim] = big1; + part[gt][c][s * 2 + 1][head_dim + 1] = total1; + } + } + } + } + } + return; +} + +/// The parts of `split_attention` for blocks of 64 positions: 2 SIMD groups of 4 heads of Q. +fn split_attention_parts_64(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + let group = q_heads / kv_heads; + let tiles = (group + 7) / 8; + let scale = 1.0 / (head_dim as f32).sqrt(); + spawn on(Topology::Device) { + for gt in 0..kv_heads * tiles across blocks { + for c in 0..(pos + 64) / 64 across blocks { + let mut w = unsafe { Tensor::uninit() }; + let mut top = unsafe { + Tensor::uninit() + }; + let mut sums = unsafe { + Tensor::uninit() + }; + let g = gt / tiles; + let base = g * group + (gt - g * tiles) * 8; + let left = group - (gt - g * tiles) * 8; + for s in 0..2 across subgroups { + let first = base + s * 4; + let mut heads = left - s * 4; + if heads > 4 { + heads = 4; + } + // A head past the last one of the group reads the last one again, and its sums go nowhere. + let mut h0 = first + 0; + if 0 >= heads { + h0 = first + heads - 1; + } + let mut h1 = first + 1; + if 1 >= heads { + h1 = first + heads - 1; + } + let mut h2 = first + 2; + if 2 >= heads { + h2 = first + heads - 1; + } + let mut h3 = first + 3; + if 3 >= heads { + h3 = first + heads - 1; + } + for l in 0..32 across lanes(32) { + // The scores of each of the 2 positions of the lane, for each head. A position past `pos` reads row + // `pos`, and its score is -3e38. + let mut t0 = c * 64 + 0 + l; + if t0 > pos { + t0 = pos; + } + let mut dot0_0 : f32 = 0.0; + let mut dot0_1 : f32 = 0.0; + let mut dot0_2 : f32 = 0.0; + let mut dot0_3 : f32 = 0.0; + let mut t1 = c * 64 + 32 + l; + if t1 > pos { + t1 = pos; + } + let mut dot1_0 : f32 = 0.0; + let mut dot1_1 : f32 = 0.0; + let mut dot1_2 : f32 = 0.0; + let mut dot1_3 : f32 = 0.0; + for d in 0..head_dim { + let k0 = k_cache[t0][g][d] as f32; + let k1 = k_cache[t1][g][d] as f32; + let q0 = q[h0][d]; + dot0_0 = dot0_0 + q0 * k0; + dot1_0 = dot1_0 + q0 * k1; + let q1 = q[h1][d]; + dot0_1 = dot0_1 + q1 * k0; + dot1_1 = dot1_1 + q1 * k1; + let q2 = q[h2][d]; + dot0_2 = dot0_2 + q2 * k0; + dot1_2 = dot1_2 + q2 * k1; + let q3 = q[h3][d]; + dot0_3 = dot0_3 + q3 * k0; + dot1_3 = dot1_3 + q3 * k1; + } + let mut s0_0 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_0 = dot0_0 * scale; + } + w[s][0][0 + l] = s0_0; + let mut s1_0 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_0 = dot1_0 * scale; + } + w[s][0][32 + l] = s1_0; + top[s][0][l] = s0_0.max(s1_0); + let mut s0_1 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_1 = dot0_1 * scale; + } + w[s][1][0 + l] = s0_1; + let mut s1_1 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_1 = dot1_1 * scale; + } + w[s][1][32 + l] = s1_1; + top[s][1][l] = s0_1.max(s1_1); + let mut s0_2 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_2 = dot0_2 * scale; + } + w[s][2][0 + l] = s0_2; + let mut s1_2 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_2 = dot1_2 * scale; + } + w[s][2][32 + l] = s1_2; + top[s][2][l] = s0_2.max(s1_2); + let mut s0_3 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_3 = dot0_3 * scale; + } + w[s][3][0 + l] = s0_3; + let mut s1_3 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_3 = dot1_3 * scale; + } + w[s][3][32 + l] = s1_3; + top[s][3][l] = s0_3.max(s1_3); + } + let big0 = lanes::max(&top[s][0], 32); + let big1 = lanes::max(&top[s][1], 32); + let big2 = lanes::max(&top[s][2], 32); + let big3 = lanes::max(&top[s][3], 32); + // The weight of each position, as exp(score - the largest score of the block). + for l in 0..32 across lanes(32) { + let e0_0 = (w[s][0][0 + l] - big0).fast_exp(); + w[s][0][0 + l] = e0_0; + let e1_0 = (w[s][0][32 + l] - big0).fast_exp(); + w[s][0][32 + l] = e1_0; + sums[s][0][l] = e0_0 + e1_0; + let e0_1 = (w[s][1][0 + l] - big1).fast_exp(); + w[s][1][0 + l] = e0_1; + let e1_1 = (w[s][1][32 + l] - big1).fast_exp(); + w[s][1][32 + l] = e1_1; + sums[s][1][l] = e0_1 + e1_1; + let e0_2 = (w[s][2][0 + l] - big2).fast_exp(); + w[s][2][0 + l] = e0_2; + let e1_2 = (w[s][2][32 + l] - big2).fast_exp(); + w[s][2][32 + l] = e1_2; + sums[s][2][l] = e0_2 + e1_2; + let e0_3 = (w[s][3][0 + l] - big3).fast_exp(); + w[s][3][0 + l] = e0_3; + let e1_3 = (w[s][3][32 + l] - big3).fast_exp(); + w[s][3][32 + l] = e1_3; + sums[s][3][l] = e0_3 + e1_3; + } + let total0 = lanes::sum(&sums[s][0], 32); + let total1 = lanes::sum(&sums[s][1], 32); + let total2 = lanes::sum(&sums[s][2], 32); + let total3 = lanes::sum(&sums[s][3], 32); + // The weighted sum of the rows of V. Lane l takes values l, l + 32, l + 64 and l + 96. + for l in 0..32 across lanes(32) { + let mut acc0_0 : f32 = 0.0; + let mut acc0_1 : f32 = 0.0; + let mut acc0_2 : f32 = 0.0; + let mut acc0_3 : f32 = 0.0; + let mut acc1_0 : f32 = 0.0; + let mut acc1_1 : f32 = 0.0; + let mut acc1_2 : f32 = 0.0; + let mut acc1_3 : f32 = 0.0; + let mut acc2_0 : f32 = 0.0; + let mut acc2_1 : f32 = 0.0; + let mut acc2_2 : f32 = 0.0; + let mut acc2_3 : f32 = 0.0; + let mut acc3_0 : f32 = 0.0; + let mut acc3_1 : f32 = 0.0; + let mut acc3_2 : f32 = 0.0; + let mut acc3_3 : f32 = 0.0; + // With head_dim below 128, values past it read others again, and their sums go nowhere. + let d0 = (0 + l) % head_dim; + let d1 = (32 + l) % head_dim; + let d2 = (64 + l) % head_dim; + let d3 = (96 + l) % head_dim; + let mut last = pos - c * 64; + if last > 63 { + last = 63; + } + for t in 0..last + 1 { + let row = c * 64 + t; + let v0 = v_cache[row][g][d0] as f32; + let v1 = v_cache[row][g][d1] as f32; + let v2 = v_cache[row][g][d2] as f32; + let v3 = v_cache[row][g][d3] as f32; + let w0 = w[s][0][t]; + acc0_0 = acc0_0 + w0 * v0; + acc0_1 = acc0_1 + w0 * v1; + acc0_2 = acc0_2 + w0 * v2; + acc0_3 = acc0_3 + w0 * v3; + let w1 = w[s][1][t]; + acc1_0 = acc1_0 + w1 * v0; + acc1_1 = acc1_1 + w1 * v1; + acc1_2 = acc1_2 + w1 * v2; + acc1_3 = acc1_3 + w1 * v3; + let w2 = w[s][2][t]; + acc2_0 = acc2_0 + w2 * v0; + acc2_1 = acc2_1 + w2 * v1; + acc2_2 = acc2_2 + w2 * v2; + acc2_3 = acc2_3 + w2 * v3; + let w3 = w[s][3][t]; + acc3_0 = acc3_0 + w3 * v0; + acc3_1 = acc3_1 + w3 * v1; + acc3_2 = acc3_2 + w3 * v2; + acc3_3 = acc3_3 + w3 * v3; + } + if 0 < heads { + if 0 < head_dim { + part[gt][c][s * 4 + 0][0 + l] = acc0_0; + } + if 32 < head_dim { + part[gt][c][s * 4 + 0][32 + l] = acc0_1; + } + if 64 < head_dim { + part[gt][c][s * 4 + 0][64 + l] = acc0_2; + } + if 96 < head_dim { + part[gt][c][s * 4 + 0][96 + l] = acc0_3; + } + } + if 1 < heads { + if 0 < head_dim { + part[gt][c][s * 4 + 1][0 + l] = acc1_0; + } + if 32 < head_dim { + part[gt][c][s * 4 + 1][32 + l] = acc1_1; + } + if 64 < head_dim { + part[gt][c][s * 4 + 1][64 + l] = acc1_2; + } + if 96 < head_dim { + part[gt][c][s * 4 + 1][96 + l] = acc1_3; + } + } + if 2 < heads { + if 0 < head_dim { + part[gt][c][s * 4 + 2][0 + l] = acc2_0; + } + if 32 < head_dim { + part[gt][c][s * 4 + 2][32 + l] = acc2_1; + } + if 64 < head_dim { + part[gt][c][s * 4 + 2][64 + l] = acc2_2; + } + if 96 < head_dim { + part[gt][c][s * 4 + 2][96 + l] = acc2_3; + } + } + if 3 < heads { + if 0 < head_dim { + part[gt][c][s * 4 + 3][0 + l] = acc3_0; + } + if 32 < head_dim { + part[gt][c][s * 4 + 3][32 + l] = acc3_1; + } + if 64 < head_dim { + part[gt][c][s * 4 + 3][64 + l] = acc3_2; + } + if 96 < head_dim { + part[gt][c][s * 4 + 3][96 + l] = acc3_3; + } + } + } + if 0 < heads { + part[gt][c][s * 4 + 0][head_dim] = big0; + part[gt][c][s * 4 + 0][head_dim + 1] = total0; + } + if 1 < heads { + part[gt][c][s * 4 + 1][head_dim] = big1; + part[gt][c][s * 4 + 1][head_dim + 1] = total1; + } + if 2 < heads { + part[gt][c][s * 4 + 2][head_dim] = big2; + part[gt][c][s * 4 + 2][head_dim + 1] = total2; + } + if 3 < heads { + part[gt][c][s * 4 + 3][head_dim] = big3; + part[gt][c][s * 4 + 3][head_dim + 1] = total3; + } + } + } + } + } + return; +} + +/// Merges the parts of `split_attention` of blocks of `n_pos` positions. A block does 32 values of one +/// head of Q, a value for each lane. +fn split_attention_merge(out : &mut Tensor, part : &Tensor, pos : i32, n_pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + let group = q_heads / kv_heads; + let tiles = (group + 7) / 8; + let splits = (pos + n_pos) / n_pos; + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for dq in 0..head_dim / 32 across blocks { + let mut top = unsafe { + Tensor::uninit() + }; + let g = h / group; + let tile = (h - g * group) / 8; + let gt = g * tiles + tile; + let at = h - g * group - tile * 8; + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let mut m : f32 = -3.0e38; + let mut c = l; + while c < splits { + m = m.max(part[gt][c][at][head_dim]); + c = c + 32; + } + top[s][0][l] = m; + } + let big = lanes::max(&top[s][0], 32); + for l in 0..32 across lanes(32) { + let d = dq * 32 + l; + let mut total : f32 = 0.0; + let mut acc : f32 = 0.0; + for c in 0..splits { + let w = (part[gt][c][at][head_dim] - big).fast_exp(); + total = total + w * part[gt][c][at][head_dim + 1]; + acc = acc + w * part[gt][c][at][d]; + } + out[h][d] = acc / total; + } + } + } + } + } + return; +} + +// The kernels that store the K and V of a generated token: copies of `nn_rope_and_store` and +// `nn_norm_rope_and_store` of `std::nn`, with a KV cache of f16. They compute in f32 and round +// what they store. + +/// RoPE for the token at position `pos`, and its K and V into the KV cache. Writes each head of +/// q, turned, to `q_out`, and each head of k, turned, and of v to row `pos` of the cache. Value i +/// of a head pairs with value i + head_dim / 2, as in the Llama and Qwen models of Hugging Face. +/// Both turn by the angle whose cosine and sine are cos[pos][i] and sin[pos][i]. +fn rope_and_store(q_out : &mut Tensor, k_cache : &mut Tensor, v_cache : &mut Tensor, q : &Tensor, k : &Tensor, v : &Tensor, cos : &Tensor, sin : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + let half = head_dim / 2; + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(q_out.extent(0), q_out.extent(1), q_heads, head_dim); + nn_check_heads(k.extent(0), k.extent(1), kv_heads, head_dim); + nn_check_heads(v.extent(0), v.extent(1), kv_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(pos < cos.extent(0) && pos < sin.extent(0) && half <= cos.extent(1) && half <= sin.extent(1), "rope_and_store: `cos` and `sin` need a row for `pos` with head_dim / 2 values"); + spawn on(Topology::Device) { + for h in 0..q_heads + kv_heads across blocks { + for i in 0..128 across lanes { + if i < head_dim { + // Value i of the head, its partner, and the angle that they share. + let mut j = i; + let mut sign : f32 = -1.0; + let mut partner = i + half; + if i >= half { + j = i - half; + sign = 1.0; + partner = i - half; + } + let c = cos[pos][j]; + let s = sin[pos][j]; + if h < q_heads { + q_out[h][i] = q[h][i] * c + sign * q[h][partner] * s; + } else { + k_cache[pos][h - q_heads][i] = (k[h - q_heads][i] * c + sign * k[h - q_heads][partner] * s) as f16; + v_cache[pos][h - q_heads][i] = v[h - q_heads][i] as f16; + } + } + } + } + } + return; +} + +/// As `rope_and_store`, after an RMSNorm over each head of q and of k: value i of a head x +/// becomes x[i] / sqrt(mean(x^2) + eps) * norm[i], where `norm` is `q_norm` for q and `k_norm` +/// for k. Qwen3 has these norms. +fn norm_rope_and_store(q_out : &mut Tensor, k_cache : &mut Tensor, v_cache : &mut Tensor, q : &Tensor, k : &Tensor, v : &Tensor, q_norm : &Tensor, k_norm : &Tensor, cos : &Tensor, sin : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32, eps : f32) -> void { + let half = head_dim / 2; + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(q_out.extent(0), q_out.extent(1), q_heads, head_dim); + nn_check_heads(k.extent(0), k.extent(1), kv_heads, head_dim); + nn_check_heads(v.extent(0), v.extent(1), kv_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_norm.len() >= head_dim && k_norm.len() >= head_dim, "norm_rope_and_store: `q_norm` and `k_norm` need head_dim values"); + assert(pos < cos.extent(0) && pos < sin.extent(0) && half <= cos.extent(1) && half <= sin.extent(1), "norm_rope_and_store: `cos` and `sin` need a row for `pos` with head_dim / 2 values"); + spawn on(Topology::Device) { + for h in 0..q_heads + kv_heads across blocks { + let mut x = unsafe { Tensor::uninit() }; + let mut part = unsafe { Tensor::uninit() }; + for i in 0..128 across lanes { + let mut a : f32 = 0.0; + if i < head_dim { + if h < q_heads { + a = q[h][i]; + } else { + a = k[h - q_heads][i]; + } + } + x[i] = a; + part[i] = a * a; + } + let ss = lanes::sum(&part, 128); + let inv = 1.0 / (ss / (head_dim as f32) + eps).sqrt(); + for i in 0..128 across lanes { + if i < head_dim { + // Value i of the head, its partner, and the angle that they share. + let mut j = i; + let mut sign : f32 = -1.0; + let mut partner = i + half; + if i >= half { + j = i - half; + sign = 1.0; + partner = i - half; + } + let c = cos[pos][j]; + let s = sin[pos][j]; + if h < q_heads { + let a = x[i] * inv * (q_norm[i] as f32); + let b = x[partner] * inv * (q_norm[partner] as f32); + q_out[h][i] = a * c + sign * b * s; + } else { + let a = x[i] * inv * (k_norm[i] as f32); + let b = x[partner] * inv * (k_norm[partner] as f32); + k_cache[pos][h - q_heads][i] = (a * c + sign * b * s) as f16; + v_cache[pos][h - q_heads][i] = v[h - q_heads][i] as f16; + } + } + } + } + } + return; +} +//===- deltanet.vx - Qwen app -----------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// One generated token through the Gated DeltaNet of a linear attention layer of Qwen3.5 and +// Qwen3.6 (#89), after the product `linear_in` and before the product `linear_out`. The math is +// that of `modeling_qwen3_5_moe.py` of transformers: +// +// - `proj`, the output of `linear_in`, has q (k_heads x 128), k (k_heads x 128), v (v_heads x 128), +// z (v_heads x 128), then b and a (v_heads each), at the offsets that the caller gives. +// - q, k and v go through a causal depthwise convolution of width 4 and a SiLU. q and k then get an +// L2 norm for each head (eps 1e-6 inside the square root), and q is multiplied by 1/sqrt(128). +// - beta = sigmoid(b), and the decay exp(g) with g = -exp(A_log) softplus(a + dt_bias). The weight +// file stores -exp(A_log) as `neg_a`. +// - Head h of v uses head h / (v_heads / k_heads) of q and k. Its state S[k][v] decays, then +// S += k (beta (v - k . S)), and the output is q . S. +// - The output gets an RMS norm for each head, times the norm weight, times silu(z). +// +// All the heads have 128 values. The state of a layer is `conv_state` [2 k_heads + v_heads, 128, 3], +// the last 3 inputs of each channel of the convolution, oldest first, and `state` [v_heads, 128, 128] +// as S[v][k]: the 128 values of k for one value of v are next to each other, so that the 32 lanes of +// a SIMD group read them in one load. Both start at zero. +import core::num; +import std::nn; +import qwen::simd; + +/// The scratch tensors of one token, in GPU memory: q and k after the convolution and the norm +/// [k_heads, 128], v after the convolution [v_heads, 128], beta and the decay exp(g) of each head of +/// v, and q . S [v_heads, 128]. +struct DeltaNetScratch { + q : Tensor, + k : Tensor, + v : Tensor, + beta : Tensor, + decay : Tensor, + o : Tensor, +} + +fn deltanet_scratch(k_heads : i32, v_heads : i32) -> DeltaNetScratch { + return DeltaNetScratch { + q : transfer(Tensor([k_heads, 128]), Memory::HBM), + k : transfer(Tensor([k_heads, 128]), Memory::HBM), + v : transfer(Tensor([v_heads, 128]), Memory::HBM), + beta : transfer(Tensor([v_heads]), Memory::HBM), + decay : transfer(Tensor([v_heads]), Memory::HBM), + o : transfer(Tensor([v_heads, 128]), Memory::HBM), + }; +} + +/// A tensor of zeros in GPU memory. +fn dn_zeros(a : i32, b : i32, c : i32) -> Tensor { + let mut x = Tensor([a, b, c]); + for i in 0..a { + for j in 0..b { + for k in 0..c { + x[i][j][k] = 0.0; + } + } + } + return transfer(x, Memory::HBM); +} + +/// The state of one layer at the start: zero. +fn deltanet_conv_state(k_heads : i32, v_heads : i32) -> Tensor { + return dn_zeros(2 * k_heads + v_heads, 128, 3); +} + +fn deltanet_state(v_heads : i32) -> Tensor { + return dn_zeros(v_heads, 128, 128); +} + +/// The Gated DeltaNet of one token: `y` (v_heads x 128 values, the input of `linear_out`) from `proj` +/// (the output of `linear_in`). z starts at `z_at` of `proj`, b at `b_at` and a at `a_at`. `conv` has +/// 4 taps for each of the (2 k_heads + v_heads) x 128 channels, channel c at 4 c, oldest tap +/// first. `neg_a` and `dt_bias` have v_heads values, and `norm` 128. +fn deltanet_step(y : &mut Tensor, conv_state : &mut Tensor, state : &mut Tensor, t : &mut DeltaNetScratch, proj : &Tensor, conv : &Tensor, neg_a : &Tensor, dt_bias : &Tensor, norm : &Tensor, z_at : i32, b_at : i32, a_at : i32, k_heads : i32, v_heads : i32, eps : f32) -> void { + let channels = (2 * k_heads + v_heads) * 128; + assert(k_heads > 0 && v_heads % k_heads == 0 && v_heads <= 64, "deltanet_step: v_heads must be a multiple of k_heads, and at most 64"); + assert(conv_state.extent(0) == 2 * k_heads + v_heads && conv_state.extent(1) == 128 && conv_state.extent(2) == 3, "deltanet_step: conv_state must be [2 k_heads + v_heads, 128, 3]"); + assert(state.extent(0) == v_heads && state.extent(1) == 128 && state.extent(2) == 128, "deltanet_step: state must be [v_heads, 128, 128]"); + assert(conv.len() == channels * 4, "deltanet_step: conv must have 4 taps for each channel"); + assert(proj.len() >= channels && proj.len() >= z_at + v_heads * 128 && proj.len() >= b_at + v_heads && proj.len() >= a_at + v_heads, "deltanet_step: proj is too short for its offsets"); + assert(neg_a.len() >= v_heads && dt_bias.len() >= v_heads && norm.len() >= 128 && y.len() >= v_heads * 128, "deltanet_step: a tensor is too short"); + deltanet_conv(&mut t.q, &mut t.k, &mut t.v, conv_state, proj, conv, k_heads, v_heads); + deltanet_gates(&mut t.beta, &mut t.decay, proj, neg_a, dt_bias, b_at, a_at, v_heads); + deltanet_recur(&mut t.o, state, &t.q, &t.k, &t.v, &t.beta, &t.decay, v_heads / k_heads, v_heads); + deltanet_gated_norm(y, &t.o, proj, norm, z_at, v_heads, eps); + return; +} + +/// The convolution and the SiLU of q, k and v, and the L2 norms of q and k. Block h does the 128 +/// channels of one head: heads 0 to k_heads - 1 of q, then those of k, then those of v. The channels +/// of `proj` are in the same order, so channel i of block h is h * 128 + i. +fn deltanet_conv(qn : &mut Tensor, kn : &mut Tensor, vv : &mut Tensor, conv_state : &mut Tensor, proj : &Tensor, conv : &Tensor, k_heads : i32, v_heads : i32) -> void { + spawn on(Topology::Device) { + for h in 0..2 * k_heads + v_heads across blocks { + let mut y = unsafe { Tensor::uninit() }; + let mut part = unsafe { Tensor::uninit() }; + for i in 0..128 across lanes { + let c = h * 128 + i; + let x0 = conv_state[h][i][0]; + let x1 = conv_state[h][i][1]; + let x2 = conv_state[h][i][2]; + let x3 = proj[c]; + let a = conv[c * 4] * x0 + conv[c * 4 + 1] * x1 + conv[c * 4 + 2] * x2 + conv[c * 4 + 3] * x3; + let s = a / (1.0 + (0.0 - a).fast_exp()); + conv_state[h][i][0] = x1; + conv_state[h][i][1] = x2; + conv_state[h][i][2] = x3; + y[i] = s; + part[i] = s * s; + } + let ss = lanes::sum(&part, 128); + let inv = 1.0 / (ss + 0.000001).sqrt(); + for i in 0..128 across lanes { + if h < k_heads { + qn[h][i] = y[i] * inv * 0.08838834764831845; + } else if h < 2 * k_heads { + kn[h - k_heads][i] = y[i] * inv; + } else { + vv[h - 2 * k_heads][i] = y[i]; + } + } + } + } + return; +} + +/// beta = sigmoid(b) and the decay exp(neg_a softplus(a + dt_bias)) of each head of v. softplus(x) +/// is x above 20, as in torch. +fn deltanet_gates(beta : &mut Tensor, decay : &mut Tensor, proj : &Tensor, neg_a : &Tensor, dt_bias : &Tensor, b_at : i32, a_at : i32, v_heads : i32) -> void { + spawn on(Topology::Device) { + for blk in 0..1 across blocks { + for j in 0..64 across lanes { + if j < v_heads { + let b = proj[b_at + j]; + beta[j] = 1.0 / (1.0 + (0.0 - b).fast_exp()); + let x = proj[a_at + j] + dt_bias[j]; + let mut sp = x; + if x <= 20.0 { + sp = simd_log(1.0 + x.fast_exp()); + } + decay[j] = (neg_a[j] * sp).fast_exp(); + } + } + } + } + return; +} + +/// The update of the state and the output q . S, for each head h of v. Block (h, vq) is one SIMD +/// group for values vq * 32 to vq * 32 + 31 of v. Lane l owns values 4 l to 4 l + 3 of k. For each +/// value of v, the lanes add up k . S, then each lane updates its 4 values of S and the lanes add up +/// q . S. Lane m keeps the output of value m. +fn deltanet_recur(o : &mut Tensor, state : &mut Tensor, qn : &Tensor, kn : &Tensor, vv : &Tensor, beta : &Tensor, decay : &Tensor, group : i32, v_heads : i32) -> void { + spawn on(Topology::Device) { + for h in 0..v_heads across blocks { + for vq in 0..4 across blocks { + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let g = h / group; + let d = 4 * l; + let q0 = qn[g][d]; + let q1 = qn[g][d + 1]; + let q2 = qn[g][d + 2]; + let q3 = qn[g][d + 3]; + let k0 = kn[g][d]; + let k1 = kn[g][d + 1]; + let k2 = kn[g][d + 2]; + let k3 = kn[g][d + 3]; + let b = beta[h]; + let dec = decay[h]; + let mut mine : f32 = 0.0; + for m in 0..32 { + let v = vq * 32 + m; + let s0 = state[h][v][d] * dec; + let s1 = state[h][v][d + 1] * dec; + let s2 = state[h][v][d + 2] * dec; + let s3 = state[h][v][d + 3] * dec; + let kv = simd_sum(s0 * k0 + s1 * k1 + s2 * k2 + s3 * k3); + let delta = (vv[h][v] - kv) * b; + let n0 = s0 + k0 * delta; + let n1 = s1 + k1 * delta; + let n2 = s2 + k2 * delta; + let n3 = s3 + k3 * delta; + state[h][v][d] = n0; + state[h][v][d + 1] = n1; + state[h][v][d + 2] = n2; + state[h][v][d + 3] = n3; + let out = simd_sum(n0 * q0 + n1 * q1 + n2 * q2 + n3 * q3); + if m == l { + mine = out; + } + } + o[h][vq * 32 + l] = mine; + } + } + } + } + } + return; +} + +/// y = rms_norm(o) * norm * silu(z), for each head of v. Block h does one head. +fn deltanet_gated_norm(y : &mut Tensor, o : &Tensor, proj : &Tensor, norm : &Tensor, z_at : i32, v_heads : i32, eps : f32) -> void { + spawn on(Topology::Device) { + for h in 0..v_heads across blocks { + let mut part = unsafe { Tensor::uninit() }; + for i in 0..128 across lanes { + let a = o[h][i]; + part[i] = a * a; + } + let ss = lanes::sum(&part, 128); + let inv = 1.0 / (ss / 128.0 + eps).sqrt(); + for i in 0..128 across lanes { + let z = proj[z_at + h * 128 + i]; + y[h * 128 + i] = o[h][i] * inv * norm[i] * (z / (1.0 + (0.0 - z).fast_exp())); + } + } + } + return; +} +//===- gated_attention.vx - Qwen app ----------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// The full attention of one token in a layer of Qwen3.5 and Qwen3.6 (#89), between the product +// `qkv` and the product `attn_out`, with the math of `modeling_qwen3_5_moe.py` of transformers: +// +// - `qkvg`, the output of `qkv`, has q (q_heads x 256), k (kv_heads x 256), v (kv_heads x 256), +// then the gate (q_heads x 256). +// - q and k get an RMS norm for each head, times their norm weights, which the weight file stores +// as 1 + w. RoPE then turns the first `rot` values of each head (rotate_half inside those +// values), and leaves the others. +// - Attention with the scale 1/sqrt(256) over the KV cache, which is f16 [position, kv_head, 256]. +// - The output is multiplied by sigmoid(gate). +// +// The attention has the design of `vec_attention` (llama.cpp's kernel_flash_attn_ext_vec, MIT +// License, Copyright (c) 2023-2026 The ggml authors), for 256 values a head: each block is a SIMD +// group of one head of q, and lane l owns values 8 l to 8 l + 7. +import core::num; +import std::nn; +import qwen::simd; + +/// The norms and RoPE of q and k at position `pos`, and the store of k and v into the caches. Block h +/// does head h of q, then the heads of k. `cos` and `sin` have rot / 2 values for each position. +fn gated_norm_rope_and_store(q_out : &mut Tensor, k_cache : &mut Tensor, v_cache : &mut Tensor, qkvg : &Tensor, q_norm : &Tensor, k_norm : &Tensor, cos : &Tensor, sin : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, rot : i32, eps : f32) -> void { + let half = rot / 2; + assert(q_out.extent(0) == q_heads && q_out.extent(1) == 256, "gated_norm_rope_and_store: q_out must be [q_heads, 256]"); + assert(k_cache.extent(0) > pos && k_cache.extent(1) == kv_heads && k_cache.extent(2) == 256 && v_cache.extent(0) > pos && v_cache.extent(1) == kv_heads && v_cache.extent(2) == 256, "gated_norm_rope_and_store: the caches must be [positions, kv_heads, 256] with a row for pos"); + assert(qkvg.len() >= (2 * q_heads + 2 * kv_heads) * 256 && q_norm.len() >= 256 && k_norm.len() >= 256, "gated_norm_rope_and_store: a tensor is too short"); + assert(rot % 2 == 0 && rot <= 256 && pos < cos.extent(0) && pos < sin.extent(0) && half <= cos.extent(1) && half <= sin.extent(1), "gated_norm_rope_and_store: `cos` and `sin` need a row for `pos` with rot / 2 values"); + spawn on(Topology::Device) { + for h in 0..q_heads + kv_heads across blocks { + let mut x = unsafe { Tensor::uninit() }; + let mut part = unsafe { Tensor::uninit() }; + for i in 0..256 across lanes { + let a = qkvg[h * 256 + i]; + x[i] = a; + part[i] = a * a; + } + let ss = lanes::sum(&part, 256); + let inv = 1.0 / (ss / 256.0 + eps).sqrt(); + for i in 0..256 across lanes { + let mut w = q_norm[i]; + if h >= q_heads { + w = k_norm[i]; + } + let a = x[i] * inv * w; + let mut r = a; + if i < rot { + // Value i, its partner, and the angle that they share. + let mut j = i; + let mut sign : f32 = -1.0; + let mut partner = i + half; + if i >= half { + j = i - half; + sign = 1.0; + partner = i - half; + } + let mut wp = q_norm[partner]; + if h >= q_heads { + wp = k_norm[partner]; + } + let b = x[partner] * inv * wp; + r = a * cos[pos][j] + sign * b * sin[pos][j]; + } + if h < q_heads { + q_out[h][i] = r; + } else { + k_cache[pos][h - q_heads][i] = r as f16; + v_cache[pos][h - q_heads][i] = qkvg[(q_heads + kv_heads + h - q_heads) * 256 + i] as f16; + } + } + } + } + return; +} + +/// The attention of the token at position `pos`, times sigmoid(gate): y[h * 256 + d] for each head +/// h of q. `part` is scratch space from `gated_attention_scratch`. +fn gated_attention(y : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, qkvg : &Tensor, pos : i32, q_heads : i32, kv_heads : i32) -> void { + assert(q.extent(0) == q_heads && q.extent(1) == 256 && q_heads % kv_heads == 0, "gated_attention: q must be [q_heads, 256], and q_heads a multiple of kv_heads"); + assert(k_cache.extent(0) > pos && k_cache.extent(1) == kv_heads && k_cache.extent(2) == 256 && v_cache.extent(0) > pos && v_cache.extent(1) == kv_heads && v_cache.extent(2) == 256, "gated_attention: the caches must be [positions, kv_heads, 256] with a row for pos"); + assert(part.extent(0) >= q_heads && part.extent(1) >= 64 && part.extent(2) == 260, "gated_attention: `part` is too small. Make it with gated_attention_scratch"); + assert(y.len() >= q_heads * 256 && qkvg.len() >= (2 * q_heads + 2 * kv_heads) * 256, "gated_attention: a tensor is too short"); + let mut nwg = 32; + if 2 * nwg * 32 < pos + 1 { + nwg = nwg * 2; + } + gated_attention_parts(part, q, k_cache, v_cache, pos, q_heads, q_heads / kv_heads, nwg, 0.0625); + gated_attention_merge(y, part, qkvg, nwg, q_heads, (q_heads + 2 * kv_heads) * 256); + return; +} + +/// The scratch space of `gated_attention`, on the CPU: up to 64 parts for each head of q, each the sum +/// of V (256 values), the largest score, and the sum of the weights. +fn gated_attention_scratch(q_heads : i32) -> Tensor { + return Tensor([q_heads, 64, 260]); +} + +/// The parts of `gated_attention`. Block (h, w) is a SIMD group for head h of q. It does the blocks of +/// 32 positions w, w + nwg, w + 2 nwg, ... up to `pos`, and writes part[h][w]: the sum of V, not +/// divided, then the largest score and the sum of the weights. For each row, the lanes add up their +/// parts of q . k, and lane r keeps the score of row r. Each lane then takes the weight of each row +/// from the lane that keeps it, for the sum of V. +fn gated_attention_parts(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, group : i32, nwg : i32, scale : f32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for w in 0..nwg across blocks { + let mut stats = unsafe { Tensor::uninit() }; + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let g = h / group; + let d = 8 * l; + let q0 = q[h][d] * scale; + let q1 = q[h][d + 1] * scale; + let q2 = q[h][d + 2] * scale; + let q3 = q[h][d + 3] * scale; + let q4 = q[h][d + 4] * scale; + let q5 = q[h][d + 5] * scale; + let q6 = q[h][d + 6] * scale; + let q7 = q[h][d + 7] * scale; + let mut big : f32 = -3.0e38; + let mut total : f32 = 0.0; + let mut o0 : f32 = 0.0; + let mut o1 : f32 = 0.0; + let mut o2 : f32 = 0.0; + let mut o3 : f32 = 0.0; + let mut o4 : f32 = 0.0; + let mut o5 : f32 = 0.0; + let mut o6 : f32 = 0.0; + let mut o7 : f32 = 0.0; + let chunks = (pos + 32) / 32; + let mut c = w; + while c < chunks { + let r0 = c * 32; + let mut mine : f32 = -3.0e38; + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > pos { + kept = pos; + } + let k0 = half4_at(k_cache, kept, g, d, 0); + let k1 = half4_at(k_cache, kept, g, d, 1); + let k2 = half4_at(k_cache, kept, g, d, 2); + let k3 = half4_at(k_cache, kept, g, d, 3); + let k4 = half4_at(k_cache, kept, g, d + 4, 0); + let k5 = half4_at(k_cache, kept, g, d + 4, 1); + let k6 = half4_at(k_cache, kept, g, d + 4, 2); + let k7 = half4_at(k_cache, kept, g, d + 4, 3); + let mut score = simd_sum(((k0 * q0 + k1 * q1) + (k2 * q2 + k3 * q3)) + ((k4 * q4 + k5 * q5) + (k6 * q6 + k7 * q7))); + if row > pos { + score = -3.0e38; + } + if r == l { + mine = score; + } + } + let top = big.max(simd_max(mine)); + let shrink = (big - top).fast_exp(); + let p = (mine - top).fast_exp(); + total = total * shrink + simd_sum(p); + o0 = o0 * shrink; + o1 = o1 * shrink; + o2 = o2 * shrink; + o3 = o3 * shrink; + o4 = o4 * shrink; + o5 = o5 * shrink; + o6 = o6 * shrink; + o7 = o7 * shrink; + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > pos { + kept = pos; + } + let pr = simd_value(p, r); + o0 = o0 + half4_at(v_cache, kept, g, d, 0) * pr; + o1 = o1 + half4_at(v_cache, kept, g, d, 1) * pr; + o2 = o2 + half4_at(v_cache, kept, g, d, 2) * pr; + o3 = o3 + half4_at(v_cache, kept, g, d, 3) * pr; + o4 = o4 + half4_at(v_cache, kept, g, d + 4, 0) * pr; + o5 = o5 + half4_at(v_cache, kept, g, d + 4, 1) * pr; + o6 = o6 + half4_at(v_cache, kept, g, d + 4, 2) * pr; + o7 = o7 + half4_at(v_cache, kept, g, d + 4, 3) * pr; + } + big = top; + c = c + nwg; + } + part[h][w][d] = o0; + part[h][w][d + 1] = o1; + part[h][w][d + 2] = o2; + part[h][w][d + 3] = o3; + part[h][w][d + 4] = o4; + part[h][w][d + 5] = o5; + part[h][w][d + 6] = o6; + part[h][w][d + 7] = o7; + // Every lane has the same largest score and sum of the weights. Lanes 0 and 1 keep them for + // the next loop. + if l < 2 { + let mut x = big; + if l == 1 { + x = total; + } + stats[s][l] = x; + } + } + for l in 0..2 across lanes(32) { + part[h][w][256 + l] = stats[s][l]; + } + } + } + } + } + return; +} + +/// Merges the first `parts` parts of `gated_attention_parts` for each head of q, and multiplies by +/// sigmoid of the gate, which starts at `gate_at` of `qkvg`. A block of 32 lanes does 32 values of one +/// head, a value for each lane. +fn gated_attention_merge(y : &mut Tensor, part : &Tensor, qkvg : &Tensor, parts : i32, q_heads : i32, gate_at : i32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for dq in 0..8 across blocks { + let mut top = unsafe { Tensor::uninit() }; + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let mut m : f32 = -3.0e38; + let mut c = l; + while c < parts { + m = m.max(part[h][c][256]); + c = c + 32; + } + top[s][l] = m; + } + let big = lanes::max(&top[s], 32); + for l in 0..32 across lanes(32) { + let d = dq * 32 + l; + let mut total : f32 = 0.0; + let mut acc : f32 = 0.0; + for c in 0..parts { + let w = (part[h][c][256] - big).fast_exp(); + total = total + w * part[h][c][257]; + acc = acc + w * part[h][c][d]; + } + let gate = qkvg[gate_at + h * 256 + d]; + y[h * 256 + d] = acc / total / (1.0 + (0.0 - gate).fast_exp()); + } + } + } + } + } + return; +} +//===- main.vx - Qwen app ---------------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// Generates tokens with greedy decoding, on the GPU: +// +// vxc src/main.vx --package qwen=src --host default \ +// --machine ~/.vx/current/fleet/m4-uma.vx -- WEIGHTS --tokens 750,75698,1445 --steps 16 +// vxc src/main.vx ... -- WEIGHTS --tokenizer TOKENIZER --prompt "def fibonacci(n):" --steps 64 +// vxc src/main.vx ... -- WEIGHTS --tokenizer TOKENIZER --chat --prompt-file FILE --steps 512 +// +// With --tokens, it prints the lines that `scripts/reference.py` prints, without the margin, and +// then the time of a token. `scripts/compare.py` compares the two outputs. +// +// With --tokenizer, a file of `scripts/convert_tokenizer.py`, the prompt is text: --prompt TEXT or +// --prompt-file FILE. The program prints the prompt and the text that it generates. It stops at a +// special token, such as <|im_end|>, or after --steps tokens. --chat puts the prompt in the chat +// format of the Instruct models and prints only the reply. --lines prints the lines of --tokens +// in place of the text. +import core::convert; +import std::time; +import std::vec; +import qwen::weights; +import qwen::model; +import qwen::qwen35; +import qwen::prefill35; +import qwen::prefill; +import qwen::session; +import qwen::speculate; +import qwen::round; +import qwen::tokenizer; + +/// The options of the command line. +struct Options { + weights : *const i8, + tokens : *const i8, + tokenizer : *const i8, + prompt : *const i8, + prompt_file : *const i8, + steps : *const i8, + has_tokens : bool, + has_tokenizer : bool, + has_prompt : bool, + has_prompt_file : bool, + has_steps : bool, + context : *const i8, + has_context : bool, + requests : *const i8, + has_requests : bool, + replies : *const i8, + has_replies : bool, + session : bool, + chat : bool, + lines : bool, + draft : *const i8, + has_draft : bool, +} + +/// The options of `argv`. Asserts that they are complete and that they fit together. +fn parse_options(argc : i32, argv : *mut *mut i8) -> Options { + assert(argc >= 4, "give: WEIGHTS --tokens 1,2,3 --steps N, or WEIGHTS --tokenizer FILE (--prompt TEXT | --prompt-file FILE) [--chat] [--lines] --steps N"); + let empty : *const i8 = ""; + let mut o = Options { + weights: unsafe { argv[1] }, tokens: empty, tokenizer: empty, prompt: empty, prompt_file: empty, + steps: empty, has_tokens: false, has_tokenizer: false, has_prompt: false, has_prompt_file: false, + has_steps: false, context: empty, has_context: false, requests: empty, has_requests: false, replies: empty, has_replies: false, session: false, chat: false, lines: false, draft: empty, has_draft: false, + }; + let mut i = 2; + while i < argc { + let name = unsafe { argv[i] }; + if same(name, "--chat") { + o.chat = true; + i = i + 1; + } else if same(name, "--session") { + o.session = true; + i = i + 1; + } else if same(name, "--lines") { + o.lines = true; + i = i + 1; + } else { + assert(i + 1 < argc, "give: WEIGHTS --tokens 1,2,3 --steps N, or WEIGHTS --tokenizer FILE (--prompt TEXT | --prompt-file FILE) [--chat] [--lines] --steps N"); + let value = unsafe { argv[i + 1] }; + if same(name, "--tokens") { + o.tokens = value; + o.has_tokens = true; + } else if same(name, "--tokenizer") { + o.tokenizer = value; + o.has_tokenizer = true; + } else if same(name, "--prompt") { + o.prompt = value; + o.has_prompt = true; + } else if same(name, "--prompt-file") { + o.prompt_file = value; + o.has_prompt_file = true; + } else if same(name, "--context") { + o.context = value; + o.has_context = true; + } else if same(name, "--requests") { + o.requests = value; + o.has_requests = true; + } else if same(name, "--replies") { + o.replies = value; + o.has_replies = true; + } else if same(name, "--draft") { + o.draft = value; + o.has_draft = true; + } else { + assert(same(name, "--steps"), "give: WEIGHTS --tokens 1,2,3 --steps N, or WEIGHTS --tokenizer FILE (--prompt TEXT | --prompt-file FILE) [--chat] [--lines] --steps N"); + o.steps = value; + o.has_steps = true; + } + i = i + 2; + } + } + if o.session { + assert(o.has_tokenizer && o.has_context && o.has_requests && o.has_replies && !o.has_tokens && !o.has_prompt && !o.has_prompt_file && !o.has_steps, "give: WEIGHTS --tokenizer FILE --session --context N --requests FILE --replies FILE"); + return o; + } + assert(o.has_steps, "give: WEIGHTS --tokens 1,2,3 --steps N, or WEIGHTS --tokenizer FILE (--prompt TEXT | --prompt-file FILE) [--chat] [--lines] --steps N"); + let one_text = o.has_prompt != o.has_prompt_file; + let no_text = !o.has_prompt && !o.has_prompt_file; + assert((o.has_tokens && no_text) || (o.has_tokenizer && !o.has_tokens && one_text), "give: WEIGHTS --tokens 1,2,3 --steps N, or WEIGHTS --tokenizer FILE (--prompt TEXT | --prompt-file FILE) [--chat] [--lines] --steps N"); + assert(o.has_tokenizer || (!o.chat && !o.lines), "--chat and --lines need --tokenizer"); + return o; +} + +/// The comma-separated numbers of `text`. Asserts that it has only digits and commas, and no empty +/// number. +fn parse_numbers(text : *const i8) -> Vec { + let mut numbers = Vec::new(); + let mut value : i32 = 0; + let mut digits = 0; + let mut empty = false; + let mut i : i64 = 0; + let mut ch = i32::from(unsafe { text[0] }); + while ch != 0 { + if ch == 44 { + empty = empty || digits == 0; + numbers.push(value); + value = 0; + digits = 0; + } else { + assert(ch >= 48 && ch <= 57, "a list of numbers can have only digits and commas"); + value = value * 10 + (ch - 48); + digits = digits + 1; + } + i = i + 1; + ch = i32::from(unsafe { text[i] }); + } + assert(!empty && digits > 0, "an empty number in a comma-separated list"); + numbers.push(value); + return numbers; +} + +/// The number of tokens that text mode runs through the model before it reads them. A read waits +/// for all the work that the GPU was given, and then the GPU has nothing to do until the CPU gives +/// it the next token: about 0.37 ms of a 21.9 ms token on the M4. The input of a token is the +/// argmax of the token before it, in GPU memory, so the GPU can run several tokens without the +/// CPU. Then the GPU waits only once for each AHEAD tokens. Up to AHEAD - 1 tokens after the end +/// of the text are run and thrown away. +const AHEAD : i32 = 8; + +/// The GPU tensor of one token. +struct Slot { + next : Tensor, +} + +/// The token in `t`. Reading it waits for the GPU to finish the work before it. +fn read_token(t : &Tensor) -> i32 { + let h = transfer(t, Memory::CPU_DRAM); + return h[0]; +} + +/// The logit `token` of `logits`. +fn read_logit(logits : &Tensor, token : i32) -> f32 { + let h = transfer(logits, Memory::CPU_DRAM); + return h[token]; +} + +/// Whether the C string `a` is `b`. +fn same(a : *const i8, b : *const i8) -> bool { + return unsafe { strcmp(a, b) } == 0; +} + +/// The token ids of the prompt: the numbers of --tokens, or the tokens of the text. +fn prompt_ids(o : &Options, t : &Tokenizer) -> Vec { + if o.has_tokens { + return parse_numbers(o.tokens); + } + let text = if o.has_prompt { + c_text(o.prompt) + } else { + read_text_file(o.prompt_file) + }; + let full = if o.chat { + chat_text(&text) + } else { + text + }; + let ids = encode(t, full.bytes, full.length); + assert(ids.len() > 0, "the prompt has no tokens"); + return ids; +} + +/// Shows token number `step`, as the loop of `main` does: its text, or a line with its logit. +/// Gives false at the end of the text, where the loop stops. +fn show(t : &Tokenizer, w : &Weights, text_mode : bool, step : i32, token : i32, logit : f32) -> bool { + if text_mode { + if is_special(t, token) || token == w.config.eos_token_id { + return false; + } + write_token(t, token); + } else { + println!("step={} token={} logit={};", step, token, logit); + } + return true; +} + +/// The logit `token` of position j of a round. +fn round_logit(r : &Round, j : i32, token : i32) -> f32 { + let h = transfer(&r.logits, Memory::CPU_DRAM); + return h[j][token]; +} + +/// The loop of `main` with speculative decoding (src/speculate.vx). Each step is a round of the +/// last token and a draft from the context, or a plain step when the draft would not pay: when the +/// longest earlier match of the end of the context is shorter than 6 tokens, or after 2 rounds in a +/// row that accepted nothing, until a longer match than theirs appears. A draft has up to `max` +/// tokens. `first` is the first generated token, from the logits in `s.logits`. Shows the same +/// `steps` tokens as the loop of `main`, and gives the number of tokens after the first. +fn generate_with_drafts(w : &Weights, s : &mut State, t : &Tokenizer, text_mode : bool, prompt : &Vec, first : i32, steps : i32, max : i32, start : &mut Instant) -> i32 { + assert(can_round(w), "--draft needs a model of Q4_0 experts with QK norms, head_dim 128 and a 6-bit lm_head"); + assert(max >= 1 && max < ROUND_MAX, "--draft must be 1 to ROUND_MAX - 1"); + assert(steps >= ROUND_MAX, "--draft needs --steps of at least ROUND_MAX"); + let mut r = new_round(&w.config); + // One run of the round kernels for each n to 8, so that their compile time is not in the time + // of a token: it restarts the clock. Larger rounds use the same kernels. The rounds write rows of + // the KV cache that the steps write again before they read them. + let mut warm = Vec::new(); + for n in 1..9 { + warm.push(first); + run_round(w, s, &mut r, &warm, prompt.len(), n); + } + let _ready = transfer(&r.next, Memory::CPU_DRAM); + *start = Instant::now(); + // The tokens of a run of plain steps: token j is in ring[j]. + let mut ring = Vec::new(); + for j in 0..AHEAD { + ring.push(Slot { + next: transfer(Tensor([1]), Memory::HBM), + }); + } + // The length of the next run of plain steps: 1 after a round, then 2, 4 and up to AHEAD while + // no draft comes up. The GPU runs the tokens of a run before the CPU reads them. Lines mode + // prints the logit of each token, so it reads each one. + let mut run = 1; + let mut context = Vec::new(); + for i in 0..prompt.len() { + context.push(prompt[i]); + } + let mut token = first; + context.push(token); + // The position of `token`, which is not in the KV cache yet. + let mut pos = prompt.len(); + let mut step = 0; + let mut rounds = 0; + let mut drafted = 0; + let mut accepted = 0; + // Rounds in a row that accepted nothing, and the length of the match of the last of them. + let mut misses = 0; + let mut missed_length = 0; + let mut going = show(t, w, text_mode, 0, token, read_logit(&s.logits, token)); + while going && step + 1 < steps { + let room = steps - step - 1; + let m = longest_match(&context); + if misses >= 2 && m.length > missed_length { + misses = 0; + } + let mut k = i32::min(i32::min(draft_length(m.length), max), room - 1); + if misses >= 2 { + k = 0; + } + let draft = tokens_after(&context, m.end, k); + k = draft.len(); + if k == 0 { + // Plain steps, with the kernels of one token each. + let mut n = 1; + if text_mode { + n = i32::min(run, room); + } + let mut h = Tensor([1]); + h[0] = token; + let input = transfer(h, Memory::HBM); + run_layers(w, s, &input, pos); + predict(w, s, &mut ring[0].next); + for j in 1..n { + run_layers(w, s, &ring[j - 1].next, pos + j); + predict(w, s, &mut ring[j].next); + } + let mut j = 0; + while j < n && going { + token = read_token(&ring[j].next); + context.push(token); + step = step + 1; + pos = pos + 1; + let mut logit : f32 = 0.0; + if !text_mode { + logit = read_logit(&s.logits, token); + } + going = show(t, w, text_mode, step, token, logit); + j = j + 1; + } + run = i32::min(run * 2, AHEAD); + } else { + run = 1; + let mut inputs = Vec::new(); + inputs.push(token); + for i in 0..k { + inputs.push(draft[i]); + } + run_round(w, s, &mut r, &inputs, pos, k + 1); + let choice = transfer(&r.next, Memory::CPU_DRAM); + rounds = rounds + 1; + drafted = drafted + k; + // c0 is the next token; each draft token that equals the choice before it adds the next one. + let mut j = 0; + let mut more = true; + while more && going { + token = choice[j]; + context.push(token); + step = step + 1; + let mut logit : f32 = 0.0; + if !text_mode { + logit = round_logit(&r, j, token); + } + going = show(t, w, text_mode, step, token, logit); + more = j < k && draft[j] == token; + if more { + accepted = accepted + 1; + j = j + 1; + } + } + pos = pos + j + 1; + if j == 0 { + misses = misses + 1; + missed_length = m.length; + } else { + misses = 0; + } + } + } + println!("rounds={} drafted={} accepted={};", rounds, drafted, accepted); + return step; +} + +/// `main` for a Qwen3.5 or Qwen3.6 model (weight file v2, arch 1). The prompt runs in chunks +/// (src/prefill35.vx). There are no drafts yet (#89). Prints the same lines diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/llama/ctx512.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/llama/ctx512.txt new file mode 100644 index 0000000..f61da32 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/llama/ctx512.txt @@ -0,0 +1,43 @@ +//===- model.vx - Qwen app --------------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// One token of a Qwen2 or Qwen3 MoE decoder on the GPU, with the kernels of `std::nn`. `State` +// holds every tensor that a token writes, and the KV cache. It is made once, before the first +// token, so the token loop allocates nothing. +import core::convert; +import core::num; +import std::nn; +import std::vec; +import qwen::attention; +import qwen::products; +import qwen::q6; +import qwen::weights; + +/// The keys and the values of every position so far, for one layer: [max_seq, kv_heads, head_dim]. +/// They are f16, half the memory of f32. The kernels compute in f32, and round only what they +/// store here. +struct Cache { + k : Tensor, + v : Tensor, +} + +/// The tensors of a mixture-of-experts layer: the router's score of each expert, the chosen +/// experts and their weights, and the SwiGLU output of each chosen expert, [experts_per_token, +/// moe_intermediate_size]. +struct Experts { + router_logits : Tensor, + ids : Tensor, + weights : Tensor, + mlp : Tensor, +} + +/// The tensors that a token writes, in GPU memory, and one `Cache` for each layer. `cos` and `sin` +/// are [max_seq, head_dim / 2]. +struct State { + max_seq : i32, + x : Tensor, + xn : Tensor, + v : Tensor, +} + +/// The tensors of a mixture-of-experts layer: the router's score of each expert, the chosen +/// experts and their weights, and the SwiGLU output of each chosen expert, [experts_per_token, +/// moe_intermediate_size]. +struct Experts { + router_logits : Tensor, + ids : Tensor, + weights : Tensor, + mlp : Tensor, +} + +/// The tensors that a token writes, in GPU memory, and one `Cache` for each layer. `cos` and `sin` +/// are [max_seq, head_dim / 2]. +struct State { + max_seq : i32, + x : Tensor, + xn : Tensor, + q : Tensor, + k : Tensor, + v : Tensor, + q_turned : Tensor, + attended : Tensor, + attention_parts : Tensor, + vec_parts : Tensor, + mlp : Tensor, + experts : Experts, + logits : Tensor, + cos : Tensor, + sin : Tensor, + caches : Vec, +} + +/// The state for up to `max_seq` positions. The angles of RoPE are computed in f64, as in +/// `reference.py`, and rounded to f32 once. +fn new_state(c : &Config, max_seq : i32) -> State { + assert(max_seq > 0 && max_seq <= c.max_positions, "max_seq must be between 1 and the max_positions of the model"); + let half = c.head_dim / 2; + let mut hcos = Tensor([max_seq, half]); + let mut hsin = Tensor([max_seq, half]); + for p in 0..max_seq { + for i in 0..half { + let angle = f64::from(p) / f64::powf(c.rope_theta, f64::from(2 * i) / f64::from(c.head_dim)); + hcos[p][i] = f64::cos(angle) as f32; + hsin[p][i] = f64::sin(angle) as f32; + } + } + // A dense model uses none of the tensors of the experts, so one value each is enough. + let experts = i32::max(c.num_experts, 1); + let chosen = i32::max(c.experts_per_token, 1); + let moe_inter = i32::max(c.moe_intermediate_size, 1); + // The flash attention of a prompt reads the cache in blocks of 64 positions. + let rows = (max_seq + 63) / 64 * 64; + let mut caches = Vec::new(); + for l in 0..c.num_layers { + caches.push(Cache { + k: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + }); + } + return State { + max_seq: max_seq, + x: transfer(Tensor([c.hidden_size]), Memory::HBM), + xn: transfer(Tensor([c.hidden_size]), Memory::HBM), + q: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + k: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + q_turned: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attended: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attention_parts: transfer(split_attention_scratch(max_seq, c.num_q_heads, c.num_kv_heads, c.head_dim), Memory::HBM), + vec_parts: transfer(vec_attention_scratch(c.num_q_heads), Memory::HBM), + mlp: transfer(Tensor([c.intermediate_size]), Memory::HBM), + experts: Experts { + router_logits: transfer(Tensor([experts]), Memory::HBM), + ids: transfer(Tensor([chosen]), Memory::HBM), + weights: transfer(Tensor([chosen]), Memory::HBM), + mlp: transfer(Tensor([chosen, moe_inter]), Memory::HBM), + }, + logits: transfer(Tensor([c.vocab_size]), Memory::HBM), + cos: transfer(hcos, Memory::HBM), + sin: transfer(hsin, Memory::HBM), + caches: caches, + }; +} + +/// y = m x, with the kernel for the dtype of `m`, which has `rows` x `cols` weights. +fn matvec(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U6 { + matvec_q6(y, &m.codes, &m.high, &m.group_scales, x, rows, cols); + } else if m.dtype == U4 { + nn_matvec_q4(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x. +fn matvec_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_matvec_q4_add(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_add(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec_add(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x, for x of [heads, head_dim]. +fn matvec_heads_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, heads : i32, head_dim : i32) -> void { + if m.dtype == U4 { + matvec_q4_heads_add_blocks(y, &m.codes, &m.group_scales, x, rows, heads, head_dim); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_heads_add(y, &m.codes, &m.scales, x, rows, heads, head_dim); + } else { + nn_matvec_heads_add(y, &m.bf16, x, rows, heads, head_dim); + } + return; +} + +/// The Q, K and V of x: m x + b, split by heads. +fn qkv(q : &mut Tensor, k : &mut Tensor, v : &mut Tensor, m : &WeightMatrix, b : &Tensor, x : &Tensor, c : &Config) -> void { + if m.dtype == U4 { + qkv_q4_blocks(q, k, v, &m.codes, &m.group_scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } else if m.dtype == F8E4M3 { + nn_qkv_fp8(q, k, v, &m.codes, &m.scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } else { + nn_qkv(q, k, v, &m.bf16, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } + return; +} + +/// The SwiGLU of a dense MLP, for the gate rows and then the up rows of `m`. +fn swiglu(out : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_swiglu_q4(out, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_swiglu_fp8(out, &m.codes, &m.scales, x, rows, cols); + } else { + nn_swiglu(out, &m.bf16, x, rows, cols); + } + return; +} + +/// The mixture of experts of a layer: the router chooses experts_per_token experts and their +/// weights, and x gets the sum of their outputs for xn, each times its weight. +fn add_experts(e : &mut Experts, x : &mut Tensor, xn : &Tensor, layer : &Layer, c : &Config) -> void { + let k = c.experts_per_token; + let inter = c.moe_intermediate_size; + nn_matvec(&mut e.router_logits, &layer.router, xn, c.num_experts, c.hidden_size); + nn_top_k(&mut e.ids, &mut e.weights, &e.router_logits, c.num_experts, k); + let gate_up = &layer.gate_up; + let down = &layer.down; + if gate_up.dtype == U4 { + moe_swiglu_q4_blocks(&mut e.mlp, &gate_up.codes, &gate_up.group_scales, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + moe_down_q4_add_blocks(x, &down.codes, &down.group_scales, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + } else { + assert(gate_up.dtype == BF16, "the experts of a mixture-of-experts model must be bf16 or Q4_0"); + nn_moe_swiglu(&mut e.mlp, &gate_up.bf16, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + nn_moe_down_add(x, &down.bf16, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + } + return; +} + +/// Runs the token in `token` at position `pos` through every layer. The hidden state of the +/// token is then in `s.x`, and its keys and values are in the caches. +fn run_layers(w : &Weights, s : &mut State, token : &Tensor, pos : i32) -> void { + let c = &w.config; + let eps = c.rms_norm_eps as f32; + assert(pos >= 0 && pos < s.max_seq, "the position is past the end of the KV cache"); + nn_embed(&mut s.x, &w.embed, token, c.hidden_size); + let mut l = 0; + for cache in s.caches.iter_mut() { + let layer = &w.layers[l]; + nn_rms_norm(&mut s.xn, &s.x, &layer.attn_norm, c.hidden_size, eps); + qkv(&mut s.q, &mut s.k, &mut s.v, &layer.qkv, &layer.qkv_bias, &s.xn, c); + if c.qk_norm { + norm_rope_and_store(&mut s.q_turned, &mut cache.k, &mut cache.v, &s.q, &s.k, &s.v, &layer.q_norm, &layer.k_norm, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.head_dim, eps); + } else { + rope_and_store(&mut s.q_turned, &mut cache.k, &mut cache.v, &s.q, &s.k, &s.v, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } + if c.head_dim == 128 { + vec_attention(&mut s.attended, &mut s.vec_parts, &s.q_turned, &cache.k, &cache.v, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } else { + split_attention(&mut s.attended, &mut s.attention_parts, &s.q_turned, &cache.k, &cache.v, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } + matvec_heads_add(&mut s.x, &layer.attn_out, &s.attended, c.hidden_size, c.num_q_heads, c.head_dim); + nn_rms_norm(&mut s.xn, &s.x, &layer.mlp_norm, c.hidden_size, eps); + if c.num_experts > 0 { + add_experts(&mut s.experts, &mut s.x, &s.xn, layer, c); + } else { + swiglu(&mut s.mlp, &layer.gate_up, &s.xn, c.intermediate_size, c.hidden_size); + matvec_add(&mut s.x, &layer.down, &s.mlp, c.hidden_size, c.intermediate_size); + } + l = l + 1; + } + return; +} + +/// The logits of the token whose hidden state is in `s.x`, and in `next` the index of the largest +/// one. Both stay in GPU memory. +fn predict(w : &Weights, s : &mut State, next : &mut Tensor) -> void { + let c = &w.config; + nn_rms_norm(&mut s.xn, &s.x, &w.final_norm, c.hidden_size, c.rms_norm_eps as f32); + if c.tied_embeddings { + nn_matvec(&mut s.logits, &w.embed, &s.xn, c.vocab_size, c.hidden_size); + } else { + matvec(&mut s.logits, &w.lm_head, &s.xn, c.vocab_size, c.hidden_size); + } + nn_argmax(next, &s.logits, c.vocab_size); + return; +} +//===- attention.vx - Qwen app ----------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// The attention of one generated token, with the positions split among blocks. This is a copy of +// `nn_attention` and its kernels from `std::nn` on Vx main (vx-lang/Vx#3216), with `split_` in place +// of `nn_` in their names. Vx v0.0.4 has the older `nn_attention`, which has one block for each head +// of Q, so its time grows with the number of positions. Remove this file, and call `nn_attention` +// of `std::nn`, when a Vx release has the new one (#4). +// +// `vec_attention`, for head_dim 128, has the design of llama.cpp's flash attention for one token +// (kernel_flash_attn_ext_vec and kernel_flash_attn_ext_vec_reduce), MIT License, Copyright (c) 2023-2026 +// The ggml authors. scripts/mlir_kernels/decode_attention.py writes its kernels: change that script, not +// the MLIR. +import core::num; +import std::nn; + +/// Attention of the token at position `pos` over rows 0 to `pos` of the KV cache, with a softmax +/// of the scores q . k / sqrt(head_dim). `part` is scratch space from `split_attention_scratch`. +/// +/// The blocks of the first kernel split the positions, 32 to a block below position 640 and 64 from +/// there on. A block serves the 8 heads of Q that share a head of K and V, so it reads each row of +/// the cache once for all 8. A second kernel merges the parts of the blocks for each head. +fn split_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_heads % kv_heads == 0, "split_attention: q_heads must be a multiple of kv_heads"); + assert(head_dim % 32 == 0 && head_dim <= 128, "split_attention: head_dim must be a multiple of 32, and at most 128"); + let mut n_pos = 32; + if pos >= 640 { + n_pos = 64; + } + assert(part.extent(0) >= kv_heads * ((q_heads / kv_heads + 7) / 8) && part.extent(1) >= (pos + n_pos) / n_pos && part.extent(2) >= 8 && part.extent(3) >= head_dim + 2, "split_attention: `part` is too small for this position. Make it with split_attention_scratch"); + if n_pos == 32 { + split_attention_parts_32(part, q, k_cache, v_cache, pos, q_heads, kv_heads, head_dim); + } else { + split_attention_parts_64(part, q, k_cache, v_cache, pos, q_heads, kv_heads, head_dim); + } + split_attention_merge(out, part, pos, n_pos, q_heads, kv_heads, head_dim); + return; +} + +/// Attention of the token at position `pos`, as `split_attention`, for head_dim 128, with the kernels of +/// llama.cpp's flash attention for one token. `vec_attention_parts` splits the blocks of 32 positions among +/// `nwg` SIMD groups for each head of Q: 32 of them, or 64 when each of 32 would have more than 2 blocks. +/// (llama.cpp goes on to 4 SIMD groups of 32 a block, but 128 parts are no faster here: their merge costs what +/// they save.) `vec_attention_merge` then merges the parts. `part` is scratch space from +/// `vec_attention_scratch`. +fn vec_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_heads % kv_heads == 0 && head_dim == 128, "vec_attention: q_heads must be a multiple of kv_heads, and head_dim 128"); + assert(part.extent(0) >= q_heads && part.extent(1) >= 128 && part.extent(2) == 132, "vec_attention: `part` is too small. Make it with vec_attention_scratch"); + let mut nwg = 32; + if 2 * nwg * 32 < pos + 1 { + nwg = nwg * 2; + } + vec_attention_parts(part, q, k_cache, v_cache, pos, q_heads, q_heads / kv_heads, nwg, 1.0 / (head_dim as f32).sqrt()); + vec_attention_merge(out, part, nwg, q_heads); + return; +} + +/// The scratch space of `vec_attention`, on the CPU: up to 128 parts for each head of Q, each the sum of V +/// (128 values), the largest score, and the sum of the weights. A part has 132 values, so that each starts +/// at a multiple of 16 bytes. +fn vec_attention_scratch(q_heads : i32) -> Tensor { + return Tensor([q_heads, 128, 132]); +} + +/// The parts of `vec_attention`, as llama.cpp's kernel_flash_attn_ext_vec. Block (h, w) is a SIMD group for +/// query head h. It does the blocks of 32 positions w, w + nwg, w + 2 nwg, ... up to `pos`, and writes +/// part[h][w]. Lane l owns values 4 l to 4 l + 3 of the head, so that the 32 lanes read a row of K or V in +/// one 256-byte load. For each row, the lanes add up their parts of q . k; then each lane keeps the score +/// of one row, and the lanes take the weights of the rows from each other for the sum of V. A part is the +/// sum of V, not divided, then the largest score and the sum of the weights. +fn vec_attention_parts(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, group : i32, nwg : i32, scale : f32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for w in 0..nwg across blocks { + let g = h / group; + let _d = mlir!( threads : 32, inputs : (%part = part : memref, %q = q : memref, %k3 = k_cache : memref, %v3 = v_cache : memref, %pos = pos : i32, %nwg = nwg : i32, %scale = scale : f32, %h = h : i32, %w = w : i32, %g = g : i32), returns : i32, dialects : ["arith", "memref", "scf", "gpu", "vector", "math"], ensures : [reads_only(q), reads_only(k_cache), reads_only(v_cache), writes_only(part[h][w])]) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %c4 = arith.constant 4 : index + %c32 = arith.constant 32 : index + %c128 = arith.constant 128 : index + %c129 = arith.constant 129 : index + %c32i = arith.constant 32 : i32 + %neg = arith.constant -3.0e38 : f32 + %zero = arith.constant 0.0 : f32 + %vz4 = arith.constant dense<0.0> : vector<4xf32> + %l = gpu.thread_id x + %l4 = arith.muli %l, %c4 : index + %hi = arith.index_cast %h : i32 to index + %wi = arith.index_cast %w : i32 to index + %gi = arith.index_cast %g : i32 to index + %posi = arith.index_cast %pos : i32 to index + %nwgi = arith.index_cast %nwg : i32 to index + %g128 = arith.muli %gi, %c128 : index + %kd = arith.addi %g128, %l4 : index + %P = memref.dim %k3, %c0 : memref + %KH = memref.dim %k3, %c1 : memref + %Wd = arith.muli %KH, %c128 : index + %k = memref.reinterpret_cast %k3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to memref> + %v = memref.reinterpret_cast %v3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to memref> + %qv = vector.load %q[%hi, %l4] {alignment = 16} : memref, vector<4xf32> + %scv = vector.broadcast %scale : f32 to vector<4xf32> + %qs = arith.mulf %qv, %scv : vector<4xf32> + %nkv = arith.addi %posi, %c32 : index + %chunks = arith.divui %nkv, %c32 : index + %st:3 = scf.for %ic = %wi to %chunks step %nwgi iter_args(%M = %neg, %S = %zero, %o = %vz4) -> (f32, f32, vector<4xf32>) { + %r0 = arith.muli %ic, %c32 : index + %my = scf.for %cc = %c0 to %c32 step %c1 iter_args(%m = %neg) -> (f32) { + %row = arith.addi %r0, %cc : index + %rowc = arith.minui %row, %posi : index + %kh = vector.load %k[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> + %kf = arith.extf %kh : vector<4xf16> to vector<4xf32> + %pr = arith.mulf %kf, %qs : vector<4xf32> + %pl = vector.reduction , %pr : vector<4xf32> into f32 + %sc = gpu.subgroup_reduce add %pl : (f32) -> f32 + %live = arith.cmpi ule, %row, %posi : index + %scm = arith.select %live, %sc, %neg : f32 + %mine = arith.cmpi eq, %cc, %l : index + %m2 = arith.select %mine, %scm, %m : f32 + scf.yield %m2 : f32 + } + %bm = gpu.subgroup_reduce maxnumf %my : (f32) -> f32 + %Mn = arith.maxnumf %M, %bm : f32 + %dm = arith.subf %M, %Mn : f32 + %ms = math.exp %dm : f32 + %dp = arith.subf %my, %Mn : f32 + %p = math.exp %dp : f32 + %bs = gpu.subgroup_reduce add %p : (f32) -> f32 + %Ss = arith.mulf %S, %ms : f32 + %Sn = arith.addf %Ss, %bs : f32 + %msv = vector.broadcast %ms : f32 to vector<4xf32> + %o1 = arith.mulf %o, %msv : vector<4xf32> + %o2 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%oa = %o1) -> (vector<4xf32>) { + %row = arith.addi %r0, %cc : index + %rowc = arith.minui %row, %posi : index + %vh = vector.load %v[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> + %vf = arith.extf %vh : vector<4xf16> to vector<4xf32> + %cci = arith.index_cast %cc : index to i32 + %pc, %pv = gpu.shuffle idx %p, %cci, %c32i : f32 + %pcv = vector.broadcast %pc : f32 to vector<4xf32> + %on = vector.fma %vf, %pcv, %oa : vector<4xf32> + scf.yield %on : vector<4xf32> + } + scf.yield %Mn, %Sn, %o2 : f32, f32, vector<4xf32> + } + vector.store %st#2, %part[%hi, %wi, %l4] : memref, vector<4xf32> + %lane0 = arith.cmpi eq, %l, %c0 : index + scf.if %lane0 { + memref.store %st#0, %part[%hi, %wi, %c128] : memref + memref.store %st#1, %part[%hi, %wi, %c129] : memref + } + macro.yield %h : i32 + }; + } + } + } + return; +} + +/// Merges the first `parts` parts of `vec_attention_parts` for each head of Q, as llama.cpp's +/// kernel_flash_attn_ext_vec_reduce. A block of 4 SIMD groups does one head: each lane weighs up to 4 parts, +/// and the SIMD groups add them up for 4 values of the head at a time. +fn vec_attention_merge(out : &mut Tensor, part : &Tensor, parts : i32, q_heads : i32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + let _d = mlir!( threads : 128, inputs : (%out = out : memref, %part diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/vx/ctx16384.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/vx/ctx16384.txt new file mode 100644 index 0000000..f6748f0 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/vx/ctx16384.txt @@ -0,0 +1,902 @@ +//===- model.vx - Qwen app --------------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// One token of a Qwen2 or Qwen3 MoE decoder on the GPU, with the kernels of `std::nn`. `State` +// holds every tensor that a token writes, and the KV cache. It is made once, before the first +// token, so the token loop allocates nothing. +import core::convert; +import core::num; +import std::nn; +import std::vec; +import qwen::attention; +import qwen::products; +import qwen::q6; +import qwen::weights; + +/// The keys and the values of every position so far, for one layer: [max_seq, kv_heads, head_dim]. +/// They are f16, half the memory of f32. The kernels compute in f32, and round only what they +/// store here. +struct Cache { + k : Tensor, + v : Tensor, +} + +/// The tensors of a mixture-of-experts layer: the router's score of each expert, the chosen +/// experts and their weights, and the SwiGLU output of each chosen expert, [experts_per_token, +/// moe_intermediate_size]. +struct Experts { + router_logits : Tensor, + ids : Tensor, + weights : Tensor, + mlp : Tensor, +} + +/// The tensors that a token writes, in GPU memory, and one `Cache` for each layer. `cos` and `sin` +/// are [max_seq, head_dim / 2]. +struct State { + max_seq : i32, + x : Tensor, + xn : Tensor, + q : Tensor, + k : Tensor, + v : Tensor, + q_turned : Tensor, + attended : Tensor, + attention_parts : Tensor, + vec_parts : Tensor, + mlp : Tensor, + experts : Experts, + logits : Tensor, + cos : Tensor, + sin : Tensor, + caches : Vec, +} + +/// The state for up to `max_seq` positions. The angles of RoPE are computed in f64, as in +/// `reference.py`, and rounded to f32 once. +fn new_state(c : &Config, max_seq : i32) -> State { + assert(max_seq > 0 && max_seq <= c.max_positions, "max_seq must be between 1 and the max_positions of the model"); + let half = c.head_dim / 2; + let mut hcos = Tensor([max_seq, half]); + let mut hsin = Tensor([max_seq, half]); + for p in 0..max_seq { + for i in 0..half { + let angle = f64::from(p) / f64::powf(c.rope_theta, f64::from(2 * i) / f64::from(c.head_dim)); + hcos[p][i] = f64::cos(angle) as f32; + hsin[p][i] = f64::sin(angle) as f32; + } + } + // A dense model uses none of the tensors of the experts, so one value each is enough. + let experts = i32::max(c.num_experts, 1); + let chosen = i32::max(c.experts_per_token, 1); + let moe_inter = i32::max(c.moe_intermediate_size, 1); + // The flash attention of a prompt reads the cache in blocks of 64 positions. + let rows = (max_seq + 63) / 64 * 64; + let mut caches = Vec::new(); + for l in 0..c.num_layers { + caches.push(Cache { + k: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + }); + } + return State { + max_seq: max_seq, + x: transfer(Tensor([c.hidden_size]), Memory::HBM), + xn: transfer(Tensor([c.hidden_size]), Memory::HBM), + q: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + k: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + q_turned: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attended: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attention_parts: transfer(split_attention_scratch(max_seq, c.num_q_heads, c.num_kv_heads, c.head_dim), Memory::HBM), + vec_parts: transfer(vec_attention_scratch(c.num_q_heads), Memory::HBM), + mlp: transfer(Tensor([c.intermediate_size]), Memory::HBM), + experts: Experts { + router_logits: transfer(Tensor([experts]), Memory::HBM), + ids: transfer(Tensor([chosen]), Memory::HBM), + weights: transfer(Tensor([chosen]), Memory::HBM), + mlp: transfer(Tensor([chosen, moe_inter]), Memory::HBM), + }, + logits: transfer(Tensor([c.vocab_size]), Memory::HBM), + cos: transfer(hcos, Memory::HBM), + sin: transfer(hsin, Memory::HBM), + caches: caches, + }; +} + +/// y = m x, with the kernel for the dtype of `m`, which has `rows` x `cols` weights. +fn matvec(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U6 { + matvec_q6(y, &m.codes, &m.high, &m.group_scales, x, rows, cols); + } else if m.dtype == U4 { + nn_matvec_q4(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x. +fn matvec_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_matvec_q4_add(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_add(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec_add(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x, for x of [heads, head_dim]. +fn matvec_heads_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, heads : i32, head_dim : i32) -> void { + if m.dtype == U4 { + matvec_q4_heads_add_blocks(y, &m.codes, &m.group_scales, x, rows, heads, head_dim); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_heads_add(y, &m.codes, &m.scales, x, rows, heads, head_dim); + } else { + nn_matvec_heads_add(y, &m.bf16, x, rows, heads, head_dim); + } + return; +} + +/// The Q, K and V of x: m x + b, split by heads. +fn qkv(q : &mut Tensor, k : &mut Tensor, v : &mut Tensor, m : &WeightMatrix, b : &Tensor, x : &Tensor, c : &Config) -> void { + if m.dtype == U4 { + qkv_q4_blocks(q, k, v, &m.codes, &m.group_scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } else if m.dtype == F8E4M3 { + nn_qkv_fp8(q, k, v, &m.codes, &m.scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } else { + nn_qkv(q, k, v, &m.bf16, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } + return; +} + +/// The SwiGLU of a dense MLP, for the gate rows and then the up rows of `m`. +fn swiglu(out : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_swiglu_q4(out, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_swiglu_fp8(out, &m.codes, &m.scales, x, rows, cols); + } else { + nn_swiglu(out, &m.bf16, x, rows, cols); + } + return; +} + +/// The mixture of experts of a layer: the router chooses experts_per_token experts and their +/// weights, and x gets the sum of their outputs for xn, each times its weight. +fn add_experts(e : &mut Experts, x : &mut Tensor, xn : &Tensor, layer : &Layer, c : &Config) -> void { + let k = c.experts_per_token; + let inter = c.moe_intermediate_size; + nn_matvec(&mut e.router_logits, &layer.router, xn, c.num_experts, c.hidden_size); + nn_top_k(&mut e.ids, &mut e.weights, &e.router_logits, c.num_experts, k); + let gate_up = &layer.gate_up; + let down = &layer.down; + if gate_up.dtype == U4 { + moe_swiglu_q4_blocks(&mut e.mlp, &gate_up.codes, &gate_up.group_scales, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + moe_down_q4_add_blocks(x, &down.codes, &down.group_scales, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + } else { + assert(gate_up.dtype == BF16, "the experts of a mixture-of-experts model must be bf16 or Q4_0"); + nn_moe_swiglu(&mut e.mlp, &gate_up.bf16, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + nn_moe_down_add(x, &down.bf16, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + } + return; +} + +/// Runs the token in `token` at position `pos` through every layer. The hidden state of the +/// token is then in `s.x`, and its keys and values are in the caches. +fn run_layers(w : &Weights, s : &mut State, token : &Tensor, pos : i32) -> void { + let c = &w.config; + let eps = c.rms_norm_eps as f32; + assert(pos >= 0 && pos < s.max_seq, "the position is past the end of the KV cache"); + nn_embed(&mut s.x, &w.embed, token, c.hidden_size); + let mut l = 0; + for cache in s.caches.iter_mut() { + let layer = &w.layers[l]; + nn_rms_norm(&mut s.xn, &s.x, &layer.attn_norm, c.hidden_size, eps); + qkv(&mut s.q, &mut s.k, &mut s.v, &layer.qkv, &layer.qkv_bias, &s.xn, c); + if c.qk_norm { + norm_rope_and_store(&mut s.q_turned, &mut cache.k, &mut cache.v, &s.q, &s.k, &s.v, &layer.q_norm, &layer.k_norm, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.head_dim, eps); + } else { + rope_and_store(&mut s.q_turned, &mut cache.k, &mut cache.v, &s.q, &s.k, &s.v, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } + if c.head_dim == 128 { + vec_attention(&mut s.attended, &mut s.vec_parts, &s.q_turned, &cache.k, &cache.v, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } else { + split_attention(&mut s.attended, &mut s.attention_parts, &s.q_turned, &cache.k, &cache.v, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } + matvec_heads_add(&mut s.x, &layer.attn_out, &s.attended, c.hidden_size, c.num_q_heads, c.head_dim); + nn_rms_norm(&mut s.xn, &s.x, &layer.mlp_norm, c.hidden_size, eps); + if c.num_experts > 0 { + add_experts(&mut s.experts, &mut s.x, &s.xn, layer, c); + } else { + swiglu(&mut s.mlp, &layer.gate_up, &s.xn, c.intermediate_size, c.hidden_size); + matvec_add(&mut s.x, &layer.down, &s.mlp, c.hidden_size, c.intermediate_size); + } + l = l + 1; + } + return; +} + +/// The logits of the token whose hidden state is in `s.x`, and in `next` the index of the largest +/// one. Both stay in GPU memory. +fn predict(w : &Weights, s : &mut State, next : &mut Tensor) -> void { + let c = &w.config; + nn_rms_norm(&mut s.xn, &s.x, &w.final_norm, c.hidden_size, c.rms_norm_eps as f32); + if c.tied_embeddings { + nn_matvec(&mut s.logits, &w.embed, &s.xn, c.vocab_size, c.hidden_size); + } else { + matvec(&mut s.logits, &w.lm_head, &s.xn, c.vocab_size, c.hidden_size); + } + nn_argmax(next, &s.logits, c.vocab_size); + return; +} +//===- attention.vx - Qwen app ----------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// The attention of one generated token, with the positions split among blocks. This is a copy of +// `nn_attention` and its kernels from `std::nn` on Vx main (vx-lang/Vx#3216), with `split_` in place +// of `nn_` in their names. Vx v0.0.4 has the older `nn_attention`, which has one block for each head +// of Q, so its time grows with the number of positions. Remove this file, and call `nn_attention` +// of `std::nn`, when a Vx release has the new one (#4). +// +// `vec_attention`, for head_dim 128, has the design of llama.cpp's flash attention for one token +// (kernel_flash_attn_ext_vec and kernel_flash_attn_ext_vec_reduce), MIT License, Copyright (c) 2023-2026 +// The ggml authors. scripts/mlir_kernels/decode_attention.py writes its kernels: change that script, not +// the MLIR. +import core::num; +import std::nn; + +/// Attention of the token at position `pos` over rows 0 to `pos` of the KV cache, with a softmax +/// of the scores q . k / sqrt(head_dim). `part` is scratch space from `split_attention_scratch`. +/// +/// The blocks of the first kernel split the positions, 32 to a block below position 640 and 64 from +/// there on. A block serves the 8 heads of Q that share a head of K and V, so it reads each row of +/// the cache once for all 8. A second kernel merges the parts of the blocks for each head. +fn split_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_heads % kv_heads == 0, "split_attention: q_heads must be a multiple of kv_heads"); + assert(head_dim % 32 == 0 && head_dim <= 128, "split_attention: head_dim must be a multiple of 32, and at most 128"); + let mut n_pos = 32; + if pos >= 640 { + n_pos = 64; + } + assert(part.extent(0) >= kv_heads * ((q_heads / kv_heads + 7) / 8) && part.extent(1) >= (pos + n_pos) / n_pos && part.extent(2) >= 8 && part.extent(3) >= head_dim + 2, "split_attention: `part` is too small for this position. Make it with split_attention_scratch"); + if n_pos == 32 { + split_attention_parts_32(part, q, k_cache, v_cache, pos, q_heads, kv_heads, head_dim); + } else { + split_attention_parts_64(part, q, k_cache, v_cache, pos, q_heads, kv_heads, head_dim); + } + split_attention_merge(out, part, pos, n_pos, q_heads, kv_heads, head_dim); + return; +} + +/// Attention of the token at position `pos`, as `split_attention`, for head_dim 128, with the kernels of +/// llama.cpp's flash attention for one token. `vec_attention_parts` splits the blocks of 32 positions among +/// `nwg` SIMD groups for each head of Q: 32 of them, or 64 when each of 32 would have more than 2 blocks. +/// (llama.cpp goes on to 4 SIMD groups of 32 a block, but 128 parts are no faster here: their merge costs what +/// they save.) `vec_attention_merge` then merges the parts. `part` is scratch space from +/// `vec_attention_scratch`. +fn vec_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_heads % kv_heads == 0 && head_dim == 128, "vec_attention: q_heads must be a multiple of kv_heads, and head_dim 128"); + assert(part.extent(0) >= q_heads && part.extent(1) >= 128 && part.extent(2) == 132, "vec_attention: `part` is too small. Make it with vec_attention_scratch"); + let mut nwg = 32; + if 2 * nwg * 32 < pos + 1 { + nwg = nwg * 2; + } + vec_attention_parts(part, q, k_cache, v_cache, pos, q_heads, q_heads / kv_heads, nwg, 1.0 / (head_dim as f32).sqrt()); + vec_attention_merge(out, part, nwg, q_heads); + return; +} + +/// The scratch space of `vec_attention`, on the CPU: up to 128 parts for each head of Q, each the sum of V +/// (128 values), the largest score, and the sum of the weights. A part has 132 values, so that each starts +/// at a multiple of 16 bytes. +fn vec_attention_scratch(q_heads : i32) -> Tensor { + return Tensor([q_heads, 128, 132]); +} + +/// The parts of `vec_attention`, as llama.cpp's kernel_flash_attn_ext_vec. Block (h, w) is a SIMD group for +/// query head h. It does the blocks of 32 positions w, w + nwg, w + 2 nwg, ... up to `pos`, and writes +/// part[h][w]. Lane l owns values 4 l to 4 l + 3 of the head, so that the 32 lanes read a row of K or V in +/// one 256-byte load. For each row, the lanes add up their parts of q . k; then each lane keeps the score +/// of one row, and the lanes take the weights of the rows from each other for the sum of V. A part is the +/// sum of V, not divided, then the largest score and the sum of the weights. +fn vec_attention_parts(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, group : i32, nwg : i32, scale : f32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for w in 0..nwg across blocks { + let g = h / group; + let _d = mlir!( threads : 32, inputs : (%part = part : memref, %q = q : memref, %k3 = k_cache : memref, %v3 = v_cache : memref, %pos = pos : i32, %nwg = nwg : i32, %scale = scale : f32, %h = h : i32, %w = w : i32, %g = g : i32), returns : i32, dialects : ["arith", "memref", "scf", "gpu", "vector", "math"], ensures : [reads_only(q), reads_only(k_cache), reads_only(v_cache), writes_only(part[h][w])]) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %c4 = arith.constant 4 : index + %c32 = arith.constant 32 : index + %c128 = arith.constant 128 : index + %c129 = arith.constant 129 : index + %c32i = arith.constant 32 : i32 + %neg = arith.constant -3.0e38 : f32 + %zero = arith.constant 0.0 : f32 + %vz4 = arith.constant dense<0.0> : vector<4xf32> + %l = gpu.thread_id x + %l4 = arith.muli %l, %c4 : index + %hi = arith.index_cast %h : i32 to index + %wi = arith.index_cast %w : i32 to index + %gi = arith.index_cast %g : i32 to index + %posi = arith.index_cast %pos : i32 to index + %nwgi = arith.index_cast %nwg : i32 to index + %g128 = arith.muli %gi, %c128 : index + %kd = arith.addi %g128, %l4 : index + %P = memref.dim %k3, %c0 : memref + %KH = memref.dim %k3, %c1 : memref + %Wd = arith.muli %KH, %c128 : index + %k = memref.reinterpret_cast %k3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to memref> + %v = memref.reinterpret_cast %v3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to memref> + %qv = vector.load %q[%hi, %l4] {alignment = 16} : memref, vector<4xf32> + %scv = vector.broadcast %scale : f32 to vector<4xf32> + %qs = arith.mulf %qv, %scv : vector<4xf32> + %nkv = arith.addi %posi, %c32 : index + %chunks = arith.divui %nkv, %c32 : index + %st:3 = scf.for %ic = %wi to %chunks step %nwgi iter_args(%M = %neg, %S = %zero, %o = %vz4) -> (f32, f32, vector<4xf32>) { + %r0 = arith.muli %ic, %c32 : index + %my = scf.for %cc = %c0 to %c32 step %c1 iter_args(%m = %neg) -> (f32) { + %row = arith.addi %r0, %cc : index + %rowc = arith.minui %row, %posi : index + %kh = vector.load %k[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> + %kf = arith.extf %kh : vector<4xf16> to vector<4xf32> + %pr = arith.mulf %kf, %qs : vector<4xf32> + %pl = vector.reduction , %pr : vector<4xf32> into f32 + %sc = gpu.subgroup_reduce add %pl : (f32) -> f32 + %live = arith.cmpi ule, %row, %posi : index + %scm = arith.select %live, %sc, %neg : f32 + %mine = arith.cmpi eq, %cc, %l : index + %m2 = arith.select %mine, %scm, %m : f32 + scf.yield %m2 : f32 + } + %bm = gpu.subgroup_reduce maxnumf %my : (f32) -> f32 + %Mn = arith.maxnumf %M, %bm : f32 + %dm = arith.subf %M, %Mn : f32 + %ms = math.exp %dm : f32 + %dp = arith.subf %my, %Mn : f32 + %p = math.exp %dp : f32 + %bs = gpu.subgroup_reduce add %p : (f32) -> f32 + %Ss = arith.mulf %S, %ms : f32 + %Sn = arith.addf %Ss, %bs : f32 + %msv = vector.broadcast %ms : f32 to vector<4xf32> + %o1 = arith.mulf %o, %msv : vector<4xf32> + %o2 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%oa = %o1) -> (vector<4xf32>) { + %row = arith.addi %r0, %cc : index + %rowc = arith.minui %row, %posi : index + %vh = vector.load %v[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> + %vf = arith.extf %vh : vector<4xf16> to vector<4xf32> + %cci = arith.index_cast %cc : index to i32 + %pc, %pv = gpu.shuffle idx %p, %cci, %c32i : f32 + %pcv = vector.broadcast %pc : f32 to vector<4xf32> + %on = vector.fma %vf, %pcv, %oa : vector<4xf32> + scf.yield %on : vector<4xf32> + } + scf.yield %Mn, %Sn, %o2 : f32, f32, vector<4xf32> + } + vector.store %st#2, %part[%hi, %wi, %l4] : memref, vector<4xf32> + %lane0 = arith.cmpi eq, %l, %c0 : index + scf.if %lane0 { + memref.store %st#0, %part[%hi, %wi, %c128] : memref + memref.store %st#1, %part[%hi, %wi, %c129] : memref + } + macro.yield %h : i32 + }; + } + } + } + return; +} + +/// Merges the first `parts` parts of `vec_attention_parts` for each head of Q, as llama.cpp's +/// kernel_flash_attn_ext_vec_reduce. A block of 4 SIMD groups does one head: each lane weighs up to 4 parts, +/// and the SIMD groups add them up for 4 values of the head at a time. +fn vec_attention_merge(out : &mut Tensor, part : &Tensor, parts : i32, q_heads : i32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + let _d = mlir!( threads : 128, inputs : (%out = out : memref, %part = part : memref, %parts = parts : i32, %h = h : i32), returns : i32, dialects : ["arith", "memref", "scf", "gpu", "vector", "math"], ensures : [reads_only(part), writes_only(out[h])]) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %c2 = arith.constant 2 : index + %c3 = arith.constant 3 : index + %c4 = arith.constant 4 : index + %c16 = arith.constant 16 : index + %c32 = arith.constant 32 : index + %c64 = arith.constant 64 : index + %c96 = arith.constant 96 : index + %c128 = arith.constant 128 : index + %c129 = arith.constant 129 : index + %neg = arith.constant -3.0e38 : f32 + %zero = arith.constant 0.0 : f32 + %one = arith.constant 1.0 : f32 + %tid = gpu.thread_id x + %sg = arith.divui %tid, %c32 : index + %l = arith.remui %tid, %c32 : index + %hi = arith.index_cast %h : i32 to index + %np = arith.index_cast %parts : i32 to index + %last = arith.subi %np, %c1 : index + %p0 = arith.addi %l, %c0 : index + %live0 = arith.cmpi ult, %p0, %np : index + %pc0 = arith.minui %p0, %last : index + %mr0 = memref.load %part[%hi, %pc0, %c128] : memref + %m0 = arith.select %live0, %mr0, %neg : f32 + %p1 = arith.addi %l, %c32 : index + %live1 = arith.cmpi ult, %p1, %np : index + %pc1 = arith.minui %p1, %last : index + %mr1 = memref.load %part[%hi, %pc1, %c128] : memref + %m1 = arith.select %live1, %mr1, %neg : f32 + %p2 = arith.addi %l, %c64 : index + %live2 = arith.cmpi ult, %p2, %np : index + %pc2 = arith.minui %p2, %last : index + %mr2 = memref.load %part[%hi, %pc2, %c128] : memref + %m2 = arith.select %live2, %mr2, %neg : f32 + %p3 = arith.addi %l, %c96 : index + %live3 = arith.cmpi ult, %p3, %np : index + %pc3 = arith.minui %p3, %last : index + %mr3 = memref.load %part[%hi, %pc3, %c128] : memref + %m3 = arith.select %live3, %mr3, %neg : f32 + %m01 = arith.maxnumf %m0, %m1 : f32 + %m23 = arith.maxnumf %m2, %m3 : f32 + %mx = arith.maxnumf %m01, %m23 : f32 + %big = gpu.subgroup_reduce maxnumf %mx : (f32) -> f32 + %dm0 = arith.subf %m0, %big : f32 + %w0 = math.exp %dm0 : f32 + %s0 = memref.load %part[%hi, %pc0, %c129] : memref + %ws0 = arith.mulf %w0, %s0 : f32 + %wv0 = vector.broadcast %w0 : f32 to vector<4xf32> + %dm1 = arith.subf %m1, %big : f32 + %w1 = math.exp %dm1 : f32 + %s1 = memref.load %part[%hi, %pc1, %c129] : memref + %ws1 = arith.mulf %w1, %s1 : f32 + %wv1 = vector.broadcast %w1 : f32 to vector<4xf32> + %dm2 = arith.subf %m2, %big : f32 + %w2 = math.exp %dm2 : f32 + %s2 = memref.load %part[%hi, %pc2, %c129] : memref + %ws2 = arith.mulf %w2, %s2 : f32 + %wv2 = vector.broadcast %w2 : f32 to vector<4xf32> + %dm3 = arith.subf %m3, %big : f32 + %w3 = math.exp %dm3 : f32 + %s3 = memref.load %part[%hi, %pc3, %c129] : memref + %ws3 = arith.mulf %w3, %s3 : f32 + %wv3 = vector.broadcast %w3 : f32 to vector<4xf32> + %t01 = arith.addf %ws0, %ws1 : f32 + %t23 = arith.addf %ws2, %ws3 : f32 + %ts = arith.addf %t01, %t23 : f32 + %total = gpu.subgroup_reduce add %ts : (f32) -> f32 + %inv = arith.divf %one, %total : f32 + %lane0 = arith.cmpi eq, %l, %c0 : index + %sg4 = arith.muli %sg, %c4 : index + %vz4 = arith.constant dense<0.0> : vector<4xf32> + scf.for %n = %c0 to %c128 step %c16 { + %d = arith.addi %n, %sg4 : index + %x0 = vector.load %part[%hi, %pc0, %d] {alignment = 16} : memref, vector<4xf32> + %a0 = vector.fma %x0, %wv0, %vz4 : vector<4xf32> + %x1 = vector.load %part[%hi, %pc1, %d] {alignment = 16} : memref, vector<4xf32> + %a1 = vector.fma %x1, %wv1, %a0 : vector<4xf32> + %x2 = vector.load %part[%hi, %pc2, %d] {alignment = 16} : memref, vector<4xf32> + %a2 = vector.fma %x2, %wv2, %a1 : vector<4xf32> + %x3 = vector.load %part[%hi, %pc3, %d] {alignment = 16} : memref, vector<4xf32> + %a3 = vector.fma %x3, %wv3, %a2 : vector<4xf32> + %e0 = vector.extract %a3[0] : f32 from vector<4xf32> + %r0 = gpu.subgroup_reduce add %e0 : (f32) -> f32 + %o0 = arith.mulf %r0, %inv : f32 + %e1 = vector.extract %a3[1] : f32 from vector<4xf32> + %r1 = gpu.subgroup_reduce add %e1 : (f32) -> f32 + %o1 = arith.mulf %r1, %inv : f32 + %e2 = vector.extract %a3[2] : f32 from vector<4xf32> + %r2 = gpu.subgroup_reduce add %e2 : (f32) -> f32 + %o2 = arith.mulf %r2, %inv : f32 + %e3 = vector.extract %a3[3] : f32 from vector<4xf32> + %r3 = gpu.subgroup_reduce add %e3 : (f32) -> f32 + %o3 = arith.mulf %r3, %inv : f32 + scf.if %lane0 { + %d0 = arith.addi %d, %c0 : index + memref.store %o0, %out[%hi, %d0] : memref + %d1 = arith.addi %d, %c1 : index + memref.store %o1, %out[%hi, %d1] : memref + %d2 = arith.addi %d, %c2 : index + memref.store %o2, %out[%hi, %d2] : memref + %d3 = arith.addi %d, %c3 : index + memref.store %o3, %out[%hi, %d3] : memref + } + } + macro.yield %h : i32 + }; + } + } + return; +} + +/// The scratch space of `split_attention` for positions below `max_seq`, on the CPU. Transfer it to the +/// memory of the other tensors. Each block of positions writes the weighted sum of V for each of its +/// heads, then the largest score and the sum of the weights. +fn split_attention_scratch(max_seq : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> Tensor { + // 20 blocks of 32 positions below position 640, and blocks of 64 positions from there on. + let mut splits = (max_seq + 63) / 64; + if splits < 20 { + splits = 20; + } + return Tensor([kv_heads * ((q_heads / kv_heads + 7) / 8), splits, 8, head_dim + 2]); +} + +/// The parts of `split_attention` for blocks of 32 positions: 4 SIMD groups of 2 heads of Q. +fn split_attention_parts_32(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + let group = q_heads / kv_heads; + let tiles = (group + 7) / 8; + let scale = 1.0 / (head_dim as f32).sqrt(); + spawn on(Topology::Device) { + for gt in 0..kv_heads * tiles across blocks { + for c in 0..(pos + 32) / 32 across blocks { + let mut w = unsafe { Tensor::uninit() }; + let mut top = unsafe { + Tensor::uninit() + }; + let mut sums = unsafe { + Tensor::uninit() + }; + let g = gt / tiles; + let base = g * group + (gt - g * tiles) * 8; + let left = group - (gt - g * tiles) * 8; + for s in 0..4 across subgroups { + let first = base + s * 2; + let mut heads = left - s * 2; + if heads > 2 { + heads = 2; + } + // A head past the last one of the group reads the last one again, and its sums go nowhere. + let mut h0 = first + 0; + if 0 >= heads { + h0 = first + heads - 1; + } + let mut h1 = first + 1; + if 1 >= heads { + h1 = first + heads - 1; + } + for l in 0..32 across lanes(32) { + // The scores of the position of the lane, for each head. A position past `pos` reads row + // `pos`, and its score is -3e38. + let mut t0 = c * 32 + 0 + l; + if t0 > pos { + t0 = pos; + } + let mut dot0_0 : f32 = 0.0; + let mut dot0_1 : f32 = 0.0; + for d in 0..head_dim { + let k0 = k_cache[t0][g][d] as f32; + let q0 = q[h0][d]; + dot0_0 = dot0_0 + q0 * k0; + let q1 = q[h1][d]; + dot0_1 = dot0_1 + q1 * k0; + } + let mut s0_0 : f32 = -3.0e38; + if c * 32 + 0 + l <= pos { + s0_0 = dot0_0 * scale; + } + w[s][0][0 + l] = s0_0; + top[s][0][l] = s0_0; + let mut s0_1 : f32 = -3.0e38; + if c * 32 + 0 + l <= pos { + s0_1 = dot0_1 * scale; + } + w[s][1][0 + l] = s0_1; + top[s][1][l] = s0_1; + } + let big0 = lanes::max(&top[s][0], 32); + let big1 = lanes::max(&top[s][1], 32); + // The weight of each position, as exp(score - the largest score of the block). + for l in 0..32 across lanes(32) { + let e0_0 = (w[s][0][0 + l] - big0).fast_exp(); + w[s][0][0 + l] = e0_0; + sums[s][0][l] = e0_0; + let e0_1 = (w[s][1][0 + l] - big1).fast_exp(); + w[s][1][0 + l] = e0_1; + sums[s][1][l] = e0_1; + } + let total0 = lanes::sum(&sums[s][0], 32); + let total1 = lanes::sum(&sums[s][1], 32); + // The weighted sum of the rows of V. Lane l takes values l, l + 32, l + 64 and l + 96. + for l in 0..32 across lanes(32) { + let mut acc0_0 : f32 = 0.0; + let mut acc0_1 : f32 = 0.0; + let mut acc0_2 : f32 = 0.0; + let mut acc0_3 : f32 = 0.0; + let mut acc1_0 : f32 = 0.0; + let mut acc1_1 : f32 = 0.0; + let mut acc1_2 : f32 = 0.0; + let mut acc1_3 : f32 = 0.0; + // With head_dim below 128, values past it read others again, and their sums go nowhere. + let d0 = (0 + l) % head_dim; + let d1 = (32 + l) % head_dim; + let d2 = (64 + l) % head_dim; + let d3 = (96 + l) % head_dim; + let mut last = pos - c * 32; + if last > 31 { + last = 31; + } + for t in 0..last + 1 { + let row = c * 32 + t; + let v0 = v_cache[row][g][d0] as f32; + let v1 = v_cache[row][g][d1] as f32; + let v2 = v_cache[row][g][d2] as f32; + let v3 = v_cache[row][g][d3] as f32; + let w0 = w[s][0][t]; + acc0_0 = acc0_0 + w0 * v0; + acc0_1 = acc0_1 + w0 * v1; + acc0_2 = acc0_2 + w0 * v2; + acc0_3 = acc0_3 + w0 * v3; + let w1 = w[s][1][t]; + acc1_0 = acc1_0 + w1 * v0; + acc1_1 = acc1_1 + w1 * v1; + acc1_2 = acc1_2 + w1 * v2; + acc1_3 = acc1_3 + w1 * v3; + } + if 0 < heads { + if 0 < head_dim { + part[gt][c][s * 2 + 0][0 + l] = acc0_0; + } + if 32 < head_dim { + part[gt][c][s * 2 + 0][32 + l] = acc0_1; + } + if 64 < head_dim { + part[gt][c][s * 2 + 0][64 + l] = acc0_2; + } + if 96 < head_dim { + part[gt][c][s * 2 + 0][96 + l] = acc0_3; + } + } + if 1 < heads { + if 0 < head_dim { + part[gt][c][s * 2 + 1][0 + l] = acc1_0; + } + if 32 < head_dim { + part[gt][c][s * 2 + 1][32 + l] = acc1_1; + } + if 64 < head_dim { + part[gt][c][s * 2 + 1][64 + l] = acc1_2; + } + if 96 < head_dim { + part[gt][c][s * 2 + 1][96 + l] = acc1_3; + } + } + } + if 0 < heads { + part[gt][c][s * 2 + 0][head_dim] = big0; + part[gt][c][s * 2 + 0][head_dim + 1] = total0; + } + if 1 < heads { + part[gt][c][s * 2 + 1][head_dim] = big1; + part[gt][c][s * 2 + 1][head_dim + 1] = total1; + } + } + } + } + } + return; +} + +/// The parts of `split_attention` for blocks of 64 positions: 2 SIMD groups of 4 heads of Q. +fn split_attention_parts_64(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + let group = q_heads / kv_heads; + let tiles = (group + 7) / 8; + let scale = 1.0 / (head_dim as f32).sqrt(); + spawn on(Topology::Device) { + for gt in 0..kv_heads * tiles across blocks { + for c in 0..(pos + 64) / 64 across blocks { + let mut w = unsafe { Tensor::uninit() }; + let mut top = unsafe { + Tensor::uninit() + }; + let mut sums = unsafe { + Tensor::uninit() + }; + let g = gt / tiles; + let base = g * group + (gt - g * tiles) * 8; + let left = group - (gt - g * tiles) * 8; + for s in 0..2 across subgroups { + let first = base + s * 4; + let mut heads = left - s * 4; + if heads > 4 { + heads = 4; + } + // A head past the last one of the group reads the last one again, and its sums go nowhere. + let mut h0 = first + 0; + if 0 >= heads { + h0 = first + heads - 1; + } + let mut h1 = first + 1; + if 1 >= heads { + h1 = first + heads - 1; + } + let mut h2 = first + 2; + if 2 >= heads { + h2 = first + heads - 1; + } + let mut h3 = first + 3; + if 3 >= heads { + h3 = first + heads - 1; + } + for l in 0..32 across lanes(32) { + // The scores of each of the 2 positions of the lane, for each head. A position past `pos` reads row + // `pos`, and its score is -3e38. + let mut t0 = c * 64 + 0 + l; + if t0 > pos { + t0 = pos; + } + let mut dot0_0 : f32 = 0.0; + let mut dot0_1 : f32 = 0.0; + let mut dot0_2 : f32 = 0.0; + let mut dot0_3 : f32 = 0.0; + let mut t1 = c * 64 + 32 + l; + if t1 > pos { + t1 = pos; + } + let mut dot1_0 : f32 = 0.0; + let mut dot1_1 : f32 = 0.0; + let mut dot1_2 : f32 = 0.0; + let mut dot1_3 : f32 = 0.0; + for d in 0..head_dim { + let k0 = k_cache[t0][g][d] as f32; + let k1 = k_cache[t1][g][d] as f32; + let q0 = q[h0][d]; + dot0_0 = dot0_0 + q0 * k0; + dot1_0 = dot1_0 + q0 * k1; + let q1 = q[h1][d]; + dot0_1 = dot0_1 + q1 * k0; + dot1_1 = dot1_1 + q1 * k1; + let q2 = q[h2][d]; + dot0_2 = dot0_2 + q2 * k0; + dot1_2 = dot1_2 + q2 * k1; + let q3 = q[h3][d]; + dot0_3 = dot0_3 + q3 * k0; + dot1_3 = dot1_3 + q3 * k1; + } + let mut s0_0 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_0 = dot0_0 * scale; + } + w[s][0][0 + l] = s0_0; + let mut s1_0 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_0 = dot1_0 * scale; + } + w[s][0][32 + l] = s1_0; + top[s][0][l] = s0_0.max(s1_0); + let mut s0_1 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_1 = dot0_1 * scale; + } + w[s][1][0 + l] = s0_1; + let mut s1_1 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_1 = dot1_1 * scale; + } + w[s][1][32 + l] = s1_1; + top[s][1][l] = s0_1.max(s1_1); + let mut s0_2 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_2 = dot0_2 * scale; + } + w[s][2][0 + l] = s0_2; + let mut s1_2 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_2 = dot1_2 * scale; + } + w[s][2][32 + l] = s1_2; + top[s][2][l] = s0_2.max(s1_2); + let mut s0_3 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_3 = dot0_3 * scale; + } + w[s][3][0 + l] = s0_3; + let mut s1_3 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_3 = dot1_3 * scale; + } + w[s][3][32 + l] = s1_3; + top[s][3][l] = s0_3.max(s1_3); + } + let big0 = lanes::max(&top[s][0], 32); + let big1 = lanes::max(&top[s][1], 32); + let big2 = lanes::max(&top[s][2], 32); + let big3 = lanes::max(&top[s][3], 32); + // The weight of each position, as exp(score - the largest score of the block). + for l in 0..32 across lanes(32) { + let e0_0 = (w[s][0][0 + l] - big0).fast_exp(); + w[s][0][0 + l] = e0_0; + let e1_0 = (w[s][0][32 + l] - big0).fast_exp(); + w[s][0][32 + l] = e1_0; + sums[s][0][l] = e0_0 + e1_0; + let e0_1 = (w[s][1][0 + l] - big1).fast_exp(); + w[s][1][0 + l] = e0_1; + let e1_1 = (w[s][1][32 + l] - big1).fast_exp(); + w[s][1][32 + l] = e1_1; + sums[s][1][l] = e0_1 + e1_1; + let e0_2 = (w[s][2][0 + l] - big2).fast_exp(); + w[s][2][0 + l] = e0_2; + let e1_2 = (w[s][2][32 + l] - big2).fast_exp(); + w[s][2][32 + l] = e1_2; + sums[s][2][l] = e0_2 + e1_2; + let e0_3 = (w[s][3][0 + l] - big3).fast_exp(); + w[s][3][0 + l] = e0_3; + let e1_3 = (w[s][3][32 + l] - big3).fast_exp(); + w[s][3][32 + l] = e1_3; + sums[s][3][l] = e0_3 + e1_3; + } + let total0 = lanes::sum(&sums[s][0], 32); + let total1 = lanes::sum(&sums[s][1], 32); + let total2 = lanes::sum(&sums[s][2], 32); + let total3 = lanes::sum(&sums[s][3], 32); + // The weighted sum of the rows of V. Lane l takes values l, l + 32, l + 64 and l + 96. + for l in 0..32 across lanes(32) { + let mut acc0_0 : f32 = 0.0; + let mut acc0_1 : f32 = 0.0; + let mut acc0_2 : f32 = 0.0; + let mut acc0_3 : f32 = 0.0; + let mut acc1_0 : f32 = 0.0; + let mut acc1_1 : f32 = 0.0; + let mut acc1_2 : f32 = 0.0; + let mut acc1_3 : f32 = 0.0; + let mut acc2_0 : f32 = 0.0; + let mut acc2_1 : f32 = 0.0; + let mut acc2_2 : f32 = 0.0; + let mut acc2_3 : f32 = 0.0; + let mut acc3_0 : f32 = 0.0; + let mut acc3_1 : f32 = 0.0; + let mut acc3_2 : f32 = 0.0; + let mut acc3_3 : f32 = 0.0; + // With head_dim below 128, values past it read others again, and their sums go nowhere. + let d0 = (0 + l) % head_dim; + let d1 = (32 + l) % head_dim; + let d2 = (64 + l) % head_dim; + let d3 = (96 + l) % head_dim; + let mut last = pos - c * 64; + if last > 63 { + last = 63; + } + for t in 0..last + 1 { + let row = c * 64 + t; + let v0 = v_cache[row][g][d0] as f32; + let v1 = v_cache[row][g][d1] as f32; + let v2 = v_cache[row][g][d2] as f32; + let v3 = v_cache[row][g][d3] as f32; + let w0 = w[s][0][t]; + acc0_0 = acc0_0 + w0 * v0; + acc0_1 = acc0_1 + w0 * v1; + acc0_2 = acc0_2 + w0 * v2; + acc0_3 = acc0_3 + w0 * v3; + let w1 = w[s][1][t]; + acc1_0 = acc1_0 + w1 * v0; + acc1_1 = acc1_1 + w1 * v1; + acc1_2 = acc1_2 + w1 * v2; + acc1_3 = acc1_3 + w1 * v3; + let w2 = w[s][2][t]; + acc2_0 = acc2_0 + w2 * v0; + acc2_1 = acc2_1 + w2 * v1; + acc2_2 = acc2_2 + w2 * v2; + acc2_3 = acc2_3 + w2 * v3; + let w3 = w[s][3][t]; + acc3_0 = acc3_0 + w3 * v0; + acc3_1 = acc3_1 + w3 * v1; + acc3_2 = acc3_2 + w3 * v2; + acc3_3 = acc3_3 + w3 * v3 \ No newline at end of file diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/vx/ctx2048.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/vx/ctx2048.txt new file mode 100644 index 0000000..dd56539 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/vx/ctx2048.txt @@ -0,0 +1,138 @@ +//===- model.vx - Qwen app --------------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// One token of a Qwen2 or Qwen3 MoE decoder on the GPU, with the kernels of `std::nn`. `State` +// holds every tensor that a token writes, and the KV cache. It is made once, before the first +// token, so the token loop allocates nothing. +import core::convert; +import core::num; +import std::nn; +import std::vec; +import qwen::attention; +import qwen::products; +import qwen::q6; +import qwen::weights; + +/// The keys and the values of every position so far, for one layer: [max_seq, kv_heads, head_dim]. +/// They are f16, half the memory of f32. The kernels compute in f32, and round only what they +/// store here. +struct Cache { + k : Tensor, + v : Tensor, +} + +/// The tensors of a mixture-of-experts layer: the router's score of each expert, the chosen +/// experts and their weights, and the SwiGLU output of each chosen expert, [experts_per_token, +/// moe_intermediate_size]. +struct Experts { + router_logits : Tensor, + ids : Tensor, + weights : Tensor, + mlp : Tensor, +} + +/// The tensors that a token writes, in GPU memory, and one `Cache` for each layer. `cos` and `sin` +/// are [max_seq, head_dim / 2]. +struct State { + max_seq : i32, + x : Tensor, + xn : Tensor, + q : Tensor, + k : Tensor, + v : Tensor, + q_turned : Tensor, + attended : Tensor, + attention_parts : Tensor, + vec_parts : Tensor, + mlp : Tensor, + experts : Experts, + logits : Tensor, + cos : Tensor, + sin : Tensor, + caches : Vec, +} + +/// The state for up to `max_seq` positions. The angles of RoPE are computed in f64, as in +/// `reference.py`, and rounded to f32 once. +fn new_state(c : &Config, max_seq : i32) -> State { + assert(max_seq > 0 && max_seq <= c.max_positions, "max_seq must be between 1 and the max_positions of the model"); + let half = c.head_dim / 2; + let mut hcos = Tensor([max_seq, half]); + let mut hsin = Tensor([max_seq, half]); + for p in 0..max_seq { + for i in 0..half { + let angle = f64::from(p) / f64::powf(c.rope_theta, f64::from(2 * i) / f64::from(c.head_dim)); + hcos[p][i] = f64::cos(angle) as f32; + hsin[p][i] = f64::sin(angle) as f32; + } + } + // A dense model uses none of the tensors of the experts, so one value each is enough. + let experts = i32::max(c.num_experts, 1); + let chosen = i32::max(c.experts_per_token, 1); + let moe_inter = i32::max(c.moe_intermediate_size, 1); + // The flash attention of a prompt reads the cache in blocks of 64 positions. + let rows = (max_seq + 63) / 64 * 64; + let mut caches = Vec::new(); + for l in 0..c.num_layers { + caches.push(Cache { + k: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + }); + } + return State { + max_seq: max_seq, + x: transfer(Tensor([c.hidden_size]), Memory::HBM), + xn: transfer(Tensor([c.hidden_size]), Memory::HBM), + q: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + k: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + q_turned: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attended: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attention_parts: transfer(split_attention_scratch(max_seq, c.num_q_heads, c.num_kv_heads, c.head_dim), Memory::HBM), + vec_parts: transfer(vec_attention_scratch(c.num_q_heads), Memory::HBM), + mlp: transfer(Tensor([c.intermediate_size]), Memory::HBM), + experts: Experts { + router_logits: transfer(Tensor([experts]), Memory::HBM), + ids: transfer(Tensor([chosen]), Memory::HBM), + weights: transfer(Tensor([chosen]), Memory::HBM), + mlp: transfer(Tensor([chosen, moe_inter]), Memory::HBM), + }, + logits: transfer(Tensor([c.vocab_size]), Memory::HBM), + cos: transfer(hcos, Memory::HBM), + sin: transfer(hsin, Memory::HBM), + caches: caches, + }; +} + +/// y = m x, with the kernel for the dtype of `m`, which has `rows` x `cols` weights. +fn matvec(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U6 { + matvec_q6(y, &m.codes, &m.high, &m.group_scales, x, rows, cols); + } else if m.dtype == U4 { + nn_matvec_q4(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x. +fn matvec_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_matvec_q4_add(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_add(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec_add(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x, for x of [heads, head_dim]. +fn matvec_heads_add(y : \ No newline at end of file diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/vx/ctx32768.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/vx/ctx32768.txt new file mode 100644 index 0000000..68a31d9 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/vx/ctx32768.txt @@ -0,0 +1,1975 @@ +//===- model.vx - Qwen app --------------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// One token of a Qwen2 or Qwen3 MoE decoder on the GPU, with the kernels of `std::nn`. `State` +// holds every tensor that a token writes, and the KV cache. It is made once, before the first +// token, so the token loop allocates nothing. +import core::convert; +import core::num; +import std::nn; +import std::vec; +import qwen::attention; +import qwen::products; +import qwen::q6; +import qwen::weights; + +/// The keys and the values of every position so far, for one layer: [max_seq, kv_heads, head_dim]. +/// They are f16, half the memory of f32. The kernels compute in f32, and round only what they +/// store here. +struct Cache { + k : Tensor, + v : Tensor, +} + +/// The tensors of a mixture-of-experts layer: the router's score of each expert, the chosen +/// experts and their weights, and the SwiGLU output of each chosen expert, [experts_per_token, +/// moe_intermediate_size]. +struct Experts { + router_logits : Tensor, + ids : Tensor, + weights : Tensor, + mlp : Tensor, +} + +/// The tensors that a token writes, in GPU memory, and one `Cache` for each layer. `cos` and `sin` +/// are [max_seq, head_dim / 2]. +struct State { + max_seq : i32, + x : Tensor, + xn : Tensor, + q : Tensor, + k : Tensor, + v : Tensor, + q_turned : Tensor, + attended : Tensor, + attention_parts : Tensor, + vec_parts : Tensor, + mlp : Tensor, + experts : Experts, + logits : Tensor, + cos : Tensor, + sin : Tensor, + caches : Vec, +} + +/// The state for up to `max_seq` positions. The angles of RoPE are computed in f64, as in +/// `reference.py`, and rounded to f32 once. +fn new_state(c : &Config, max_seq : i32) -> State { + assert(max_seq > 0 && max_seq <= c.max_positions, "max_seq must be between 1 and the max_positions of the model"); + let half = c.head_dim / 2; + let mut hcos = Tensor([max_seq, half]); + let mut hsin = Tensor([max_seq, half]); + for p in 0..max_seq { + for i in 0..half { + let angle = f64::from(p) / f64::powf(c.rope_theta, f64::from(2 * i) / f64::from(c.head_dim)); + hcos[p][i] = f64::cos(angle) as f32; + hsin[p][i] = f64::sin(angle) as f32; + } + } + // A dense model uses none of the tensors of the experts, so one value each is enough. + let experts = i32::max(c.num_experts, 1); + let chosen = i32::max(c.experts_per_token, 1); + let moe_inter = i32::max(c.moe_intermediate_size, 1); + // The flash attention of a prompt reads the cache in blocks of 64 positions. + let rows = (max_seq + 63) / 64 * 64; + let mut caches = Vec::new(); + for l in 0..c.num_layers { + caches.push(Cache { + k: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + }); + } + return State { + max_seq: max_seq, + x: transfer(Tensor([c.hidden_size]), Memory::HBM), + xn: transfer(Tensor([c.hidden_size]), Memory::HBM), + q: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + k: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + q_turned: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attended: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attention_parts: transfer(split_attention_scratch(max_seq, c.num_q_heads, c.num_kv_heads, c.head_dim), Memory::HBM), + vec_parts: transfer(vec_attention_scratch(c.num_q_heads), Memory::HBM), + mlp: transfer(Tensor([c.intermediate_size]), Memory::HBM), + experts: Experts { + router_logits: transfer(Tensor([experts]), Memory::HBM), + ids: transfer(Tensor([chosen]), Memory::HBM), + weights: transfer(Tensor([chosen]), Memory::HBM), + mlp: transfer(Tensor([chosen, moe_inter]), Memory::HBM), + }, + logits: transfer(Tensor([c.vocab_size]), Memory::HBM), + cos: transfer(hcos, Memory::HBM), + sin: transfer(hsin, Memory::HBM), + caches: caches, + }; +} + +/// y = m x, with the kernel for the dtype of `m`, which has `rows` x `cols` weights. +fn matvec(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U6 { + matvec_q6(y, &m.codes, &m.high, &m.group_scales, x, rows, cols); + } else if m.dtype == U4 { + nn_matvec_q4(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x. +fn matvec_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_matvec_q4_add(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_add(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec_add(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x, for x of [heads, head_dim]. +fn matvec_heads_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, heads : i32, head_dim : i32) -> void { + if m.dtype == U4 { + matvec_q4_heads_add_blocks(y, &m.codes, &m.group_scales, x, rows, heads, head_dim); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_heads_add(y, &m.codes, &m.scales, x, rows, heads, head_dim); + } else { + nn_matvec_heads_add(y, &m.bf16, x, rows, heads, head_dim); + } + return; +} + +/// The Q, K and V of x: m x + b, split by heads. +fn qkv(q : &mut Tensor, k : &mut Tensor, v : &mut Tensor, m : &WeightMatrix, b : &Tensor, x : &Tensor, c : &Config) -> void { + if m.dtype == U4 { + qkv_q4_blocks(q, k, v, &m.codes, &m.group_scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } else if m.dtype == F8E4M3 { + nn_qkv_fp8(q, k, v, &m.codes, &m.scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } else { + nn_qkv(q, k, v, &m.bf16, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } + return; +} + +/// The SwiGLU of a dense MLP, for the gate rows and then the up rows of `m`. +fn swiglu(out : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_swiglu_q4(out, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_swiglu_fp8(out, &m.codes, &m.scales, x, rows, cols); + } else { + nn_swiglu(out, &m.bf16, x, rows, cols); + } + return; +} + +/// The mixture of experts of a layer: the router chooses experts_per_token experts and their +/// weights, and x gets the sum of their outputs for xn, each times its weight. +fn add_experts(e : &mut Experts, x : &mut Tensor, xn : &Tensor, layer : &Layer, c : &Config) -> void { + let k = c.experts_per_token; + let inter = c.moe_intermediate_size; + nn_matvec(&mut e.router_logits, &layer.router, xn, c.num_experts, c.hidden_size); + nn_top_k(&mut e.ids, &mut e.weights, &e.router_logits, c.num_experts, k); + let gate_up = &layer.gate_up; + let down = &layer.down; + if gate_up.dtype == U4 { + moe_swiglu_q4_blocks(&mut e.mlp, &gate_up.codes, &gate_up.group_scales, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + moe_down_q4_add_blocks(x, &down.codes, &down.group_scales, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + } else { + assert(gate_up.dtype == BF16, "the experts of a mixture-of-experts model must be bf16 or Q4_0"); + nn_moe_swiglu(&mut e.mlp, &gate_up.bf16, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + nn_moe_down_add(x, &down.bf16, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + } + return; +} + +/// Runs the token in `token` at position `pos` through every layer. The hidden state of the +/// token is then in `s.x`, and its keys and values are in the caches. +fn run_layers(w : &Weights, s : &mut State, token : &Tensor, pos : i32) -> void { + let c = &w.config; + let eps = c.rms_norm_eps as f32; + assert(pos >= 0 && pos < s.max_seq, "the position is past the end of the KV cache"); + nn_embed(&mut s.x, &w.embed, token, c.hidden_size); + let mut l = 0; + for cache in s.caches.iter_mut() { + let layer = &w.layers[l]; + nn_rms_norm(&mut s.xn, &s.x, &layer.attn_norm, c.hidden_size, eps); + qkv(&mut s.q, &mut s.k, &mut s.v, &layer.qkv, &layer.qkv_bias, &s.xn, c); + if c.qk_norm { + norm_rope_and_store(&mut s.q_turned, &mut cache.k, &mut cache.v, &s.q, &s.k, &s.v, &layer.q_norm, &layer.k_norm, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.head_dim, eps); + } else { + rope_and_store(&mut s.q_turned, &mut cache.k, &mut cache.v, &s.q, &s.k, &s.v, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } + if c.head_dim == 128 { + vec_attention(&mut s.attended, &mut s.vec_parts, &s.q_turned, &cache.k, &cache.v, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } else { + split_attention(&mut s.attended, &mut s.attention_parts, &s.q_turned, &cache.k, &cache.v, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } + matvec_heads_add(&mut s.x, &layer.attn_out, &s.attended, c.hidden_size, c.num_q_heads, c.head_dim); + nn_rms_norm(&mut s.xn, &s.x, &layer.mlp_norm, c.hidden_size, eps); + if c.num_experts > 0 { + add_experts(&mut s.experts, &mut s.x, &s.xn, layer, c); + } else { + swiglu(&mut s.mlp, &layer.gate_up, &s.xn, c.intermediate_size, c.hidden_size); + matvec_add(&mut s.x, &layer.down, &s.mlp, c.hidden_size, c.intermediate_size); + } + l = l + 1; + } + return; +} + +/// The logits of the token whose hidden state is in `s.x`, and in `next` the index of the largest +/// one. Both stay in GPU memory. +fn predict(w : &Weights, s : &mut State, next : &mut Tensor) -> void { + let c = &w.config; + nn_rms_norm(&mut s.xn, &s.x, &w.final_norm, c.hidden_size, c.rms_norm_eps as f32); + if c.tied_embeddings { + nn_matvec(&mut s.logits, &w.embed, &s.xn, c.vocab_size, c.hidden_size); + } else { + matvec(&mut s.logits, &w.lm_head, &s.xn, c.vocab_size, c.hidden_size); + } + nn_argmax(next, &s.logits, c.vocab_size); + return; +} +//===- attention.vx - Qwen app ----------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// The attention of one generated token, with the positions split among blocks. This is a copy of +// `nn_attention` and its kernels from `std::nn` on Vx main (vx-lang/Vx#3216), with `split_` in place +// of `nn_` in their names. Vx v0.0.4 has the older `nn_attention`, which has one block for each head +// of Q, so its time grows with the number of positions. Remove this file, and call `nn_attention` +// of `std::nn`, when a Vx release has the new one (#4). +// +// `vec_attention`, for head_dim 128, has the design of llama.cpp's flash attention for one token +// (kernel_flash_attn_ext_vec and kernel_flash_attn_ext_vec_reduce), MIT License, Copyright (c) 2023-2026 +// The ggml authors. scripts/mlir_kernels/decode_attention.py writes its kernels: change that script, not +// the MLIR. +import core::num; +import std::nn; + +/// Attention of the token at position `pos` over rows 0 to `pos` of the KV cache, with a softmax +/// of the scores q . k / sqrt(head_dim). `part` is scratch space from `split_attention_scratch`. +/// +/// The blocks of the first kernel split the positions, 32 to a block below position 640 and 64 from +/// there on. A block serves the 8 heads of Q that share a head of K and V, so it reads each row of +/// the cache once for all 8. A second kernel merges the parts of the blocks for each head. +fn split_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_heads % kv_heads == 0, "split_attention: q_heads must be a multiple of kv_heads"); + assert(head_dim % 32 == 0 && head_dim <= 128, "split_attention: head_dim must be a multiple of 32, and at most 128"); + let mut n_pos = 32; + if pos >= 640 { + n_pos = 64; + } + assert(part.extent(0) >= kv_heads * ((q_heads / kv_heads + 7) / 8) && part.extent(1) >= (pos + n_pos) / n_pos && part.extent(2) >= 8 && part.extent(3) >= head_dim + 2, "split_attention: `part` is too small for this position. Make it with split_attention_scratch"); + if n_pos == 32 { + split_attention_parts_32(part, q, k_cache, v_cache, pos, q_heads, kv_heads, head_dim); + } else { + split_attention_parts_64(part, q, k_cache, v_cache, pos, q_heads, kv_heads, head_dim); + } + split_attention_merge(out, part, pos, n_pos, q_heads, kv_heads, head_dim); + return; +} + +/// Attention of the token at position `pos`, as `split_attention`, for head_dim 128, with the kernels of +/// llama.cpp's flash attention for one token. `vec_attention_parts` splits the blocks of 32 positions among +/// `nwg` SIMD groups for each head of Q: 32 of them, or 64 when each of 32 would have more than 2 blocks. +/// (llama.cpp goes on to 4 SIMD groups of 32 a block, but 128 parts are no faster here: their merge costs what +/// they save.) `vec_attention_merge` then merges the parts. `part` is scratch space from +/// `vec_attention_scratch`. +fn vec_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_heads % kv_heads == 0 && head_dim == 128, "vec_attention: q_heads must be a multiple of kv_heads, and head_dim 128"); + assert(part.extent(0) >= q_heads && part.extent(1) >= 128 && part.extent(2) == 132, "vec_attention: `part` is too small. Make it with vec_attention_scratch"); + let mut nwg = 32; + if 2 * nwg * 32 < pos + 1 { + nwg = nwg * 2; + } + vec_attention_parts(part, q, k_cache, v_cache, pos, q_heads, q_heads / kv_heads, nwg, 1.0 / (head_dim as f32).sqrt()); + vec_attention_merge(out, part, nwg, q_heads); + return; +} + +/// The scratch space of `vec_attention`, on the CPU: up to 128 parts for each head of Q, each the sum of V +/// (128 values), the largest score, and the sum of the weights. A part has 132 values, so that each starts +/// at a multiple of 16 bytes. +fn vec_attention_scratch(q_heads : i32) -> Tensor { + return Tensor([q_heads, 128, 132]); +} + +/// The parts of `vec_attention`, as llama.cpp's kernel_flash_attn_ext_vec. Block (h, w) is a SIMD group for +/// query head h. It does the blocks of 32 positions w, w + nwg, w + 2 nwg, ... up to `pos`, and writes +/// part[h][w]. Lane l owns values 4 l to 4 l + 3 of the head, so that the 32 lanes read a row of K or V in +/// one 256-byte load. For each row, the lanes add up their parts of q . k; then each lane keeps the score +/// of one row, and the lanes take the weights of the rows from each other for the sum of V. A part is the +/// sum of V, not divided, then the largest score and the sum of the weights. +fn vec_attention_parts(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, group : i32, nwg : i32, scale : f32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for w in 0..nwg across blocks { + let g = h / group; + let _d = mlir!( threads : 32, inputs : (%part = part : memref, %q = q : memref, %k3 = k_cache : memref, %v3 = v_cache : memref, %pos = pos : i32, %nwg = nwg : i32, %scale = scale : f32, %h = h : i32, %w = w : i32, %g = g : i32), returns : i32, dialects : ["arith", "memref", "scf", "gpu", "vector", "math"], ensures : [reads_only(q), reads_only(k_cache), reads_only(v_cache), writes_only(part[h][w])]) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %c4 = arith.constant 4 : index + %c32 = arith.constant 32 : index + %c128 = arith.constant 128 : index + %c129 = arith.constant 129 : index + %c32i = arith.constant 32 : i32 + %neg = arith.constant -3.0e38 : f32 + %zero = arith.constant 0.0 : f32 + %vz4 = arith.constant dense<0.0> : vector<4xf32> + %l = gpu.thread_id x + %l4 = arith.muli %l, %c4 : index + %hi = arith.index_cast %h : i32 to index + %wi = arith.index_cast %w : i32 to index + %gi = arith.index_cast %g : i32 to index + %posi = arith.index_cast %pos : i32 to index + %nwgi = arith.index_cast %nwg : i32 to index + %g128 = arith.muli %gi, %c128 : index + %kd = arith.addi %g128, %l4 : index + %P = memref.dim %k3, %c0 : memref + %KH = memref.dim %k3, %c1 : memref + %Wd = arith.muli %KH, %c128 : index + %k = memref.reinterpret_cast %k3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to memref> + %v = memref.reinterpret_cast %v3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to memref> + %qv = vector.load %q[%hi, %l4] {alignment = 16} : memref, vector<4xf32> + %scv = vector.broadcast %scale : f32 to vector<4xf32> + %qs = arith.mulf %qv, %scv : vector<4xf32> + %nkv = arith.addi %posi, %c32 : index + %chunks = arith.divui %nkv, %c32 : index + %st:3 = scf.for %ic = %wi to %chunks step %nwgi iter_args(%M = %neg, %S = %zero, %o = %vz4) -> (f32, f32, vector<4xf32>) { + %r0 = arith.muli %ic, %c32 : index + %my = scf.for %cc = %c0 to %c32 step %c1 iter_args(%m = %neg) -> (f32) { + %row = arith.addi %r0, %cc : index + %rowc = arith.minui %row, %posi : index + %kh = vector.load %k[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> + %kf = arith.extf %kh : vector<4xf16> to vector<4xf32> + %pr = arith.mulf %kf, %qs : vector<4xf32> + %pl = vector.reduction , %pr : vector<4xf32> into f32 + %sc = gpu.subgroup_reduce add %pl : (f32) -> f32 + %live = arith.cmpi ule, %row, %posi : index + %scm = arith.select %live, %sc, %neg : f32 + %mine = arith.cmpi eq, %cc, %l : index + %m2 = arith.select %mine, %scm, %m : f32 + scf.yield %m2 : f32 + } + %bm = gpu.subgroup_reduce maxnumf %my : (f32) -> f32 + %Mn = arith.maxnumf %M, %bm : f32 + %dm = arith.subf %M, %Mn : f32 + %ms = math.exp %dm : f32 + %dp = arith.subf %my, %Mn : f32 + %p = math.exp %dp : f32 + %bs = gpu.subgroup_reduce add %p : (f32) -> f32 + %Ss = arith.mulf %S, %ms : f32 + %Sn = arith.addf %Ss, %bs : f32 + %msv = vector.broadcast %ms : f32 to vector<4xf32> + %o1 = arith.mulf %o, %msv : vector<4xf32> + %o2 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%oa = %o1) -> (vector<4xf32>) { + %row = arith.addi %r0, %cc : index + %rowc = arith.minui %row, %posi : index + %vh = vector.load %v[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> + %vf = arith.extf %vh : vector<4xf16> to vector<4xf32> + %cci = arith.index_cast %cc : index to i32 + %pc, %pv = gpu.shuffle idx %p, %cci, %c32i : f32 + %pcv = vector.broadcast %pc : f32 to vector<4xf32> + %on = vector.fma %vf, %pcv, %oa : vector<4xf32> + scf.yield %on : vector<4xf32> + } + scf.yield %Mn, %Sn, %o2 : f32, f32, vector<4xf32> + } + vector.store %st#2, %part[%hi, %wi, %l4] : memref, vector<4xf32> + %lane0 = arith.cmpi eq, %l, %c0 : index + scf.if %lane0 { + memref.store %st#0, %part[%hi, %wi, %c128] : memref + memref.store %st#1, %part[%hi, %wi, %c129] : memref + } + macro.yield %h : i32 + }; + } + } + } + return; +} + +/// Merges the first `parts` parts of `vec_attention_parts` for each head of Q, as llama.cpp's +/// kernel_flash_attn_ext_vec_reduce. A block of 4 SIMD groups does one head: each lane weighs up to 4 parts, +/// and the SIMD groups add them up for 4 values of the head at a time. +fn vec_attention_merge(out : &mut Tensor, part : &Tensor, parts : i32, q_heads : i32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + let _d = mlir!( threads : 128, inputs : (%out = out : memref, %part = part : memref, %parts = parts : i32, %h = h : i32), returns : i32, dialects : ["arith", "memref", "scf", "gpu", "vector", "math"], ensures : [reads_only(part), writes_only(out[h])]) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %c2 = arith.constant 2 : index + %c3 = arith.constant 3 : index + %c4 = arith.constant 4 : index + %c16 = arith.constant 16 : index + %c32 = arith.constant 32 : index + %c64 = arith.constant 64 : index + %c96 = arith.constant 96 : index + %c128 = arith.constant 128 : index + %c129 = arith.constant 129 : index + %neg = arith.constant -3.0e38 : f32 + %zero = arith.constant 0.0 : f32 + %one = arith.constant 1.0 : f32 + %tid = gpu.thread_id x + %sg = arith.divui %tid, %c32 : index + %l = arith.remui %tid, %c32 : index + %hi = arith.index_cast %h : i32 to index + %np = arith.index_cast %parts : i32 to index + %last = arith.subi %np, %c1 : index + %p0 = arith.addi %l, %c0 : index + %live0 = arith.cmpi ult, %p0, %np : index + %pc0 = arith.minui %p0, %last : index + %mr0 = memref.load %part[%hi, %pc0, %c128] : memref + %m0 = arith.select %live0, %mr0, %neg : f32 + %p1 = arith.addi %l, %c32 : index + %live1 = arith.cmpi ult, %p1, %np : index + %pc1 = arith.minui %p1, %last : index + %mr1 = memref.load %part[%hi, %pc1, %c128] : memref + %m1 = arith.select %live1, %mr1, %neg : f32 + %p2 = arith.addi %l, %c64 : index + %live2 = arith.cmpi ult, %p2, %np : index + %pc2 = arith.minui %p2, %last : index + %mr2 = memref.load %part[%hi, %pc2, %c128] : memref + %m2 = arith.select %live2, %mr2, %neg : f32 + %p3 = arith.addi %l, %c96 : index + %live3 = arith.cmpi ult, %p3, %np : index + %pc3 = arith.minui %p3, %last : index + %mr3 = memref.load %part[%hi, %pc3, %c128] : memref + %m3 = arith.select %live3, %mr3, %neg : f32 + %m01 = arith.maxnumf %m0, %m1 : f32 + %m23 = arith.maxnumf %m2, %m3 : f32 + %mx = arith.maxnumf %m01, %m23 : f32 + %big = gpu.subgroup_reduce maxnumf %mx : (f32) -> f32 + %dm0 = arith.subf %m0, %big : f32 + %w0 = math.exp %dm0 : f32 + %s0 = memref.load %part[%hi, %pc0, %c129] : memref + %ws0 = arith.mulf %w0, %s0 : f32 + %wv0 = vector.broadcast %w0 : f32 to vector<4xf32> + %dm1 = arith.subf %m1, %big : f32 + %w1 = math.exp %dm1 : f32 + %s1 = memref.load %part[%hi, %pc1, %c129] : memref + %ws1 = arith.mulf %w1, %s1 : f32 + %wv1 = vector.broadcast %w1 : f32 to vector<4xf32> + %dm2 = arith.subf %m2, %big : f32 + %w2 = math.exp %dm2 : f32 + %s2 = memref.load %part[%hi, %pc2, %c129] : memref + %ws2 = arith.mulf %w2, %s2 : f32 + %wv2 = vector.broadcast %w2 : f32 to vector<4xf32> + %dm3 = arith.subf %m3, %big : f32 + %w3 = math.exp %dm3 : f32 + %s3 = memref.load %part[%hi, %pc3, %c129] : memref + %ws3 = arith.mulf %w3, %s3 : f32 + %wv3 = vector.broadcast %w3 : f32 to vector<4xf32> + %t01 = arith.addf %ws0, %ws1 : f32 + %t23 = arith.addf %ws2, %ws3 : f32 + %ts = arith.addf %t01, %t23 : f32 + %total = gpu.subgroup_reduce add %ts : (f32) -> f32 + %inv = arith.divf %one, %total : f32 + %lane0 = arith.cmpi eq, %l, %c0 : index + %sg4 = arith.muli %sg, %c4 : index + %vz4 = arith.constant dense<0.0> : vector<4xf32> + scf.for %n = %c0 to %c128 step %c16 { + %d = arith.addi %n, %sg4 : index + %x0 = vector.load %part[%hi, %pc0, %d] {alignment = 16} : memref, vector<4xf32> + %a0 = vector.fma %x0, %wv0, %vz4 : vector<4xf32> + %x1 = vector.load %part[%hi, %pc1, %d] {alignment = 16} : memref, vector<4xf32> + %a1 = vector.fma %x1, %wv1, %a0 : vector<4xf32> + %x2 = vector.load %part[%hi, %pc2, %d] {alignment = 16} : memref, vector<4xf32> + %a2 = vector.fma %x2, %wv2, %a1 : vector<4xf32> + %x3 = vector.load %part[%hi, %pc3, %d] {alignment = 16} : memref, vector<4xf32> + %a3 = vector.fma %x3, %wv3, %a2 : vector<4xf32> + %e0 = vector.extract %a3[0] : f32 from vector<4xf32> + %r0 = gpu.subgroup_reduce add %e0 : (f32) -> f32 + %o0 = arith.mulf %r0, %inv : f32 + %e1 = vector.extract %a3[1] : f32 from vector<4xf32> + %r1 = gpu.subgroup_reduce add %e1 : (f32) -> f32 + %o1 = arith.mulf %r1, %inv : f32 + %e2 = vector.extract %a3[2] : f32 from vector<4xf32> + %r2 = gpu.subgroup_reduce add %e2 : (f32) -> f32 + %o2 = arith.mulf %r2, %inv : f32 + %e3 = vector.extract %a3[3] : f32 from vector<4xf32> + %r3 = gpu.subgroup_reduce add %e3 : (f32) -> f32 + %o3 = arith.mulf %r3, %inv : f32 + scf.if %lane0 { + %d0 = arith.addi %d, %c0 : index + memref.store %o0, %out[%hi, %d0] : memref + %d1 = arith.addi %d, %c1 : index + memref.store %o1, %out[%hi, %d1] : memref + %d2 = arith.addi %d, %c2 : index + memref.store %o2, %out[%hi, %d2] : memref + %d3 = arith.addi %d, %c3 : index + memref.store %o3, %out[%hi, %d3] : memref + } + } + macro.yield %h : i32 + }; + } + } + return; +} + +/// The scratch space of `split_attention` for positions below `max_seq`, on the CPU. Transfer it to the +/// memory of the other tensors. Each block of positions writes the weighted sum of V for each of its +/// heads, then the largest score and the sum of the weights. +fn split_attention_scratch(max_seq : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> Tensor { + // 20 blocks of 32 positions below position 640, and blocks of 64 positions from there on. + let mut splits = (max_seq + 63) / 64; + if splits < 20 { + splits = 20; + } + return Tensor([kv_heads * ((q_heads / kv_heads + 7) / 8), splits, 8, head_dim + 2]); +} + +/// The parts of `split_attention` for blocks of 32 positions: 4 SIMD groups of 2 heads of Q. +fn split_attention_parts_32(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + let group = q_heads / kv_heads; + let tiles = (group + 7) / 8; + let scale = 1.0 / (head_dim as f32).sqrt(); + spawn on(Topology::Device) { + for gt in 0..kv_heads * tiles across blocks { + for c in 0..(pos + 32) / 32 across blocks { + let mut w = unsafe { Tensor::uninit() }; + let mut top = unsafe { + Tensor::uninit() + }; + let mut sums = unsafe { + Tensor::uninit() + }; + let g = gt / tiles; + let base = g * group + (gt - g * tiles) * 8; + let left = group - (gt - g * tiles) * 8; + for s in 0..4 across subgroups { + let first = base + s * 2; + let mut heads = left - s * 2; + if heads > 2 { + heads = 2; + } + // A head past the last one of the group reads the last one again, and its sums go nowhere. + let mut h0 = first + 0; + if 0 >= heads { + h0 = first + heads - 1; + } + let mut h1 = first + 1; + if 1 >= heads { + h1 = first + heads - 1; + } + for l in 0..32 across lanes(32) { + // The scores of the position of the lane, for each head. A position past `pos` reads row + // `pos`, and its score is -3e38. + let mut t0 = c * 32 + 0 + l; + if t0 > pos { + t0 = pos; + } + let mut dot0_0 : f32 = 0.0; + let mut dot0_1 : f32 = 0.0; + for d in 0..head_dim { + let k0 = k_cache[t0][g][d] as f32; + let q0 = q[h0][d]; + dot0_0 = dot0_0 + q0 * k0; + let q1 = q[h1][d]; + dot0_1 = dot0_1 + q1 * k0; + } + let mut s0_0 : f32 = -3.0e38; + if c * 32 + 0 + l <= pos { + s0_0 = dot0_0 * scale; + } + w[s][0][0 + l] = s0_0; + top[s][0][l] = s0_0; + let mut s0_1 : f32 = -3.0e38; + if c * 32 + 0 + l <= pos { + s0_1 = dot0_1 * scale; + } + w[s][1][0 + l] = s0_1; + top[s][1][l] = s0_1; + } + let big0 = lanes::max(&top[s][0], 32); + let big1 = lanes::max(&top[s][1], 32); + // The weight of each position, as exp(score - the largest score of the block). + for l in 0..32 across lanes(32) { + let e0_0 = (w[s][0][0 + l] - big0).fast_exp(); + w[s][0][0 + l] = e0_0; + sums[s][0][l] = e0_0; + let e0_1 = (w[s][1][0 + l] - big1).fast_exp(); + w[s][1][0 + l] = e0_1; + sums[s][1][l] = e0_1; + } + let total0 = lanes::sum(&sums[s][0], 32); + let total1 = lanes::sum(&sums[s][1], 32); + // The weighted sum of the rows of V. Lane l takes values l, l + 32, l + 64 and l + 96. + for l in 0..32 across lanes(32) { + let mut acc0_0 : f32 = 0.0; + let mut acc0_1 : f32 = 0.0; + let mut acc0_2 : f32 = 0.0; + let mut acc0_3 : f32 = 0.0; + let mut acc1_0 : f32 = 0.0; + let mut acc1_1 : f32 = 0.0; + let mut acc1_2 : f32 = 0.0; + let mut acc1_3 : f32 = 0.0; + // With head_dim below 128, values past it read others again, and their sums go nowhere. + let d0 = (0 + l) % head_dim; + let d1 = (32 + l) % head_dim; + let d2 = (64 + l) % head_dim; + let d3 = (96 + l) % head_dim; + let mut last = pos - c * 32; + if last > 31 { + last = 31; + } + for t in 0..last + 1 { + let row = c * 32 + t; + let v0 = v_cache[row][g][d0] as f32; + let v1 = v_cache[row][g][d1] as f32; + let v2 = v_cache[row][g][d2] as f32; + let v3 = v_cache[row][g][d3] as f32; + let w0 = w[s][0][t]; + acc0_0 = acc0_0 + w0 * v0; + acc0_1 = acc0_1 + w0 * v1; + acc0_2 = acc0_2 + w0 * v2; + acc0_3 = acc0_3 + w0 * v3; + let w1 = w[s][1][t]; + acc1_0 = acc1_0 + w1 * v0; + acc1_1 = acc1_1 + w1 * v1; + acc1_2 = acc1_2 + w1 * v2; + acc1_3 = acc1_3 + w1 * v3; + } + if 0 < heads { + if 0 < head_dim { + part[gt][c][s * 2 + 0][0 + l] = acc0_0; + } + if 32 < head_dim { + part[gt][c][s * 2 + 0][32 + l] = acc0_1; + } + if 64 < head_dim { + part[gt][c][s * 2 + 0][64 + l] = acc0_2; + } + if 96 < head_dim { + part[gt][c][s * 2 + 0][96 + l] = acc0_3; + } + } + if 1 < heads { + if 0 < head_dim { + part[gt][c][s * 2 + 1][0 + l] = acc1_0; + } + if 32 < head_dim { + part[gt][c][s * 2 + 1][32 + l] = acc1_1; + } + if 64 < head_dim { + part[gt][c][s * 2 + 1][64 + l] = acc1_2; + } + if 96 < head_dim { + part[gt][c][s * 2 + 1][96 + l] = acc1_3; + } + } + } + if 0 < heads { + part[gt][c][s * 2 + 0][head_dim] = big0; + part[gt][c][s * 2 + 0][head_dim + 1] = total0; + } + if 1 < heads { + part[gt][c][s * 2 + 1][head_dim] = big1; + part[gt][c][s * 2 + 1][head_dim + 1] = total1; + } + } + } + } + } + return; +} + +/// The parts of `split_attention` for blocks of 64 positions: 2 SIMD groups of 4 heads of Q. +fn split_attention_parts_64(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + let group = q_heads / kv_heads; + let tiles = (group + 7) / 8; + let scale = 1.0 / (head_dim as f32).sqrt(); + spawn on(Topology::Device) { + for gt in 0..kv_heads * tiles across blocks { + for c in 0..(pos + 64) / 64 across blocks { + let mut w = unsafe { Tensor::uninit() }; + let mut top = unsafe { + Tensor::uninit() + }; + let mut sums = unsafe { + Tensor::uninit() + }; + let g = gt / tiles; + let base = g * group + (gt - g * tiles) * 8; + let left = group - (gt - g * tiles) * 8; + for s in 0..2 across subgroups { + let first = base + s * 4; + let mut heads = left - s * 4; + if heads > 4 { + heads = 4; + } + // A head past the last one of the group reads the last one again, and its sums go nowhere. + let mut h0 = first + 0; + if 0 >= heads { + h0 = first + heads - 1; + } + let mut h1 = first + 1; + if 1 >= heads { + h1 = first + heads - 1; + } + let mut h2 = first + 2; + if 2 >= heads { + h2 = first + heads - 1; + } + let mut h3 = first + 3; + if 3 >= heads { + h3 = first + heads - 1; + } + for l in 0..32 across lanes(32) { + // The scores of each of the 2 positions of the lane, for each head. A position past `pos` reads row + // `pos`, and its score is -3e38. + let mut t0 = c * 64 + 0 + l; + if t0 > pos { + t0 = pos; + } + let mut dot0_0 : f32 = 0.0; + let mut dot0_1 : f32 = 0.0; + let mut dot0_2 : f32 = 0.0; + let mut dot0_3 : f32 = 0.0; + let mut t1 = c * 64 + 32 + l; + if t1 > pos { + t1 = pos; + } + let mut dot1_0 : f32 = 0.0; + let mut dot1_1 : f32 = 0.0; + let mut dot1_2 : f32 = 0.0; + let mut dot1_3 : f32 = 0.0; + for d in 0..head_dim { + let k0 = k_cache[t0][g][d] as f32; + let k1 = k_cache[t1][g][d] as f32; + let q0 = q[h0][d]; + dot0_0 = dot0_0 + q0 * k0; + dot1_0 = dot1_0 + q0 * k1; + let q1 = q[h1][d]; + dot0_1 = dot0_1 + q1 * k0; + dot1_1 = dot1_1 + q1 * k1; + let q2 = q[h2][d]; + dot0_2 = dot0_2 + q2 * k0; + dot1_2 = dot1_2 + q2 * k1; + let q3 = q[h3][d]; + dot0_3 = dot0_3 + q3 * k0; + dot1_3 = dot1_3 + q3 * k1; + } + let mut s0_0 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_0 = dot0_0 * scale; + } + w[s][0][0 + l] = s0_0; + let mut s1_0 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_0 = dot1_0 * scale; + } + w[s][0][32 + l] = s1_0; + top[s][0][l] = s0_0.max(s1_0); + let mut s0_1 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_1 = dot0_1 * scale; + } + w[s][1][0 + l] = s0_1; + let mut s1_1 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_1 = dot1_1 * scale; + } + w[s][1][32 + l] = s1_1; + top[s][1][l] = s0_1.max(s1_1); + let mut s0_2 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_2 = dot0_2 * scale; + } + w[s][2][0 + l] = s0_2; + let mut s1_2 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_2 = dot1_2 * scale; + } + w[s][2][32 + l] = s1_2; + top[s][2][l] = s0_2.max(s1_2); + let mut s0_3 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_3 = dot0_3 * scale; + } + w[s][3][0 + l] = s0_3; + let mut s1_3 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_3 = dot1_3 * scale; + } + w[s][3][32 + l] = s1_3; + top[s][3][l] = s0_3.max(s1_3); + } + let big0 = lanes::max(&top[s][0], 32); + let big1 = lanes::max(&top[s][1], 32); + let big2 = lanes::max(&top[s][2], 32); + let big3 = lanes::max(&top[s][3], 32); + // The weight of each position, as exp(score - the largest score of the block). + for l in 0..32 across lanes(32) { + let e0_0 = (w[s][0][0 + l] - big0).fast_exp(); + w[s][0][0 + l] = e0_0; + let e1_0 = (w[s][0][32 + l] - big0).fast_exp(); + w[s][0][32 + l] = e1_0; + sums[s][0][l] = e0_0 + e1_0; + let e0_1 = (w[s][1][0 + l] - big1).fast_exp(); + w[s][1][0 + l] = e0_1; + let e1_1 = (w[s][1][32 + l] - big1).fast_exp(); + w[s][1][32 + l] = e1_1; + sums[s][1][l] = e0_1 + e1_1; + let e0_2 = (w[s][2][0 + l] - big2).fast_exp(); + w[s][2][0 + l] = e0_2; + let e1_2 = (w[s][2][32 + l] - big2).fast_exp(); + w[s][2][32 + l] = e1_2; + sums[s][2][l] = e0_2 + e1_2; + let e0_3 = (w[s][3][0 + l] - big3).fast_exp(); + w[s][3][0 + l] = e0_3; + let e1_3 = (w[s][3][32 + l] - big3).fast_exp(); + w[s][3][32 + l] = e1_3; + sums[s][3][l] = e0_3 + e1_3; + } + let total0 = lanes::sum(&sums[s][0], 32); + let total1 = lanes::sum(&sums[s][1], 32); + let total2 = lanes::sum(&sums[s][2], 32); + let total3 = lanes::sum(&sums[s][3], 32); + // The weighted sum of the rows of V. Lane l takes values l, l + 32, l + 64 and l + 96. + for l in 0..32 across lanes(32) { + let mut acc0_0 : f32 = 0.0; + let mut acc0_1 : f32 = 0.0; + let mut acc0_2 : f32 = 0.0; + let mut acc0_3 : f32 = 0.0; + let mut acc1_0 : f32 = 0.0; + let mut acc1_1 : f32 = 0.0; + let mut acc1_2 : f32 = 0.0; + let mut acc1_3 : f32 = 0.0; + let mut acc2_0 : f32 = 0.0; + let mut acc2_1 : f32 = 0.0; + let mut acc2_2 : f32 = 0.0; + let mut acc2_3 : f32 = 0.0; + let mut acc3_0 : f32 = 0.0; + let mut acc3_1 : f32 = 0.0; + let mut acc3_2 : f32 = 0.0; + let mut acc3_3 : f32 = 0.0; + // With head_dim below 128, values past it read others again, and their sums go nowhere. + let d0 = (0 + l) % head_dim; + let d1 = (32 + l) % head_dim; + let d2 = (64 + l) % head_dim; + let d3 = (96 + l) % head_dim; + let mut last = pos - c * 64; + if last > 63 { + last = 63; + } + for t in 0..last + 1 { + let row = c * 64 + t; + let v0 = v_cache[row][g][d0] as f32; + let v1 = v_cache[row][g][d1] as f32; + let v2 = v_cache[row][g][d2] as f32; + let v3 = v_cache[row][g][d3] as f32; + let w0 = w[s][0][t]; + acc0_0 = acc0_0 + w0 * v0; + acc0_1 = acc0_1 + w0 * v1; + acc0_2 = acc0_2 + w0 * v2; + acc0_3 = acc0_3 + w0 * v3; + let w1 = w[s][1][t]; + acc1_0 = acc1_0 + w1 * v0; + acc1_1 = acc1_1 + w1 * v1; + acc1_2 = acc1_2 + w1 * v2; + acc1_3 = acc1_3 + w1 * v3; + let w2 = w[s][2][t]; + acc2_0 = acc2_0 + w2 * v0; + acc2_1 = acc2_1 + w2 * v1; + acc2_2 = acc2_2 + w2 * v2; + acc2_3 = acc2_3 + w2 * v3; + let w3 = w[s][3][t]; + acc3_0 = acc3_0 + w3 * v0; + acc3_1 = acc3_1 + w3 * v1; + acc3_2 = acc3_2 + w3 * v2; + acc3_3 = acc3_3 + w3 * v3; + } + if 0 < heads { + if 0 < head_dim { + part[gt][c][s * 4 + 0][0 + l] = acc0_0; + } + if 32 < head_dim { + part[gt][c][s * 4 + 0][32 + l] = acc0_1; + } + if 64 < head_dim { + part[gt][c][s * 4 + 0][64 + l] = acc0_2; + } + if 96 < head_dim { + part[gt][c][s * 4 + 0][96 + l] = acc0_3; + } + } + if 1 < heads { + if 0 < head_dim { + part[gt][c][s * 4 + 1][0 + l] = acc1_0; + } + if 32 < head_dim { + part[gt][c][s * 4 + 1][32 + l] = acc1_1; + } + if 64 < head_dim { + part[gt][c][s * 4 + 1][64 + l] = acc1_2; + } + if 96 < head_dim { + part[gt][c][s * 4 + 1][96 + l] = acc1_3; + } + } + if 2 < heads { + if 0 < head_dim { + part[gt][c][s * 4 + 2][0 + l] = acc2_0; + } + if 32 < head_dim { + part[gt][c][s * 4 + 2][32 + l] = acc2_1; + } + if 64 < head_dim { + part[gt][c][s * 4 + 2][64 + l] = acc2_2; + } + if 96 < head_dim { + part[gt][c][s * 4 + 2][96 + l] = acc2_3; + } + } + if 3 < heads { + if 0 < head_dim { + part[gt][c][s * 4 + 3][0 + l] = acc3_0; + } + if 32 < head_dim { + part[gt][c][s * 4 + 3][32 + l] = acc3_1; + } + if 64 < head_dim { + part[gt][c][s * 4 + 3][64 + l] = acc3_2; + } + if 96 < head_dim { + part[gt][c][s * 4 + 3][96 + l] = acc3_3; + } + } + } + if 0 < heads { + part[gt][c][s * 4 + 0][head_dim] = big0; + part[gt][c][s * 4 + 0][head_dim + 1] = total0; + } + if 1 < heads { + part[gt][c][s * 4 + 1][head_dim] = big1; + part[gt][c][s * 4 + 1][head_dim + 1] = total1; + } + if 2 < heads { + part[gt][c][s * 4 + 2][head_dim] = big2; + part[gt][c][s * 4 + 2][head_dim + 1] = total2; + } + if 3 < heads { + part[gt][c][s * 4 + 3][head_dim] = big3; + part[gt][c][s * 4 + 3][head_dim + 1] = total3; + } + } + } + } + } + return; +} + +/// Merges the parts of `split_attention` of blocks of `n_pos` positions. A block does 32 values of one +/// head of Q, a value for each lane. +fn split_attention_merge(out : &mut Tensor, part : &Tensor, pos : i32, n_pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + let group = q_heads / kv_heads; + let tiles = (group + 7) / 8; + let splits = (pos + n_pos) / n_pos; + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for dq in 0..head_dim / 32 across blocks { + let mut top = unsafe { + Tensor::uninit() + }; + let g = h / group; + let tile = (h - g * group) / 8; + let gt = g * tiles + tile; + let at = h - g * group - tile * 8; + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let mut m : f32 = -3.0e38; + let mut c = l; + while c < splits { + m = m.max(part[gt][c][at][head_dim]); + c = c + 32; + } + top[s][0][l] = m; + } + let big = lanes::max(&top[s][0], 32); + for l in 0..32 across lanes(32) { + let d = dq * 32 + l; + let mut total : f32 = 0.0; + let mut acc : f32 = 0.0; + for c in 0..splits { + let w = (part[gt][c][at][head_dim] - big).fast_exp(); + total = total + w * part[gt][c][at][head_dim + 1]; + acc = acc + w * part[gt][c][at][d]; + } + out[h][d] = acc / total; + } + } + } + } + } + return; +} + +// The kernels that store the K and V of a generated token: copies of `nn_rope_and_store` and +// `nn_norm_rope_and_store` of `std::nn`, with a KV cache of f16. They compute in f32 and round +// what they store. + +/// RoPE for the token at position `pos`, and its K and V into the KV cache. Writes each head of +/// q, turned, to `q_out`, and each head of k, turned, and of v to row `pos` of the cache. Value i +/// of a head pairs with value i + head_dim / 2, as in the Llama and Qwen models of Hugging Face. +/// Both turn by the angle whose cosine and sine are cos[pos][i] and sin[pos][i]. +fn rope_and_store(q_out : &mut Tensor, k_cache : &mut Tensor, v_cache : &mut Tensor, q : &Tensor, k : &Tensor, v : &Tensor, cos : &Tensor, sin : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + let half = head_dim / 2; + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(q_out.extent(0), q_out.extent(1), q_heads, head_dim); + nn_check_heads(k.extent(0), k.extent(1), kv_heads, head_dim); + nn_check_heads(v.extent(0), v.extent(1), kv_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(pos < cos.extent(0) && pos < sin.extent(0) && half <= cos.extent(1) && half <= sin.extent(1), "rope_and_store: `cos` and `sin` need a row for `pos` with head_dim / 2 values"); + spawn on(Topology::Device) { + for h in 0..q_heads + kv_heads across blocks { + for i in 0..128 across lanes { + if i < head_dim { + // Value i of the head, its partner, and the angle that they share. + let mut j = i; + let mut sign : f32 = -1.0; + let mut partner = i + half; + if i >= half { + j = i - half; + sign = 1.0; + partner = i - half; + } + let c = cos[pos][j]; + let s = sin[pos][j]; + if h < q_heads { + q_out[h][i] = q[h][i] * c + sign * q[h][partner] * s; + } else { + k_cache[pos][h - q_heads][i] = (k[h - q_heads][i] * c + sign * k[h - q_heads][partner] * s) as f16; + v_cache[pos][h - q_heads][i] = v[h - q_heads][i] as f16; + } + } + } + } + } + return; +} + +/// As `rope_and_store`, after an RMSNorm over each head of q and of k: value i of a head x +/// becomes x[i] / sqrt(mean(x^2) + eps) * norm[i], where `norm` is `q_norm` for q and `k_norm` +/// for k. Qwen3 has these norms. +fn norm_rope_and_store(q_out : &mut Tensor, k_cache : &mut Tensor, v_cache : &mut Tensor, q : &Tensor, k : &Tensor, v : &Tensor, q_norm : &Tensor, k_norm : &Tensor, cos : &Tensor, sin : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32, eps : f32) -> void { + let half = head_dim / 2; + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(q_out.extent(0), q_out.extent(1), q_heads, head_dim); + nn_check_heads(k.extent(0), k.extent(1), kv_heads, head_dim); + nn_check_heads(v.extent(0), v.extent(1), kv_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_norm.len() >= head_dim && k_norm.len() >= head_dim, "norm_rope_and_store: `q_norm` and `k_norm` need head_dim values"); + assert(pos < cos.extent(0) && pos < sin.extent(0) && half <= cos.extent(1) && half <= sin.extent(1), "norm_rope_and_store: `cos` and `sin` need a row for `pos` with head_dim / 2 values"); + spawn on(Topology::Device) { + for h in 0..q_heads + kv_heads across blocks { + let mut x = unsafe { Tensor::uninit() }; + let mut part = unsafe { Tensor::uninit() }; + for i in 0..128 across lanes { + let mut a : f32 = 0.0; + if i < head_dim { + if h < q_heads { + a = q[h][i]; + } else { + a = k[h - q_heads][i]; + } + } + x[i] = a; + part[i] = a * a; + } + let ss = lanes::sum(&part, 128); + let inv = 1.0 / (ss / (head_dim as f32) + eps).sqrt(); + for i in 0..128 across lanes { + if i < head_dim { + // Value i of the head, its partner, and the angle that they share. + let mut j = i; + let mut sign : f32 = -1.0; + let mut partner = i + half; + if i >= half { + j = i - half; + sign = 1.0; + partner = i - half; + } + let c = cos[pos][j]; + let s = sin[pos][j]; + if h < q_heads { + let a = x[i] * inv * (q_norm[i] as f32); + let b = x[partner] * inv * (q_norm[partner] as f32); + q_out[h][i] = a * c + sign * b * s; + } else { + let a = x[i] * inv * (k_norm[i] as f32); + let b = x[partner] * inv * (k_norm[partner] as f32); + k_cache[pos][h - q_heads][i] = (a * c + sign * b * s) as f16; + v_cache[pos][h - q_heads][i] = v[h - q_heads][i] as f16; + } + } + } + } + } + return; +} +//===- deltanet.vx - Qwen app -----------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// One generated token through the Gated DeltaNet of a linear attention layer of Qwen3.5 and +// Qwen3.6 (#89), after the product `linear_in` and before the product `linear_out`. The math is +// that of `modeling_qwen3_5_moe.py` of transformers: +// +// - `proj`, the output of `linear_in`, has q (k_heads x 128), k (k_heads x 128), v (v_heads x 128), +// z (v_heads x 128), then b and a (v_heads each), at the offsets that the caller gives. +// - q, k and v go through a causal depthwise convolution of width 4 and a SiLU. q and k then get an +// L2 norm for each head (eps 1e-6 inside the square root), and q is multiplied by 1/sqrt(128). +// - beta = sigmoid(b), and the decay exp(g) with g = -exp(A_log) softplus(a + dt_bias). The weight +// file stores -exp(A_log) as `neg_a`. +// - Head h of v uses head h / (v_heads / k_heads) of q and k. Its state S[k][v] decays, then +// S += k (beta (v - k . S)), and the output is q . S. +// - The output gets an RMS norm for each head, times the norm weight, times silu(z). +// +// All the heads have 128 values. The state of a layer is `conv_state` [2 k_heads + v_heads, 128, 3], +// the last 3 inputs of each channel of the convolution, oldest first, and `state` [v_heads, 128, 128] +// as S[v][k]: the 128 values of k for one value of v are next to each other, so that the 32 lanes of +// a SIMD group read them in one load. Both start at zero. +import core::num; +import std::nn; +import qwen::simd; + +/// The scratch tensors of one token, in GPU memory: q and k after the convolution and the norm +/// [k_heads, 128], v after the convolution [v_heads, 128], beta and the decay exp(g) of each head of +/// v, and q . S [v_heads, 128]. +struct DeltaNetScratch { + q : Tensor, + k : Tensor, + v : Tensor, + beta : Tensor, + decay : Tensor, + o : Tensor, +} + +fn deltanet_scratch(k_heads : i32, v_heads : i32) -> DeltaNetScratch { + return DeltaNetScratch { + q : transfer(Tensor([k_heads, 128]), Memory::HBM), + k : transfer(Tensor([k_heads, 128]), Memory::HBM), + v : transfer(Tensor([v_heads, 128]), Memory::HBM), + beta : transfer(Tensor([v_heads]), Memory::HBM), + decay : transfer(Tensor([v_heads]), Memory::HBM), + o : transfer(Tensor([v_heads, 128]), Memory::HBM), + }; +} + +/// A tensor of zeros in GPU memory. +fn dn_zeros(a : i32, b : i32, c : i32) -> Tensor { + let mut x = Tensor([a, b, c]); + for i in 0..a { + for j in 0..b { + for k in 0..c { + x[i][j][k] = 0.0; + } + } + } + return transfer(x, Memory::HBM); +} + +/// The state of one layer at the start: zero. +fn deltanet_conv_state(k_heads : i32, v_heads : i32) -> Tensor { + return dn_zeros(2 * k_heads + v_heads, 128, 3); +} + +fn deltanet_state(v_heads : i32) -> Tensor { + return dn_zeros(v_heads, 128, 128); +} + +/// The Gated DeltaNet of one token: `y` (v_heads x 128 values, the input of `linear_out`) from `proj` +/// (the output of `linear_in`). z starts at `z_at` of `proj`, b at `b_at` and a at `a_at`. `conv` has +/// 4 taps for each of the (2 k_heads + v_heads) x 128 channels, channel c at 4 c, oldest tap +/// first. `neg_a` and `dt_bias` have v_heads values, and `norm` 128. +fn deltanet_step(y : &mut Tensor, conv_state : &mut Tensor, state : &mut Tensor, t : &mut DeltaNetScratch, proj : &Tensor, conv : &Tensor, neg_a : &Tensor, dt_bias : &Tensor, norm : &Tensor, z_at : i32, b_at : i32, a_at : i32, k_heads : i32, v_heads : i32, eps : f32) -> void { + let channels = (2 * k_heads + v_heads) * 128; + assert(k_heads > 0 && v_heads % k_heads == 0 && v_heads <= 64, "deltanet_step: v_heads must be a multiple of k_heads, and at most 64"); + assert(conv_state.extent(0) == 2 * k_heads + v_heads && conv_state.extent(1) == 128 && conv_state.extent(2) == 3, "deltanet_step: conv_state must be [2 k_heads + v_heads, 128, 3]"); + assert(state.extent(0) == v_heads && state.extent(1) == 128 && state.extent(2) == 128, "deltanet_step: state must be [v_heads, 128, 128]"); + assert(conv.len() == channels * 4, "deltanet_step: conv must have 4 taps for each channel"); + assert(proj.len() >= channels && proj.len() >= z_at + v_heads * 128 && proj.len() >= b_at + v_heads && proj.len() >= a_at + v_heads, "deltanet_step: proj is too short for its offsets"); + assert(neg_a.len() >= v_heads && dt_bias.len() >= v_heads && norm.len() >= 128 && y.len() >= v_heads * 128, "deltanet_step: a tensor is too short"); + deltanet_conv(&mut t.q, &mut t.k, &mut t.v, conv_state, proj, conv, k_heads, v_heads); + deltanet_gates(&mut t.beta, &mut t.decay, proj, neg_a, dt_bias, b_at, a_at, v_heads); + deltanet_recur(&mut t.o, state, &t.q, &t.k, &t.v, &t.beta, &t.decay, v_heads / k_heads, v_heads); + deltanet_gated_norm(y, &t.o, proj, norm, z_at, v_heads, eps); + return; +} + +/// The convolution and the SiLU of q, k and v, and the L2 norms of q and k. Block h does the 128 +/// channels of one head: heads 0 to k_heads - 1 of q, then those of k, then those of v. The channels +/// of `proj` are in the same order, so channel i of block h is h * 128 + i. +fn deltanet_conv(qn : &mut Tensor, kn : &mut Tensor, vv : &mut Tensor, conv_state : &mut Tensor, proj : &Tensor, conv : &Tensor, k_heads : i32, v_heads : i32) -> void { + spawn on(Topology::Device) { + for h in 0..2 * k_heads + v_heads across blocks { + let mut y = unsafe { Tensor::uninit() }; + let mut part = unsafe { Tensor::uninit() }; + for i in 0..128 across lanes { + let c = h * 128 + i; + let x0 = conv_state[h][i][0]; + let x1 = conv_state[h][i][1]; + let x2 = conv_state[h][i][2]; + let x3 = proj[c]; + let a = conv[c * 4] * x0 + conv[c * 4 + 1] * x1 + conv[c * 4 + 2] * x2 + conv[c * 4 + 3] * x3; + let s = a / (1.0 + (0.0 - a).fast_exp()); + conv_state[h][i][0] = x1; + conv_state[h][i][1] = x2; + conv_state[h][i][2] = x3; + y[i] = s; + part[i] = s * s; + } + let ss = lanes::sum(&part, 128); + let inv = 1.0 / (ss + 0.000001).sqrt(); + for i in 0..128 across lanes { + if h < k_heads { + qn[h][i] = y[i] * inv * 0.08838834764831845; + } else if h < 2 * k_heads { + kn[h - k_heads][i] = y[i] * inv; + } else { + vv[h - 2 * k_heads][i] = y[i]; + } + } + } + } + return; +} + +/// beta = sigmoid(b) and the decay exp(neg_a softplus(a + dt_bias)) of each head of v. softplus(x) +/// is x above 20, as in torch. +fn deltanet_gates(beta : &mut Tensor, decay : &mut Tensor, proj : &Tensor, neg_a : &Tensor, dt_bias : &Tensor, b_at : i32, a_at : i32, v_heads : i32) -> void { + spawn on(Topology::Device) { + for blk in 0..1 across blocks { + for j in 0..64 across lanes { + if j < v_heads { + let b = proj[b_at + j]; + beta[j] = 1.0 / (1.0 + (0.0 - b).fast_exp()); + let x = proj[a_at + j] + dt_bias[j]; + let mut sp = x; + if x <= 20.0 { + sp = simd_log(1.0 + x.fast_exp()); + } + decay[j] = (neg_a[j] * sp).fast_exp(); + } + } + } + } + return; +} + +/// The update of the state and the output q . S, for each head h of v. Block (h, vq) is one SIMD +/// group for values vq * 32 to vq * 32 + 31 of v. Lane l owns values 4 l to 4 l + 3 of k. For each +/// value of v, the lanes add up k . S, then each lane updates its 4 values of S and the lanes add up +/// q . S. Lane m keeps the output of value m. +fn deltanet_recur(o : &mut Tensor, state : &mut Tensor, qn : &Tensor, kn : &Tensor, vv : &Tensor, beta : &Tensor, decay : &Tensor, group : i32, v_heads : i32) -> void { + spawn on(Topology::Device) { + for h in 0..v_heads across blocks { + for vq in 0..4 across blocks { + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let g = h / group; + let d = 4 * l; + let q0 = qn[g][d]; + let q1 = qn[g][d + 1]; + let q2 = qn[g][d + 2]; + let q3 = qn[g][d + 3]; + let k0 = kn[g][d]; + let k1 = kn[g][d + 1]; + let k2 = kn[g][d + 2]; + let k3 = kn[g][d + 3]; + let b = beta[h]; + let dec = decay[h]; + let mut mine : f32 = 0.0; + for m in 0..32 { + let v = vq * 32 + m; + let s0 = state[h][v][d] * dec; + let s1 = state[h][v][d + 1] * dec; + let s2 = state[h][v][d + 2] * dec; + let s3 = state[h][v][d + 3] * dec; + let kv = simd_sum(s0 * k0 + s1 * k1 + s2 * k2 + s3 * k3); + let delta = (vv[h][v] - kv) * b; + let n0 = s0 + k0 * delta; + let n1 = s1 + k1 * delta; + let n2 = s2 + k2 * delta; + let n3 = s3 + k3 * delta; + state[h][v][d] = n0; + state[h][v][d + 1] = n1; + state[h][v][d + 2] = n2; + state[h][v][d + 3] = n3; + let out = simd_sum(n0 * q0 + n1 * q1 + n2 * q2 + n3 * q3); + if m == l { + mine = out; + } + } + o[h][vq * 32 + l] = mine; + } + } + } + } + } + return; +} + +/// y = rms_norm(o) * norm * silu(z), for each head of v. Block h does one head. +fn deltanet_gated_norm(y : &mut Tensor, o : &Tensor, proj : &Tensor, norm : &Tensor, z_at : i32, v_heads : i32, eps : f32) -> void { + spawn on(Topology::Device) { + for h in 0..v_heads across blocks { + let mut part = unsafe { Tensor::uninit() }; + for i in 0..128 across lanes { + let a = o[h][i]; + part[i] = a * a; + } + let ss = lanes::sum(&part, 128); + let inv = 1.0 / (ss / 128.0 + eps).sqrt(); + for i in 0..128 across lanes { + let z = proj[z_at + h * 128 + i]; + y[h * 128 + i] = o[h][i] * inv * norm[i] * (z / (1.0 + (0.0 - z).fast_exp())); + } + } + } + return; +} +//===- gated_attention.vx - Qwen app ----------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// The full attention of one token in a layer of Qwen3.5 and Qwen3.6 (#89), between the product +// `qkv` and the product `attn_out`, with the math of `modeling_qwen3_5_moe.py` of transformers: +// +// - `qkvg`, the output of `qkv`, has q (q_heads x 256), k (kv_heads x 256), v (kv_heads x 256), +// then the gate (q_heads x 256). +// - q and k get an RMS norm for each head, times their norm weights, which the weight file stores +// as 1 + w. RoPE then turns the first `rot` values of each head (rotate_half inside those +// values), and leaves the others. +// - Attention with the scale 1/sqrt(256) over the KV cache, which is f16 [position, kv_head, 256]. +// - The output is multiplied by sigmoid(gate). +// +// The attention has the design of `vec_attention` (llama.cpp's kernel_flash_attn_ext_vec, MIT +// License, Copyright (c) 2023-2026 The ggml authors), for 256 values a head: each block is a SIMD +// group of one head of q, and lane l owns values 8 l to 8 l + 7. +import core::num; +import std::nn; +import qwen::simd; + +/// The norms and RoPE of q and k at position `pos`, and the store of k and v into the caches. Block h +/// does head h of q, then the heads of k. `cos` and `sin` have rot / 2 values for each position. +fn gated_norm_rope_and_store(q_out : &mut Tensor, k_cache : &mut Tensor, v_cache : &mut Tensor, qkvg : &Tensor, q_norm : &Tensor, k_norm : &Tensor, cos : &Tensor, sin : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, rot : i32, eps : f32) -> void { + let half = rot / 2; + assert(q_out.extent(0) == q_heads && q_out.extent(1) == 256, "gated_norm_rope_and_store: q_out must be [q_heads, 256]"); + assert(k_cache.extent(0) > pos && k_cache.extent(1) == kv_heads && k_cache.extent(2) == 256 && v_cache.extent(0) > pos && v_cache.extent(1) == kv_heads && v_cache.extent(2) == 256, "gated_norm_rope_and_store: the caches must be [positions, kv_heads, 256] with a row for pos"); + assert(qkvg.len() >= (2 * q_heads + 2 * kv_heads) * 256 && q_norm.len() >= 256 && k_norm.len() >= 256, "gated_norm_rope_and_store: a tensor is too short"); + assert(rot % 2 == 0 && rot <= 256 && pos < cos.extent(0) && pos < sin.extent(0) && half <= cos.extent(1) && half <= sin.extent(1), "gated_norm_rope_and_store: `cos` and `sin` need a row for `pos` with rot / 2 values"); + spawn on(Topology::Device) { + for h in 0..q_heads + kv_heads across blocks { + let mut x = unsafe { Tensor::uninit() }; + let mut part = unsafe { Tensor::uninit() }; + for i in 0..256 across lanes { + let a = qkvg[h * 256 + i]; + x[i] = a; + part[i] = a * a; + } + let ss = lanes::sum(&part, 256); + let inv = 1.0 / (ss / 256.0 + eps).sqrt(); + for i in 0..256 across lanes { + let mut w = q_norm[i]; + if h >= q_heads { + w = k_norm[i]; + } + let a = x[i] * inv * w; + let mut r = a; + if i < rot { + // Value i, its partner, and the angle that they share. + let mut j = i; + let mut sign : f32 = -1.0; + let mut partner = i + half; + if i >= half { + j = i - half; + sign = 1.0; + partner = i - half; + } + let mut wp = q_norm[partner]; + if h >= q_heads { + wp = k_norm[partner]; + } + let b = x[partner] * inv * wp; + r = a * cos[pos][j] + sign * b * sin[pos][j]; + } + if h < q_heads { + q_out[h][i] = r; + } else { + k_cache[pos][h - q_heads][i] = r as f16; + v_cache[pos][h - q_heads][i] = qkvg[(q_heads + kv_heads + h - q_heads) * 256 + i] as f16; + } + } + } + } + return; +} + +/// The attention of the token at position `pos`, times sigmoid(gate): y[h * 256 + d] for each head +/// h of q. `part` is scratch space from `gated_attention_scratch`. +fn gated_attention(y : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, qkvg : &Tensor, pos : i32, q_heads : i32, kv_heads : i32) -> void { + assert(q.extent(0) == q_heads && q.extent(1) == 256 && q_heads % kv_heads == 0, "gated_attention: q must be [q_heads, 256], and q_heads a multiple of kv_heads"); + assert(k_cache.extent(0) > pos && k_cache.extent(1) == kv_heads && k_cache.extent(2) == 256 && v_cache.extent(0) > pos && v_cache.extent(1) == kv_heads && v_cache.extent(2) == 256, "gated_attention: the caches must be [positions, kv_heads, 256] with a row for pos"); + assert(part.extent(0) >= q_heads && part.extent(1) >= 64 && part.extent(2) == 260, "gated_attention: `part` is too small. Make it with gated_attention_scratch"); + assert(y.len() >= q_heads * 256 && qkvg.len() >= (2 * q_heads + 2 * kv_heads) * 256, "gated_attention: a tensor is too short"); + let mut nwg = 32; + if 2 * nwg * 32 < pos + 1 { + nwg = nwg * 2; + } + gated_attention_parts(part, q, k_cache, v_cache, pos, q_heads, q_heads / kv_heads, nwg, 0.0625); + gated_attention_merge(y, part, qkvg, nwg, q_heads, (q_heads + 2 * kv_heads) * 256); + return; +} + +/// The scratch space of `gated_attention`, on the CPU: up to 64 parts for each head of q, each the sum +/// of V (256 values), the largest score, and the sum of the weights. +fn gated_attention_scratch(q_heads : i32) -> Tensor { + return Tensor([q_heads, 64, 260]); +} + +/// The parts of `gated_attention`. Block (h, w) is a SIMD group for head h of q. It does the blocks of +/// 32 positions w, w + nwg, w + 2 nwg, ... up to `pos`, and writes part[h][w]: the sum of V, not +/// divided, then the largest score and the sum of the weights. For each row, the lanes add up their +/// parts of q . k, and lane r keeps the score of row r. Each lane then takes the weight of each row +/// from the lane that keeps it, for the sum of V. +fn gated_attention_parts(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, group : i32, nwg : i32, scale : f32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for w in 0..nwg across blocks { + let mut stats = unsafe { Tensor::uninit() }; + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let g = h / group; + let d = 8 * l; + let q0 = q[h][d] * scale; + let q1 = q[h][d + 1] * scale; + let q2 = q[h][d + 2] * scale; + let q3 = q[h][d + 3] * scale; + let q4 = q[h][d + 4] * scale; + let q5 = q[h][d + 5] * scale; + let q6 = q[h][d + 6] * scale; + let q7 = q[h][d + 7] * scale; + let mut big : f32 = -3.0e38; + let mut total : f32 = 0.0; + let mut o0 : f32 = 0.0; + let mut o1 : f32 = 0.0; + let mut o2 : f32 = 0.0; + let mut o3 : f32 = 0.0; + let mut o4 : f32 = 0.0; + let mut o5 : f32 = 0.0; + let mut o6 : f32 = 0.0; + let mut o7 : f32 = 0.0; + let chunks = (pos + 32) / 32; + let mut c = w; + while c < chunks { + let r0 = c * 32; + let mut mine : f32 = -3.0e38; + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > pos { + kept = pos; + } + let k0 = half4_at(k_cache, kept, g, d, 0); + let k1 = half4_at(k_cache, kept, g, d, 1); + let k2 = half4_at(k_cache, kept, g, d, 2); + let k3 = half4_at(k_cache, kept, g, d, 3); + let k4 = half4_at(k_cache, kept, g, d + 4, 0); + let k5 = half4_at(k_cache, kept, g, d + 4, 1); + let k6 = half4_at(k_cache, kept, g, d + 4, 2); + let k7 = half4_at(k_cache, kept, g, d + 4, 3); + let mut score = simd_sum(((k0 * q0 + k1 * q1) + (k2 * q2 + k3 * q3)) + ((k4 * q4 + k5 * q5) + (k6 * q6 + k7 * q7))); + if row > pos { + score = -3.0e38; + } + if r == l { + mine = score; + } + } + let top = big.max(simd_max(mine)); + let shrink = (big - top).fast_exp(); + let p = (mine - top).fast_exp(); + total = total * shrink + simd_sum(p); + o0 = o0 * shrink; + o1 = o1 * shrink; + o2 = o2 * shrink; + o3 = o3 * shrink; + o4 = o4 * shrink; + o5 = o5 * shrink; + o6 = o6 * shrink; + o7 = o7 * shrink; + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > pos { + kept = pos; + } + let pr = simd_value(p, r); + o0 = o0 + half4_at(v_cache, kept, g, d, 0) * pr; + o1 = o1 + half4_at(v_cache, kept, g, d, 1) * pr; + o2 = o2 + half4_at(v_cache, kept, g, d, 2) * pr; + o3 = o3 + half4_at(v_cache, kept, g, d, 3) * pr; + o4 = o4 + half4_at(v_cache, kept, g, d + 4, 0) * pr; + o5 = o5 + half4_at(v_cache, kept, g, d + 4, 1) * pr; + o6 = o6 + half4_at(v_cache, kept, g, d + 4, 2) * pr; + o7 = o7 + half4_at(v_cache, kept, g, d + 4, 3) * pr; + } + big = top; + c = c + nwg; + } + part[h][w][d] = o0; + part[h][w][d + 1] = o1; + part[h][w][d + 2] = o2; + part[h][w][d + 3] = o3; + part[h][w][d + 4] = o4; + part[h][w][d + 5] = o5; + part[h][w][d + 6] = o6; + part[h][w][d + 7] = o7; + // Every lane has the same largest score and sum of the weights. Lanes 0 and 1 keep them for + // the next loop. + if l < 2 { + let mut x = big; + if l == 1 { + x = total; + } + stats[s][l] = x; + } + } + for l in 0..2 across lanes(32) { + part[h][w][256 + l] = stats[s][l]; + } + } + } + } + } + return; +} + +/// Merges the first `parts` parts of `gated_attention_parts` for each head of q, and multiplies by +/// sigmoid of the gate, which starts at `gate_at` of `qkvg`. A block of 32 lanes does 32 values of one +/// head, a value for each lane. +fn gated_attention_merge(y : &mut Tensor, part : &Tensor, qkvg : &Tensor, parts : i32, q_heads : i32, gate_at : i32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for dq in 0..8 across blocks { + let mut top = unsafe { Tensor::uninit() }; + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let mut m : f32 = -3.0e38; + let mut c = l; + while c < parts { + m = m.max(part[h][c][256]); + c = c + 32; + } + top[s][l] = m; + } + let big = lanes::max(&top[s], 32); + for l in 0..32 across lanes(32) { + let d = dq * 32 + l; + let mut total : f32 = 0.0; + let mut acc : f32 = 0.0; + for c in 0..parts { + let w = (part[h][c][256] - big).fast_exp(); + total = total + w * part[h][c][257]; + acc = acc + w * part[h][c][d]; + } + let gate = qkvg[gate_at + h * 256 + d]; + y[h * 256 + d] = acc / total / (1.0 + (0.0 - gate).fast_exp()); + } + } + } + } + } + return; +} +//===- main.vx - Qwen app ---------------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// Generates tokens with greedy decoding, on the GPU: +// +// vxc src/main.vx --package qwen=src --host default \ +// --machine ~/.vx/current/fleet/m4-uma.vx -- WEIGHTS --tokens 750,75698,1445 --steps 16 +// vxc src/main.vx ... -- WEIGHTS --tokenizer TOKENIZER --prompt "def fibonacci(n):" --steps 64 +// vxc src/main.vx ... -- WEIGHTS --tokenizer TOKENIZER --chat --prompt-file FILE --steps 512 +// +// With --tokens, it prints the lines that `scripts/reference.py` prints, without the margin, and +// then the time of a token. `scripts/compare.py` compares the two outputs. +// +// With --tokenizer, a file of `scripts/convert_tokenizer.py`, the prompt is text: --prompt TEXT or +// --prompt-file FILE. The program prints the prompt and the text that it generates. It stops at a +// special token, such as <|im_end|>, or after --steps tokens. --chat puts the prompt in the chat +// format of the Instruct models and prints only the reply. --lines prints the lines of --tokens +// in place of the text. +import core::convert; +import std::time; +import std::vec; +import qwen::weights; +import qwen::model; +import qwen::qwen35; +import qwen::prefill35; +import qwen::prefill; +import qwen::session; +import qwen::speculate; +import qwen::round; +import qwen::tokenizer; + +/// The options of the command line. +struct Options { + weights : *const i8, + tokens : *const i8, + tokenizer : *const i8, + prompt : *const i8, + prompt_file : *const i8, + steps : *const i8, + has_tokens : bool, + has_tokenizer : bool, + has_prompt : bool, + has_prompt_file : bool, + has_steps : bool, + context : *const i8, + has_context : bool, + requests : *const i8, + has_requests : bool, + replies : *const i8, + has_replies : bool, + session : bool, + chat : bool, + lines : bool, + draft : *const i8, + has_draft : bool, +} + +/// The options of `argv`. Asserts that they are complete and that they fit together. +fn parse_options(argc : i32, argv : *mut *mut i8) -> Options { + assert(argc >= 4, "give: WEIGHTS --tokens 1,2,3 --steps N, or WEIGHTS --tokenizer FILE (--prompt TEXT | --prompt-file FILE) [--chat] [--lines] --steps N"); + let empty : *const i8 = ""; + let mut o = Options { + weights: unsafe { argv[1] }, tokens: empty, tokenizer: empty, prompt: empty, prompt_file: empty, + steps: empty, has_tokens: false, has_tokenizer: false, has_prompt: false, has_prompt_file: false, + has_steps: false, context: empty, has_context: false, requests: empty, has_requests: false, replies: empty, has_replies: false, session: false, chat: false, lines: false, draft: empty, has_draft: false, + }; + let mut i = 2; + while i < argc { + let name = unsafe { argv[i] }; + if same(name, "--chat") { + o.chat = true; + i = i + 1; + } else if same(name, "--session") { + o.session = true; + i = i + 1; + } else if same(name, "--lines") { + o.lines = true; + i = i + 1; + } else { + assert(i + 1 < argc, "give: WEIGHTS --tokens 1,2,3 --steps N, or WEIGHTS --tokenizer FILE (--prompt TEXT | --prompt-file FILE) [--chat] [--lines] --steps N"); + let value = unsafe { argv[i + 1] }; + if same(name, "--tokens") { + o.tokens = value; + o.has_tokens = true; + } else if same(name, "--tokenizer") { + o.tokenizer = value; + o.has_tokenizer = true; + } else if same(name, "--prompt") { + o.prompt = value; + o.has_prompt = true; + } else if same(name, "--prompt-file") { + o.prompt_file = value; + o.has_prompt_file = true; + } else if same(name, "--context") { + o.context = value; + o.has_context = true; + } else if same(name, "--requests") { + o.requests = value; + o.has_requests = true; + } else if same(name, "--replies") { + o.replies = value; + o.has_replies = true; + } else if same(name, "--draft") { + o.draft = value; + o.has_draft = true; + } else { + assert(same(name, "--steps"), "give: WEIGHTS --tokens 1,2,3 --steps N, or WEIGHTS --tokenizer FILE (--prompt TEXT | --prompt-file FILE) [--chat] [--lines] --steps N"); + o.steps = value; + o.has_steps = true; + } + i = i + 2; + } + } + if o.session { + assert(o.has_tokenizer && o.has_context && o.has_requests && o.has_replies && !o.has_tokens && !o.has_prompt && !o.has_prompt_file && !o.has_steps, "give: WEIGHTS --tokenizer FILE --session --context N --requests FILE --replies FILE"); + return o; + } + assert(o.has_steps, "give: WEIGHTS --tokens 1,2,3 --steps N, or WEIGHTS --tokenizer FILE (--prompt TEXT | --prompt-file FILE) [--chat] [--lines] --steps N"); + let one_text = o.has_prompt != o.has_prompt_file; + let no_text = !o.has_prompt && !o.has_prompt_file; + assert((o.has_tokens && no_text) || (o.has_tokenizer && !o.has_tokens && one_text), "give: WEIGHTS --tokens 1,2,3 --steps N, or WEIGHTS --tokenizer FILE (--prompt TEXT | --prompt-file FILE) [--chat] [--lines] --steps N"); + assert(o.has_tokenizer || (!o.chat && !o.lines), "--chat and --lines need --tokenizer"); + return o; +} + +/// The comma-separated numbers of `text`. Asserts that it has only digits and commas, and no empty +/// number. +fn parse_numbers(text : *const i8) -> Vec { + let mut numbers = Vec::new(); + let mut value : i32 = 0; + let mut digits = 0; + let mut empty = false; + let mut i : i64 = 0; + let mut ch = i32::from(unsafe { text[0] }); + while ch != 0 { + if ch == 44 { + empty = empty || digits == 0; + numbers.push(value); + value = 0; + digits = 0; + } else { + assert(ch >= 48 && ch <= 57, "a list of numbers can have only digits and commas"); + value = value * 10 + (ch - 48); + digits = digits + 1; + } + i = i + 1; + ch = i32::from(unsafe { text[i] }); + } + assert(!empty && digits > 0, "an empty number in a comma-separated list"); + numbers.push(value); + return numbers; +} + +/// The number of tokens that text mode runs through the model before it reads them. A read waits +/// for all the work that the GPU was given, and then the GPU has nothing to do until the CPU gives +/// it the next token: about 0.37 ms of a 21.9 ms token on the M4. The input of a token is the +/// argmax of the token before it, in GPU memory, so the GPU can run several tokens without the +/// CPU. Then the GPU waits only once for each AHEAD tokens. Up to AHEAD - 1 tokens after the end +/// of the text are run and thrown away. +const AHEAD : i32 = 8; + +/// The GPU tensor of one token. +struct Slot { + next : Tensor, +} + +/// The token in `t`. Reading it waits for the GPU to finish the work before it. +fn read_token(t : &Tensor) -> i32 { + let h = transfer(t, Memory::CPU_DRAM); + return h[0]; +} + +/// The logit `token` of `logits`. +fn read_logit(logits : &Tensor, token : i32) -> f32 { + let h = transfer(logits, Memory::CPU_DRAM); + return h[token]; +} + +/// Whether the C string `a` is `b`. +fn same(a : *const i8, b : *const i8) -> bool { + return unsafe { strcmp(a, b) } == 0; +} + +/// The token ids of the prompt: the numbers of --tokens, or the tokens of the text. +fn prompt_ids(o : &Options, t : &Tokenizer) -> Vec { + if o.has_tokens { + return parse_numbers(o.tokens); + } + let text = if o.has_prompt { + c_text(o.prompt) + } else { + read_text_file(o.prompt_file) + }; + let full = if o.chat { + chat_text(&text) + } else { + text + }; + let ids = encode(t, full.bytes, full.length); + assert(ids.len() > 0, "the prompt has no tokens"); + return ids; +} + +/// Shows token number `step`, as the loop of `main` does: its text, or a line with its logit. +/// Gives false at the end of the text, where the loop stops. +fn show(t : &Tokenizer, w : &Weights, text_mode : bool, step : i32, token : i32, logit : f32) -> bool { + if text_mode { + if is_special(t, token) || token == w.config.eos_token_id { + return false; + } + write_token(t, token); + } else { + println!("step={} token={} logit={};", step, token, logit); + } + return true; +} + +/// The logit `token` of position j of a round. +fn round_logit(r : &Round, j : i32, token : i32) -> f32 { + let h = transfer(&r.logits, Memory::CPU_DRAM); + return h[j][token]; +} + +/// The loop of `main` with speculative decoding (src/speculate.vx). Each step is a round of the +/// last token and a draft from the context, or a plain step when the draft would not pay: when the +/// longest earlier match of the end of the context is shorter than 6 tokens, or after 2 rounds in a +/// row that accepted nothing, until a longer match than theirs appears. A draft has up to `max` +/// tokens. `first` is the first generated token, from the logits in `s.logits`. Shows the same +/// `steps` tokens as the loop of `main`, and gives the number of tokens after the first. +fn generate_with_drafts(w : &Weights, s : &mut State, t : &Tokenizer, text_mode : bool, prompt : &Vec, first : i32, steps : i32, max : i32, start : &mut Instant) -> i32 { + assert(can_round(w), "--draft needs a model of Q4_0 experts with QK norms, head_dim 128 and a 6-bit lm_head"); + assert(max >= 1 && max < ROUND_MAX, "--draft must be 1 to ROUND_MAX - 1"); + assert(steps >= ROUND_MAX, "--draft needs --steps of at least ROUND_MAX"); + let mut r = new_round(&w.config); + // One run of the round kernels for each n to 8, so that their compile time is not in the time + // of a token: it restarts the clock. Larger rounds use the same kernels. The rounds write rows of + // the KV cache that the steps write again before they read them. + let mut warm = Vec::new(); + for n in 1..9 { + warm.push(first); + run_round(w, s, &mut r, &warm, prompt.len(), n); + } + let _ready = transfer(&r.next, Memory::CPU_DRAM); + *start = Instant::now(); + // The tokens of a run of plain steps: token j is in ring[j]. + let mut ring = Vec::new(); + for j in 0..AHEAD { + ring.push(Slot { + next: transfer(Tensor([1]), Memory::HBM), + }); + } + // The length of the next run of plain steps: 1 after a round, then 2, 4 and up to AHEAD while + // no draft comes up. The GPU runs the tokens of a run before the CPU reads them. Lines mode + // prints the logit of each token, so it reads each one. + let mut run = 1; + let mut context = Vec::new(); + for i in 0..prompt.len() { + context.push(prompt[i]); + } + let mut token = first; + context.push(token); + // The position of `token`, which is not in the KV cache yet. + let mut pos = prompt.len(); + let mut step = 0; + let mut rounds = 0; + let mut drafted = 0; + let mut accepted = 0; + // Rounds in a row that accepted nothing, and the length of the match of the last of them. + let mut misses = 0; + let mut missed_length = 0; + let mut going = show(t, w, text_mode, 0, token, read_logit(&s.logits, token)); + while going && step + 1 < steps { + let room = steps - step - 1; + let m = longest_match(&context); + if misses >= 2 && m.length > missed_length { + misses = 0; + } + let mut k = i32::min(i32::min(draft_length(m.length), max), room - 1); + if misses >= 2 { + k = 0; + } + let draft = tokens_after(&context, m.end, k); + k = draft.len(); + if k == 0 { + // Plain steps, with the kernels of one token each. + let mut n = 1; + if text_mode { + n = i32::min(run, room); + } + let mut h = Tensor([1]); + h[0] = token; + let input = transfer(h, Memory::HBM); + run_layers(w, s, &input, pos); + predict(w, s, &mut ring[0].next); + for j in 1..n { + run_layers(w, s, &ring[j - 1].next, pos + j); + predict(w, s, &mut ring[j].next); + } + let mut j = 0; + while j < n && going { + token = read_token(&ring[j].next); + context.push(token); + step = step + 1; + pos = pos + 1; + let mut logit : f32 = 0.0; + if !text_mode { + logit = read_logit(&s.logits, token); + } + going = show(t, w, text_mode, step, token, logit); + j = j + 1; + } + run = i32::min(run * 2, AHEAD); + } else { + run = 1; + let mut inputs = Vec::new(); + inputs.push(token); + for i in 0..k { + inputs.push(draft[i]); + } + run_round(w, s, &mut r, &inputs, pos, k + 1); + let choice = transfer(&r.next, Memory::CPU_DRAM); + rounds = rounds + 1; + drafted = drafted + k; + // c0 is the next token; each draft token that equals the choice before it adds the next one. + let mut j = 0; + let mut more = true; + while more && going { + token = choice[j]; + context.push(token); + step = step + 1; + let mut logit : f32 = 0.0; + if !text_mode { + logit = round_logit(&r, j, token); + } + going = show(t, w, text_mode, step, token, logit); + more = j < k && draft[j] == token; + if more { + accepted = accepted + 1; + j = j + 1; + } + } + pos = pos + j + 1; + if j == 0 { + misses = misses + 1; + missed_length = m.length; + } else { + misses = 0; + } + } + } + println!("rounds={} drafted={} accepted={};", rounds, drafted, accepted); + return step; +} + +/// `main` for a Qwen3.5 or Qwen3.6 model (weight file v2, arch 1). The prompt runs in chunks +/// (src/prefill35.vx). There are no drafts yet (#89). Prints the same lines \ No newline at end of file diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/vx/ctx512.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/vx/ctx512.txt new file mode 100644 index 0000000..f266cda --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/vx/ctx512.txt @@ -0,0 +1,43 @@ +//===- model.vx - Qwen app --------------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// One token of a Qwen2 or Qwen3 MoE decoder on the GPU, with the kernels of `std::nn`. `State` +// holds every tensor that a token writes, and the KV cache. It is made once, before the first +// token, so the token loop allocates nothing. +import core::convert; +import core::num; +import std::nn; +import std::vec; +import qwen::attention; +import qwen::products; +import qwen::q6; +import qwen::weights; + +/// The keys and the values of every position so far, for one layer: [max_seq, kv_heads, head_dim]. +/// They are f16, half the memory of f32. The kernels compute in f32, and round only what they +/// store here. +struct Cache { + k : Tensor, + v : Tensor, +} + +/// The tensors of a mixture-of-experts layer: the router's score of each expert, the chosen +/// experts and their weights, and the SwiGLU output of each chosen expert, [experts_per_token, +/// moe_intermediate_size]. +struct Experts { + router_logits : Tensor, + ids : Tensor, + weights : Tensor, + mlp : Tensor, +} + +/// The tensors that a token writes, in GPU memory, and one `Cache` for each layer. `cos` and `sin` +/// are [max_seq, head_dim / 2]. +struct State { + max_seq : i32, + x : Tensor, + xn : Tensor, + v : Tensor, +} + +/// The tensors of a mixture-of-experts layer: the router's score of each expert, the chosen +/// experts and their weights, and the SwiGLU output of each chosen expert, [experts_per_token, +/// moe_intermediate_size]. +struct Experts { + router_logits : Tensor, + ids : Tensor, + weights : Tensor, + mlp : Tensor, +} + +/// The tensors that a token writes, in GPU memory, and one `Cache` for each layer. `cos` and `sin` +/// are [max_seq, head_dim / 2]. +struct State { + max_seq : i32, + x : Tensor, + xn : Tensor, + q : Tensor, + k : Tensor, + v : Tensor, + q_turned : Tensor, + attended : Tensor, + attention_parts : Tensor, + vec_parts : Tensor, + mlp : Tensor, + experts : Experts, + logits : Tensor, + cos : Tensor, + sin : Tensor, + caches : Vec, +} + +/// The state for up to `max_seq` positions. The angles of RoPE are computed in f64, as in +/// `reference.py`, and rounded to f32 once. +fn new_state(c : &Config, max_seq : i32) -> State { + assert(max_seq > 0 && max_seq <= c.max_positions, "max_seq must be between 1 and the max_positions of the model"); + let half = c.head_dim / 2; + let mut hcos = Tensor([max_seq, half]); + let mut hsin = Tensor([max_seq, half]); + for p in 0..max_seq { + for i in 0..half { + let angle = f64::from(p) / f64::powf(c.rope_theta, f64::from(2 * i) / f64::from(c.head_dim)); + hcos[p][i] = f64::cos(angle) as f32; + hsin[p][i] = f64::sin(angle) as f32; + } + } + // A dense model uses none of the tensors of the experts, so one value each is enough. + let experts = i32::max(c.num_experts, 1); + let chosen = i32::max(c.experts_per_token, 1); + let moe_inter = i32::max(c.moe_intermediate_size, 1); + // The flash attention of a prompt reads the cache in blocks of 64 positions. + let rows = (max_seq + 63) / 64 * 64; + let mut caches = Vec::new(); + for l in 0..c.num_layers { + caches.push(Cache { + k: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + }); + } + return State { + max_seq: max_seq, + x: transfer(Tensor([c.hidden_size]), Memory::HBM), + xn: transfer(Tensor([c.hidden_size]), Memory::HBM), + q: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + k: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + q_turned: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attended: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attention_parts: transfer(split_attention_scratch(max_seq, c.num_q_heads, c.num_kv_heads, c.head_dim), Memory::HBM), + vec_parts: transfer(vec_attention_scratch(c.num_q_heads), Memory::HBM), + mlp: transfer(Tensor([c.intermediate_size]), Memory::HBM), + experts: Experts { + router_logits: transfer(Tensor([experts]), Memory::HBM), + ids: transfer(Tensor([chosen]), Memory::HBM), + weights: transfer(Tensor([chosen]), Memory::HBM), + mlp: transfer(Tensor([chosen, moe_inter]), Memory::HBM), + }, + logits: transfer(Tensor([c.vocab_size]), Memory::HBM), + cos: transfer(hcos, Memory::HBM), + sin: transfer(hsin, Memory::HBM), + caches: caches, + }; +} + +/// y = m x, with the kernel for the dtype of `m`, which has `rows` x `cols` weights. +fn matvec(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U6 { + matvec_q6(y, &m.codes, &m.high, &m.group_scales, x, rows, cols); + } else if m.dtype == U4 { + nn_matvec_q4(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x. +fn matvec_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_matvec_q4_add(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_add(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec_add(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x, for x of [heads, head_dim]. +fn matvec_heads_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, heads : i32, head_dim : i32) -> void { + if m.dtype == U4 { + matvec_q4_heads_add_blocks(y, &m.codes, &m.group_scales, x, rows, heads, head_dim); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_heads_add(y, &m.codes, &m.scales, x, rows, heads, head_dim); + } else { + nn_matvec_heads_add(y, &m.bf16, x, rows, heads, head_dim); + } + return; +} + +/// The Q, K and V of x: m x + b, split by heads. +fn qkv(q : &mut Tensor, k : &mut Tensor, v : &mut Tensor, m : &WeightMatrix, b : &Tensor, x : &Tensor, c : &Config) -> void { + if m.dtype == U4 { + qkv_q4_blocks(q, k, v, &m.codes, &m.group_scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } else if m.dtype == F8E4M3 { + nn_qkv_fp8(q, k, v, &m.codes, &m.scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } else { + nn_qkv(q, k, v, &m.bf16, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } + return; +} + +/// The SwiGLU of a dense MLP, for the gate rows and then the up rows of `m`. +fn swiglu(out : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_swiglu_q4(out, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_swiglu_fp8(out, &m.codes, &m.scales, x, rows, cols); + } else { + nn_swiglu(out, &m.bf16, x, rows, cols); + } + return; +} + +/// The mixture of experts of a layer: the router chooses experts_per_token experts and their +/// weights, and x gets the sum of their outputs for xn, each times its weight. +fn add_experts(e : &mut Experts, x : &mut Tensor, xn : &Tensor, layer : &Layer, c : &Config) -> void { + let k = c.experts_per_token; + let inter = c.moe_intermediate_size; + nn_matvec(&mut e.router_logits, &layer.router, xn, c.num_experts, c.hidden_size); + nn_top_k(&mut e.ids, &mut e.weights, &e.router_logits, c.num_experts, k); + let gate_up = &layer.gate_up; + let down = &layer.down; + if gate_up.dtype == U4 { + moe_swiglu_q4_blocks(&mut e.mlp, &gate_up.codes, &gate_up.group_scales, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + moe_down_q4_add_blocks(x, &down.codes, &down.group_scales, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + } else { + assert(gate_up.dtype == BF16, "the experts of a mixture-of-experts model must be bf16 or Q4_0"); + nn_moe_swiglu(&mut e.mlp, &gate_up.bf16, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + nn_moe_down_add(x, &down.bf16, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + } + return; +} + +/// Runs the token in `token` at position `pos` through every layer. The hidden state of the +/// token is then in `s.x`, and its keys and values are in the caches. +fn run_layers(w : &Weights, s : &mut State, token : &Tensor, pos : i32) -> void { + let c = &w.config; + let eps = c.rms_norm_eps as f32; + assert(pos >= 0 && pos < s.max_seq, "the position is past the end of the KV cache"); + nn_embed(&mut s.x, &w.embed, token, c.hidden_size); + let mut l = 0; + for cache in s.caches.iter_mut() { + let layer = &w.layers[l]; + nn_rms_norm(&mut s.xn, &s.x, &layer.attn_norm, c.hidden_size, eps); + qkv(&mut s.q, &mut s.k, &mut s.v, &layer.qkv, &layer.qkv_bias, &s.xn, c); + if c.qk_norm { + norm_rope_and_store(&mut s.q_turned, &mut cache.k, &mut cache.v, &s.q, &s.k, &s.v, &layer.q_norm, &layer.k_norm, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.head_dim, eps); + } else { + rope_and_store(&mut s.q_turned, &mut cache.k, &mut cache.v, &s.q, &s.k, &s.v, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } + if c.head_dim == 128 { + vec_attention(&mut s.attended, &mut s.vec_parts, &s.q_turned, &cache.k, &cache.v, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } else { + split_attention(&mut s.attended, &mut s.attention_parts, &s.q_turned, &cache.k, &cache.v, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } + matvec_heads_add(&mut s.x, &layer.attn_out, &s.attended, c.hidden_size, c.num_q_heads, c.head_dim); + nn_rms_norm(&mut s.xn, &s.x, &layer.mlp_norm, c.hidden_size, eps); + if c.num_experts > 0 { + add_experts(&mut s.experts, &mut s.x, &s.xn, layer, c); + } else { + swiglu(&mut s.mlp, &layer.gate_up, &s.xn, c.intermediate_size, c.hidden_size); + matvec_add(&mut s.x, &layer.down, &s.mlp, c.hidden_size, c.intermediate_size); + } + l = l + 1; + } + return; +} + +/// The logits of the token whose hidden state is in `s.x`, and in `next` the index of the largest +/// one. Both stay in GPU memory. +fn predict(w : &Weights, s : &mut State, next : &mut Tensor) -> void { + let c = &w.config; + nn_rms_norm(&mut s.xn, &s.x, &w.final_norm, c.hidden_size, c.rms_norm_eps as f32); + if c.tied_embeddings { + nn_matvec(&mut s.logits, &w.embed, &s.xn, c.vocab_size, c.hidden_size); + } else { + matvec(&mut s.logits, &w.lm_head, &s.xn, c.vocab_size, c.hidden_size); + } + nn_argmax(next, &s.logits, c.vocab_size); + return; +} +//===- attention.vx - Qwen app ----------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// The attention of one generated token, with the positions split among blocks. This is a copy of +// `nn_attention` and its kernels from `std::nn` on Vx main (vx-lang/Vx#3216), with `split_` in place +// of `nn_` in their names. Vx v0.0.4 has the older `nn_attention`, which has one block for each head +// of Q, so its time grows with the number of positions. Remove this file, and call `nn_attention` +// of `std::nn`, when a Vx release has the new one (#4). +// +// `vec_attention`, for head_dim 128, has the design of llama.cpp's flash attention for one token +// (kernel_flash_attn_ext_vec and kernel_flash_attn_ext_vec_reduce), MIT License, Copyright (c) 2023-2026 +// The ggml authors. scripts/mlir_kernels/decode_attention.py writes its kernels: change that script, not +// the MLIR. +import core::num; +import std::nn; + +/// Attention of the token at position `pos` over rows 0 to `pos` of the KV cache, with a softmax +/// of the scores q . k / sqrt(head_dim). `part` is scratch space from `split_attention_scratch`. +/// +/// The blocks of the first kernel split the positions, 32 to a block below position 640 and 64 from +/// there on. A block serves the 8 heads of Q that share a head of K and V, so it reads each row of +/// the cache once for all 8. A second kernel merges the parts of the blocks for each head. +fn split_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_heads % kv_heads == 0, "split_attention: q_heads must be a multiple of kv_heads"); + assert(head_dim % 32 == 0 && head_dim <= 128, "split_attention: head_dim must be a multiple of 32, and at most 128"); + let mut n_pos = 32; + if pos >= 640 { + n_pos = 64; + } + assert(part.extent(0) >= kv_heads * ((q_heads / kv_heads + 7) / 8) && part.extent(1) >= (pos + n_pos) / n_pos && part.extent(2) >= 8 && part.extent(3) >= head_dim + 2, "split_attention: `part` is too small for this position. Make it with split_attention_scratch"); + if n_pos == 32 { + split_attention_parts_32(part, q, k_cache, v_cache, pos, q_heads, kv_heads, head_dim); + } else { + split_attention_parts_64(part, q, k_cache, v_cache, pos, q_heads, kv_heads, head_dim); + } + split_attention_merge(out, part, pos, n_pos, q_heads, kv_heads, head_dim); + return; +} + +/// Attention of the token at position `pos`, as `split_attention`, for head_dim 128, with the kernels of +/// llama.cpp's flash attention for one token. `vec_attention_parts` splits the blocks of 32 positions among +/// `nwg` SIMD groups for each head of Q: 32 of them, or 64 when each of 32 would have more than 2 blocks. +/// (llama.cpp goes on to 4 SIMD groups of 32 a block, but 128 parts are no faster here: their merge costs what +/// they save.) `vec_attention_merge` then merges the parts. `part` is scratch space from +/// `vec_attention_scratch`. +fn vec_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_heads % kv_heads == 0 && head_dim == 128, "vec_attention: q_heads must be a multiple of kv_heads, and head_dim 128"); + assert(part.extent(0) >= q_heads && part.extent(1) >= 128 && part.extent(2) == 132, "vec_attention: `part` is too small. Make it with vec_attention_scratch"); + let mut nwg = 32; + if 2 * nwg * 32 < pos + 1 { + nwg = nwg * 2; + } + vec_attention_parts(part, q, k_cache, v_cache, pos, q_heads, q_heads / kv_heads, nwg, 1.0 / (head_dim as f32).sqrt()); + vec_attention_merge(out, part, nwg, q_heads); + return; +} + +/// The scratch space of `vec_attention`, on the CPU: up to 128 parts for each head of Q, each the sum of V +/// (128 values), the largest score, and the sum of the weights. A part has 132 values, so that each starts +/// at a multiple of 16 bytes. +fn vec_attention_scratch(q_heads : i32) -> Tensor { + return Tensor([q_heads, 128, 132]); +} + +/// The parts of `vec_attention`, as llama.cpp's kernel_flash_attn_ext_vec. Block (h, w) is a SIMD group for +/// query head h. It does the blocks of 32 positions w, w + nwg, w + 2 nwg, ... up to `pos`, and writes +/// part[h][w]. Lane l owns values 4 l to 4 l + 3 of the head, so that the 32 lanes read a row of K or V in +/// one 256-byte load. For each row, the lanes add up their parts of q . k; then each lane keeps the score +/// of one row, and the lanes take the weights of the rows from each other for the sum of V. A part is the +/// sum of V, not divided, then the largest score and the sum of the weights. +fn vec_attention_parts(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, group : i32, nwg : i32, scale : f32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for w in 0..nwg across blocks { + let g = h / group; + let _d = mlir!( threads : 32, inputs : (%part = part : memref, %q = q : memref, %k3 = k_cache : memref, %v3 = v_cache : memref, %pos = pos : i32, %nwg = nwg : i32, %scale = scale : f32, %h = h : i32, %w = w : i32, %g = g : i32), returns : i32, dialects : ["arith", "memref", "scf", "gpu", "vector", "math"], ensures : [reads_only(q), reads_only(k_cache), reads_only(v_cache), writes_only(part[h][w])]) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %c4 = arith.constant 4 : index + %c32 = arith.constant 32 : index + %c128 = arith.constant 128 : index + %c129 = arith.constant 129 : index + %c32i = arith.constant 32 : i32 + %neg = arith.constant -3.0e38 : f32 + %zero = arith.constant 0.0 : f32 + %vz4 = arith.constant dense<0.0> : vector<4xf32> + %l = gpu.thread_id x + %l4 = arith.muli %l, %c4 : index + %hi = arith.index_cast %h : i32 to index + %wi = arith.index_cast %w : i32 to index + %gi = arith.index_cast %g : i32 to index + %posi = arith.index_cast %pos : i32 to index + %nwgi = arith.index_cast %nwg : i32 to index + %g128 = arith.muli %gi, %c128 : index + %kd = arith.addi %g128, %l4 : index + %P = memref.dim %k3, %c0 : memref + %KH = memref.dim %k3, %c1 : memref + %Wd = arith.muli %KH, %c128 : index + %k = memref.reinterpret_cast %k3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to memref> + %v = memref.reinterpret_cast %v3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to memref> + %qv = vector.load %q[%hi, %l4] {alignment = 16} : memref, vector<4xf32> + %scv = vector.broadcast %scale : f32 to vector<4xf32> + %qs = arith.mulf %qv, %scv : vector<4xf32> + %nkv = arith.addi %posi, %c32 : index + %chunks = arith.divui %nkv, %c32 : index + %st:3 = scf.for %ic = %wi to %chunks step %nwgi iter_args(%M = %neg, %S = %zero, %o = %vz4) -> (f32, f32, vector<4xf32>) { + %r0 = arith.muli %ic, %c32 : index + %my = scf.for %cc = %c0 to %c32 step %c1 iter_args(%m = %neg) -> (f32) { + %row = arith.addi %r0, %cc : index + %rowc = arith.minui %row, %posi : index + %kh = vector.load %k[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> + %kf = arith.extf %kh : vector<4xf16> to vector<4xf32> + %pr = arith.mulf %kf, %qs : vector<4xf32> + %pl = vector.reduction , %pr : vector<4xf32> into f32 + %sc = gpu.subgroup_reduce add %pl : (f32) -> f32 + %live = arith.cmpi ule, %row, %posi : index + %scm = arith.select %live, %sc, %neg : f32 + %mine = arith.cmpi eq, %cc, %l : index + %m2 = arith.select %mine, %scm, %m : f32 + scf.yield %m2 : f32 + } + %bm = gpu.subgroup_reduce maxnumf %my : (f32) -> f32 + %Mn = arith.maxnumf %M, %bm : f32 + %dm = arith.subf %M, %Mn : f32 + %ms = math.exp %dm : f32 + %dp = arith.subf %my, %Mn : f32 + %p = math.exp %dp : f32 + %bs = gpu.subgroup_reduce add %p : (f32) -> f32 + %Ss = arith.mulf %S, %ms : f32 + %Sn = arith.addf %Ss, %bs : f32 + %msv = vector.broadcast %ms : f32 to vector<4xf32> + %o1 = arith.mulf %o, %msv : vector<4xf32> + %o2 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%oa = %o1) -> (vector<4xf32>) { + %row = arith.addi %r0, %cc : index + %rowc = arith.minui %row, %posi : index + %vh = vector.load %v[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> + %vf = arith.extf %vh : vector<4xf16> to vector<4xf32> + %cci = arith.index_cast %cc : index to i32 + %pc, %pv = gpu.shuffle idx %p, %cci, %c32i : f32 + %pcv = vector.broadcast %pc : f32 to vector<4xf32> + %on = vector.fma %vf, %pcv, %oa : vector<4xf32> + scf.yield %on : vector<4xf32> + } + scf.yield %Mn, %Sn, %o2 : f32, f32, vector<4xf32> + } + vector.store %st#2, %part[%hi, %wi, %l4] : memref, vector<4xf32> + %lane0 = arith.cmpi eq, %l, %c0 : index + scf.if %lane0 { + memref.store %st#0, %part[%hi, %wi, %c128] : memref + memref.store %st#1, %part[%hi, %wi, %c129] : memref + } + macro.yield %h : i32 + }; + } + } + } + return; +} + +/// Merges the first `parts` parts of `vec_attention_parts` for each head of Q, as llama.cpp's +/// kernel_flash_attn_ext_vec_reduce. A block of 4 SIMD groups does one head: each lane weighs up to 4 parts, +/// and the SIMD groups add them up for 4 values of the head at a time. +fn vec_attention_merge(out : &mut Tensor, part : &Tensor, parts : i32, q_heads : i32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + let _d = mlir!( threads : 128, inputs : (%out = out : memref, %part \ No newline at end of file diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/complete1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/complete1.txt new file mode 100644 index 0000000..12241e6 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/complete1.txt @@ -0,0 +1,102 @@ +<|im_start|>user +`src/hir/flatten/affine.rs`: + +```rust +//===- affine.rs - Vx Compiler --------------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Counted loops that the code generator writes as `affine.for`, so that the affine passes can +// fuse and tile them. docs/discussions/loop_optimizations_in_the_frontend_and_in_mlir.md has the +// rules. +// +//===----------------------------------------------------------------------===// + +use super::*; +use crate::bytecode::AFFINE_FOR_BRANCHES; + +/// Whether the body of a loop can be the body of an `affine.for`: nothing in it leaves the loop, +/// and it holds no region that the MLIR passes lower by splitting its block. +pub(super) fn affine_body(body: &[Statement]) -> bool { + stays_in(body, false) +} + +/// Whether nothing in `stmts` leaves the loop. In a nested loop, `in_loop` is set, and a +/// `break` or `continue` stays in that loop. +fn stays_in(stmts: &[Statement], in_loop: bool) -> bool { + stmts.iter().all(|s| match s { + Statement::Return(_) => false, + Statement::Break(_) | Statement::Continue(_) => in_loop, + Statement::ForLoop(f) => { + exprs_stay_in(std::slice::from_ref(s), in_loop) && stays_in(&f.body, true) + } + Statement::Loop(l) => { + exprs_stay_in(std::slice::from_ref(s), in_loop) && stays_in(&l.body, true) + } + // An unexpanded macro may hold anything. + Statement::MacroCall(_) | Statement::Error(_) => false, + _ => exprs_stay_in(std::slice::from_ref(s), in_loop), + }) +} + +/// Whether the expressions of `stmts`, and the blocks in them, stay in the loop. +fn exprs_stay_in(stmts: &[Statement], in_loop: bool) -> bool { + let mut ok = true; + let mut check = |e: &Expr| { + ok &= match e { + Expr::If(i) => { + stays_in(&i.then_block, in_loop) + && i.else_block.as_ref().is_none_or(|b| stays_in(b, in_loop)) + } + Expr::Match(m) => m.arms.iter().all(|a| stays_in(&a.body, in_loop)), + // The checker makes a `tasks` block and a task body an `UnsafeBlock` with a `task` + // mark, and the lowering of a task splits its block. + Expr::UnsafeBlock(b) => b.task.is_none() && stays_in(&b.stmts, in_loop), + Expr::ComptimeBlock(b) => stays_in(&b.stmts, in_loop), + Expr::SpawnOn(_) + | Expr::TaskBlock(_) + | Expr::InlineMlir(_) + | Expr::Closure(_) + | Expr::MacroCall(_) => false, + _ => true, + } + }; + for s in stmts { + // A nested loop's body is checked by `stays_in`. Only its own expressions are here. + match s { + Statement::ForLoop(f) => { + crate::syntax::visit_expr(&f.iterable, &mut check); + f.invariants + .iter() + .for_each(|e| crate::syntax::visit_expr(e, &mut check)); + } + Statement::Loop(l) => l + .invariants + .iter() + .for_each(|e| crate::syntax::visit_expr(e, &mut check)), + _ => crate::syntax::visit_exprs(std::slice::from_ref(s), &mut check), + } + } + ok +} + +impl Lowerer<'_> { + /// Whether `v` can be a bound of an `affine.for` here: a constant, a value from before the + /// outermost open affine loop, or the variable of an open affine loop. + fn affine_bound(&self, v: &Val) -> bool { + let r = v.reg.0 as usize; + match self.affine_open.first() { + None => true, +``` + +This file stops in the middle. Continue it from exactly where it stops. Output only the rest of the file.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/complete2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/complete2.txt new file mode 100644 index 0000000..1a872a5 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/complete2.txt @@ -0,0 +1,112 @@ +<|im_start|>user +`utils/memalg/shakedown.py`: + +```python +#!/usr/bin/env python3 +"""Predict -> measure -> compare, end to end. + +The dry run. Its output is an error table for one memory link on the machine we already +own, and its purpose is to find bugs in OUR harness -- a wrong formula, a mislabeled column, a +unit mismatch -- before any GPU time is paid for. The MLSys admission matrix was dry-run the same +way and it caught an 8x arithmetic error before any money was spent. + +Three steps, each of which can fail loudly: + + predict generate a Vx program that transfers a tile of each swept size, compile it against the + machine file, and harvest `--diagnostics-json` -> predicted picoseconds per hop. + measure run the C benchmark -> achieved copy time per size. + compare join on byte count, report signed relative error. + +The join is on `bytes`, which is why the extractor had to emit it: without a byte +count in the prediction record there is nothing to join on and the two halves cannot be related at +all. +""" + +import argparse +import csv +import json +import os +import subprocess +import sys +import tempfile + +# The tile shapes swept. Square f32 tiles, so bytes = 4*d*d; chosen so the byte counts line up +# with the measurement's powers of two. +DIMS = [32, 64, 128, 256, 512, 1024, 2048, 4096] + + +def tile_bytes(d): + return 4 * d * d + + +def predict(vxc, machine, workdir): + """Compile one probe program per size and harvest its predicted hop costs. + + One program per size rather than one program with every size: the resident-set check would + reject a program holding every tile at once, and a rejected compile emits no routes. + """ + out = {} + for d in DIMS: + src = os.path.join(workdir, f"probe_{d}.vx") + with open(src, "w") as f: + f.write( + "fn main() -> i32 {\n" + f" let tile : Tensor = Tensor([{d}, {d}]);\n" + " let _h = transfer(tile, Memory::HBM);\n" + " return 0;\n" + "}\n" + ) + js = os.path.join(workdir, f"probe_{d}.json") + proc = subprocess.run( + [vxc, "--machine", machine, src, "--diagnostics-json", js, "--emit-mlir"], + capture_output=True, + text=True, + ) + if not os.path.exists(js): + print(f" !! no diagnostics for {d}x{d}: {proc.stderr.strip()[:200]}", file=sys.stderr) + continue + rec = json.load(open(js)) + for r in rec.get("routes", []): + if r["path"] == ["CPU_DRAM", "HBM"] and r.get("derived_cost") is not None: + if r.get("derived_unit") != "ps": + # A cycle-denominated cost cannot be compared against a wall-clock measurement + # without a declared clock. Refusing beats silently treating cycles as ps. + print( + f" !! {d}x{d}: predicted unit is {r['derived_unit']}, not ps -- " + "cannot compare against wall-clock without a clock figure", + file=sys.stderr, + ) + continue + out[r["bytes"]] = r["derived_cost"] + return out + + +def measure(binary): + proc = subprocess.run([binary], capture_output=True, text=True, check=True) + rows = {} + for row in csv.DictReader(proc.stdout.splitlines()): + rows[int(row["bytes"])] = { + "ns": float(row["median_ns"]), + "q1": float(row["q1_ns"]), + "q3": float(row["q3_ns"]), + "copy_gbps": float(row["copy_GBps"]), + "traffic_gbps": float(row["traffic_GBps"]), + } + return rows + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--vxc", default="target/release/vxc") + ap.add_argument("--machine", default="fleet/m4-uma.vx") + ap.add_argument("--bench", default="utils/memalg/measure_link") + ap.add_argument("--out", default=None, help="write the error table here as CSV") +``` + +This file stops in the middle. Continue it from exactly where it stops. Output only the rest of the file.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/complete3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/complete3.txt new file mode 100644 index 0000000..8ba9deb --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/complete3.txt @@ -0,0 +1,134 @@ +<|im_start|>user +`stdlib/rust_core/src/io.rs`: + +```rust +//===- io.rs - Vx Compiler -------------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file implements the standard library I/O primitives. +// It contains the Rust-side FFI implementations for file system operations, +// console printing, and basic input/output functionality exposed to Vx programs. +// +//===----------------------------------------------------------------------===// +//! FFI bindings for `std::fs::File`. + +use crate::{instantiate_file_ffi, instantiate_stdio_ffi}; + +instantiate_file_ffi!(crate::ffi::io::off_the_worker); +instantiate_stdio_ffi!(); + +/// While a task runs, each thread keeps what it prints until a newline, and then writes the +/// whole line at once. So the lines of tasks that print at the same time do not mix. With no +/// task running, each piece is written at once, as before, so its order with output from C is +/// the order of the calls. +pub(crate) mod lines { + use std::cell::RefCell; + use std::io::Write; + use std::sync::atomic::{AtomicUsize, Ordering}; + + static RUNNING_TASKS: AtomicUsize = AtomicUsize::new(0); + + thread_local! { + static LINE: RefCell> = const { RefCell::new(Vec::new()) }; + /// Set between the two `vx_print_to_stderr` calls around an `eprint!` or a `panic`. + static TO_STDERR: std::cell::Cell = const { std::cell::Cell::new(false) }; + } + + pub(crate) fn set_stderr(on: bool) { + TO_STDERR.with(|flag| flag.set(on)); + } + + /// Swaps the line and the stderr flag of this thread with these. The shared runtime gives + /// each fiber its own, so that the lines of two fibers on one thread do not mix. + pub(crate) fn swap_with_thread(line: &mut Vec, to_stderr: &mut bool) { + LINE.with(|l| std::mem::swap(&mut *l.borrow_mut(), line)); + TO_STDERR.with(|flag| *to_stderr = flag.replace(*to_stderr)); + } + + /// Takes what this thread keeps of its line. + #[cfg(test)] + pub(crate) fn take_line() -> Vec { + LINE.with(|l| std::mem::take(&mut *l.borrow_mut())) + } + + pub(crate) fn task_started() { + RUNNING_TASKS.fetch_add(1, Ordering::SeqCst); + } + + /// At the end of a task on its own thread: writes what is left of its line. + pub(crate) fn task_ended() { + flush(); + RUNNING_TASKS.fetch_sub(1, Ordering::SeqCst); + } + + /// Writes what is left of this thread's line. + pub(crate) fn flush() { + LINE.with(|line| { + let mut line = line.borrow_mut(); + if !line.is_empty() { + let mut out = std::io::stdout().lock(); + let _ = out.write_all(&line); + let _ = out.flush(); + line.clear(); + } + }); + } + + pub(crate) fn print(text: &str) { + // Standard error is not buffered, and a task's line on it is not kept apart. + if TO_STDERR.with(|flag| flag.get()) { + let _ = std::io::stderr().lock().write_all(text.as_bytes()); + return; + } + LINE.with(|line| { + let mut line = line.borrow_mut(); + if RUNNING_TASKS.load(Ordering::SeqCst) == 0 && line.is_empty() { + let mut out = std::io::stdout().lock(); + let _ = out.write_all(text.as_bytes()); + let _ = out.flush(); + return; + } + line.extend_from_slice(text.as_bytes()); + if let Some(end) = line.iter().rposition(|&b| b == b'\n') { + let mut out = std::io::stdout().lock(); + let _ = out.write_all(&line[..=end]); + let _ = out.flush(); + line.drain(..=end); + } + }); + } +} + +#[no_mangle] +pub extern "C" fn print_i32(val: i32) -> i32 { + lines::print(&format!("{}", val)); + 0 +} + +#[no_mangle] +pub extern "C" fn print_i64(val: i64) -> i32 { + lines::print(&format!("{}", val)); + 0 +} + +/// The unsigned counterparts of `print_i32`/`print_i64`. MLIR's integer types are signless, +/// so a Vx `u64` and `i64` reach codegen as the same `i64` and only the element type says +/// which is which; without these every value above the signed range printed as a negative +/// number. One per width, so the element type alone decides the call. +#[no_mangle] +pub extern "C" fn print_u8(val: u8) -> i32 { + lines::print(&format!("{}", val)); +``` + +This file stops in the middle. Continue it from exactly where it stops. Output only the rest of the file.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/edit1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/edit1.txt new file mode 100644 index 0000000..5874050 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/edit1.txt @@ -0,0 +1,128 @@ +<|im_start|>user +`scripts/tools/differential_fuzz/generators/tensors.py`: + +```python +"""Functions that build tensors in nested blocks and return one, often early. + +`g(n, k)` makes tensors of length `n` in nested `if`s and `for` loops, adds to them, and +returns one, possibly from inside a block. `main` calls it for four values of `k` and prints +every element. The Rust twin uses `Vec`. Aimed at the freeing of heap buffers: an early +return from nested blocks is where #993 and #1014 were. + +Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +See LICENSE for license information. +SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +""" + +import random + +from fuzzlib import Program + +class Gen: + def __init__(self, rng): + self.rng = rng + self.count = 0 + + def fresh(self): + self.count += 1 + return f"v{self.count}" + + def val(self, ints): + r = self.rng.random() + if r < 0.3 or not ints: + return str(self.rng.randint(0, 9)) + a = self.rng.choice(ints) + if r < 0.7: + return f"({a} + {self.rng.choice(ints + ['1', '2'])})" + return a + + def body(self, tensors, ints, depth): + out = [] + for _ in range(self.rng.randint(1, 4)): + k = self.rng.random() + if k < 0.25 or not tensors: + t = self.fresh() + out.append(("new", t)) + tensors = tensors + [t] + elif k < 0.5: + out.append(("fill", self.rng.choice(tensors), self.val(ints))) + elif k < 0.65 and depth < 3: + out.append(("if", self.val(ints), self.body(tensors, ints, depth + 1), + self.body(tensors, ints, depth + 1) if self.rng.random() < 0.5 else None)) + elif k < 0.8 and depth < 3: + iv = f"i{depth}" + out.append(("for", iv, self.rng.randint(0, 3), self.body(tensors, ints + [iv], depth + 1))) + elif k < 0.9 and depth > 0: + out.append(("ret", self.val(ints), self.rng.choice(tensors))) + else: + a, b = self.rng.choice(tensors), self.rng.choice(tensors) + out.append(("add", a, b)) + return out + +def render(stmts, lang, ind): + pad = " " * ind + L = [] + for s in stmts: + if s[0] == "new": + if lang == "vx": + L += [f"{pad}let mut {s[1]} = Tensor([n]);", f"{pad}for j in 0..n {{", f"{pad} {s[1]}[j] = 0;", f"{pad}}}"] + else: + L += [f"{pad}let mut {s[1]}: Vec = vec![0; n as usize];"] + elif s[0] == "fill": + idx = "j" if lang == "vx" else "j as usize" + L += [f"{pad}for j in 0..n {{", f"{pad} {s[1]}[{idx}] = {s[1]}[{idx}] + j + {s[2]};", f"{pad}}}"] + elif s[0] == "add": + idx = "j" if lang == "vx" else "j as usize" + L += [f"{pad}for j in 0..n {{", f"{pad} {s[1]}[{idx}] = {s[1]}[{idx}] + {s[2]}[{idx}];", f"{pad}}}"] + elif s[0] == "if": + L.append(f"{pad}if ({s[1]}) % 2 == 0 {{") + L += render(s[2], lang, ind + 1) + if s[3] is not None: + L.append(f"{pad}}} else {{") + L += render(s[3], lang, ind + 1) + L.append(f"{pad}}}") + elif s[0] == "for": + L.append(f"{pad}for {s[1]} in 0..{s[2]} {{") + L += render(s[3], lang, ind + 1) + L.append(f"{pad}}}") + elif s[0] == "ret": + L.append(f"{pad}if ({s[1]}) % 3 == 0 {{") + L.append(f"{pad} return {s[2]};") + L.append(f"{pad}}}") + return L + + +def generate(seed): + rng = random.Random(seed) + g = Gen(rng) + tree = g.body([], ["k"], 0) + last = rng.choice([s[1] for s in tree if s[0] == "new"] or ["NONE"]) + if last == "NONE": + tree.insert(0, ("new", "v0")) + last = "v0" + returned = next(s for s in tree if s[0] == "new" and s[1] == last) + + def source(stmts, lang): + if lang == "vx": + return "\n".join( + ["fn g(n : i32, k : i32) -> Tensor {"] + render(stmts, "vx", 1) + + [f" return {last};", "}", "", "fn main() -> i32 {", " for k in 0..4 {", + " let r = g(3, k);", " for j in 0..3 {", " print(r[j]);", + " print!(\" \");", " }", " }", " return 0;", "}", ""]) + return "\n".join( + ["#![allow(unused, unused_mut, unused_variables, unreachable_code)]", + "fn g(n: i32, k: i32) -> Vec {"] + render(stmts, "rs", 1) + + [f" return {last};", "}", "fn main() {", " let mut s = String::new();", + " for k in 0..4 { let r = g(3, k); for j in 0..3 { s += &format!(\"{} \", r[j]); } }", + " print!(\"{}\", s);", "}", ""]) + + return Program(tree, source, keep=lambda stmt, block: stmt is returned) +``` + +Add a type hint to every function parameter and return value. Output the whole file, and change nothing else.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/edit2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/edit2.txt new file mode 100644 index 0000000..e1dfddf --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/edit2.txt @@ -0,0 +1,132 @@ +<|im_start|>user +`src/hir/check/host_waits.rs`: + +```rust +//===- check submodule - Vx Compiler ----------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// A channel end or a lock stays on the host (M6 in +// docs/discussions/waiting_tasks_channels_and_task_errors.md). A GPU does not promise that a +// block of threads makes progress, so a kernel that waits for the host while the host waits for +// the kernel never ends. A `spawn on` body for a device that names one gets E6038. +// +//===----------------------------------------------------------------------===// + +use super::super::*; + +impl TypeChecker<'_> { + /// Whether code on `top` runs on a device, not on the host. A GPU that shares the memory of + /// the host still runs on the device. + pub(crate) fn runs_on_a_device(&self, top: &Topology) -> bool { + match top { + Topology::CPU + | Topology::CpuAvx512 + | Topology::CpuNeon + | Topology::AMX + | Topology::Current => false, + Topology::GPU(_) | Topology::NPU(_) | Topology::AccCore(_) | Topology::ANE => true, + Topology::Slice(inner, ..) => self.runs_on_a_device(inner), + Topology::Custom(..) => { + self.transfer_cost_graph.default_memory_for(top) + != self.transfer_cost_graph.default_memory_for(&Topology::CPU) + } + } + } + + /// E6038 when the device body being checked names `name`, of type `ty`, and `ty` holds a + /// channel end or a lock. True when it reported the error. + pub(crate) fn report_host_only_on_a_device( + &mut self, + name: &str, + ty: &Type, + span: &Span, + ) -> bool { + let Some(spawn) = self.device_spawn else { + return false; + }; + // A generic function that the body calls is checked with the topology of the host. + if self.speculating || !self.runs_on_a_device(&self.active_topology) { + return false; + } + let Some(why) = self.host_only_part(ty, &mut Vec::new()) else { + return false; + }; + self.unreadable_reported.insert(*span); + self.errors.error_with_code( + crate::diagnostic::DiagnosticCode::E6038, + format!( + "the body of the `spawn on` at line {} runs on {}, and it uses '{name}': {why}. A \ + channel end and a lock stay on the host, because a wait on the device for the \ + host can wait forever. Use '{name}' before the `spawn on`, or after it", + spawn.line, + self.active_topology.display_name() + ), + Some(crate::diagnostic::SourceSpan::from_ast_span(span)), + ); + true + } + + /// The chain of fields from `ty` to a channel end or a lock in it, or `None` when it holds + /// none. + fn host_only_part(&mut self, ty: &Type, visiting: &mut Vec) -> Option { + match ty { + Type::Borrow { inner, .. } + | Type::Ref(inner, _) + | Type::Verified(inner) + | Type::Distinct(inner) + | Type::DisjointRanges(inner) + | Type::Pinned(inner, _) => self.host_only_part(inner, visiting), + Type::Struct(..) | Type::Enum(..) | Type::GenericInstance(..) => { + if self.implements_host_only(ty) { + return Some(format!("'{ty}' can wait for the host")); + } + let (name, args) = match ty { + Type::GenericInstance(base, args) => match base.as_ref() { + Type::Struct(n, _) | Type::Enum(n, _) => (n.clone(), args.clone()), + _ => return None, + }, + Type::Struct(n, _) | Type::Enum(n, _) => (n.clone(), Vec::new()), + _ => return None, + }; + if visiting.contains(ty) { + return None; + } + visiting.push(ty.clone()); + let why = self + .held_types(&name, &args) + .into_iter() + .find_map(|(field, held)| { + self.host_only_part(&held, visiting).map(|inner| { + format!("{field} of '{ty}' has type '{held}', and {inner}") + }) + }); + visiting.pop(); + why + } + _ => None, + } + } + + /// Whether the standard library marks `ty` with `impl HostOnly`, as it does for a channel end + /// and a lock. + fn implements_host_only(&mut self, ty: &Type) -> bool { + let blocks = self.env.impls.get("HostOnly").cloned().unwrap_or_default(); + blocks + .iter() + .any(|ib| self.unify_types(&ib.target_type, ty, &mut std::collections::HashMap::new())) + } +} +``` + +Add a `///` doc comment above every function that has none. Output the whole file, and change nothing else.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/edit3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/edit3.txt new file mode 100644 index 0000000..9ba76fa --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/edit3.txt @@ -0,0 +1,134 @@ +<|im_start|>user +`utils/memalg/measure_link.c`: + +```c +// measure_link.c -- achieved copy bandwidth across a size sweep (the per-seam protocol). +// +// The measurement half of the shakedown. Emits one CSV row per (size, rep-median) so the compare +// step joins it against the compiler's predictions by byte count. +// +// Protocol, mirroring what the M-series will do on rented hardware, so that the *protocol* is what +// gets debugged here rather than on a metered box: +// +// * log-spaced sizes from 4 KiB to 256 MiB, both to catch a latency floor at the small end and +// to get past every cache at the large end; +// * >= 9 reps, median reported with IQR, because a mean over a noisy laptop is not a measurement; +// * a warm-up rep per size, discarded -- the first touch pays page faults, and on a lazily-mapped +// allocation that is a first-touch cost, not a bandwidth; +// * buffers re-touched between reps so the copy is not reading from a cache it just filled; +// * `clock_gettime(CLOCK_MONOTONIC)`, never wall time. +// +// Reports BOTH the copy rate (bytes copied / time) and the traffic rate (2x that, since a memcpy +// reads a byte and writes a byte). Which of the two a declared "memory bandwidth" figure should be +// compared against is exactly the sort of question a dry run is supposed to force into the open -- +// so the harness reports both rather than picking one and hiding the choice. +// +// cc -O2 measure_link.c -o measure_link && ./measure_link > raw.csv +#include +#include +#include +#include + +#ifndef REPS +#define REPS 11 +#endif + +static double now_sec(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (double)ts.tv_sec + (double)ts.tv_nsec * 1e-9; +} + +static int cmp_double(const void *a, const void *b) { + double x = *(const double *)a, y = *(const double *)b; + return (x > y) - (x < y); +} + +int main(void) { + // 4 KiB .. 256 MiB, log-spaced (x2). The small end is where a bandwidth-only model is expected + // to under-predict cost because a latency floor dominates; measuring that crossover IS a result. + size_t sizes[64]; + int n = 0; + for (size_t s = 4096; s <= (256ul << 20); s *= 2) sizes[n++] = s; + + printf("bytes,median_ns,q1_ns,q3_ns,copy_GBps,traffic_GBps,reps\n"); + + for (int i = 0; i < n; ++i) { + size_t bytes = sizes[i]; + char *src = malloc(bytes); + char *dst = malloc(bytes); + if (!src || !dst) { + fprintf(stderr, "alloc failed at %zu bytes\n", bytes); + free(src); free(dst); + continue; + } + // First touch every page so the timed region measures copying, not faulting. + memset(src, 0x5a, bytes); + memset(dst, 0x00, bytes); + + memcpy(dst, src, bytes); // warm-up, discarded + + // How many copies per timed region. `CLOCK_MONOTONIC` on this machine has ~1 us granularity, + // so a single 4 KiB copy times as either 0 or 1000 ns -- which yields an infinite bandwidth + // and, worse, looks like a number. Timing a calibrated batch and dividing is the fix, and + // finding this on the laptop instead of on a rented box is the whole point of the dry run. + // + // The batch is grown until the timed region is >= TARGET_NS, so the clock's granularity is a + // negligible fraction of what is being measured at every size. + const double TARGET_NS = 5e6; // 5 ms + long iters = 1; + for (;;) { + double t0 = now_sec(); + for (long k = 0; k < iters; ++k) memcpy(dst, src, bytes); + double elapsed = (now_sec() - t0) * 1e9; + if (elapsed >= TARGET_NS || iters >= (1L << 30)) break; + // Scale straight to the target rather than doubling, with a floor so a zero reading (the + // very case this loop exists for) still makes progress. + long next = elapsed > 0 ? (long)(iters * TARGET_NS / elapsed) + 1 : iters * 8; + iters = next > iters ? next : iters * 2; + } + + double samples[REPS]; + for (int r = 0; r < REPS; ++r) { + double t0 = now_sec(); + for (long k = 0; k < iters; ++k) memcpy(dst, src, bytes); + double t1 = now_sec(); + samples[r] = (t1 - t0) * 1e9 / (double)iters; // ns per copy + } + // Keep the result observable so the copy cannot be optimised away. + volatile char sink = dst[bytes - 1]; + (void)sink; + + qsort(samples, REPS, sizeof(double), cmp_double); + double med = samples[REPS / 2]; + double q1 = samples[REPS / 4]; + double q3 = samples[(3 * REPS) / 4]; + if (med <= 0.0) { + // Still unmeasurable. Report it as missing rather than as an infinite bandwidth: a row that + // says nothing is recoverable, a row that says `inf` gets averaged into a result. + fprintf(stderr, "%zu bytes: unmeasurable even at %ld iters/rep -- row skipped\n", bytes, + iters); + free(src); + free(dst); + continue; + } + double copy_gbps = (double)bytes / med; // bytes/ns == GB/s + double traffic_gbps = 2.0 * copy_gbps; // a memcpy reads AND writes + + printf("%zu,%.1f,%.1f,%.1f,%.2f,%.2f,%d\n", bytes, med, q1, q3, copy_gbps, traffic_gbps, REPS); + fflush(stdout); + + free(src); + free(dst); + } + return 0; +} +``` + +Add a one-line comment above every function that says what it does. Output the whole file, and change nothing else.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/explain1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/explain1.txt new file mode 100644 index 0000000..273f2a3 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/explain1.txt @@ -0,0 +1,126 @@ +<|im_start|>user +`src/hir/places.rs`: + +```rust +//===- places.rs - Vx Compiler ---------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +//! Shared "place" helpers — one derivation of *which memory an lvalue names* and *whether two paths +//! overlap*, used by both the borrow checker (conflict detection, `expr.rs`) and the flat lowerer +//! (alias-scope disjointness, `flatten.rs`). +//! +//! These facts used to be computed twice -- the checker's `extract_base_and_path` and its three +//! inline overlap loops, and the lowerer's `place_base_path` / `paths_may_alias`. Both were sound +//! but duplicated; this module is the single source both now call. The borrow checker keeps its +//! `Vec` representation (its `BorrowRecord` stores string paths) by adapting +//! `base_and_path` at the boundary; the overlap predicate is generic over the path element, so +//! `Vec` and `Vec` share it without conversion. +use crate::symbol::Symbol; +use crate::syntax::Expr; + +/// The path element for an index: `[3]` for an integer literal, and [`ANY_INDEX`] for anything +/// else, which may be any element. So `q[0]` and `q[1]` are different places, and `q[i]` may be +/// either of them. +pub fn index_element(index: &Expr) -> String { + match index { + Expr::Range(_) => RANGE_INDEX.to_string(), + Expr::Number(n) => match n.value.parse::() { + Ok(k) => format!("[{k}]"), + Err(_) => ANY_INDEX.to_string(), + }, + _ => ANY_INDEX.to_string(), + } +} + +/// The path element of an index whose value is not known: it may name any element. +pub const ANY_INDEX: &str = "[?]"; + +/// The path element of a range index, `q[1..3]`: some rows of `q`. The result keeps its first +/// dimension, so an index after it, `q[1..3][1]`, picks a row of `q` again, not a column. +pub const RANGE_INDEX: &str = "[..]"; + +/// Add `elem` to the end of `path`. An index after a range is a row of the same dimension, so +/// it joins the range into [`ANY_INDEX`], and a range after a range stays a range. +pub fn push_path_element + From>(path: &mut Vec, elem: String) { + if let Some(last) = path.last_mut() { + if last.as_ref() == RANGE_INDEX && elem.starts_with('[') { + if elem != RANGE_INDEX { + *last = T::from(ANY_INDEX.to_string()); + } + return; + } + } + path.push(T::from(elem)); +} + +/// The root local and projection path of an lvalue: `o.x.y` -> `(o, [x, y])`, `q[0].x` -> +/// `(q, [[0], x])`, a bare local -> `(o, [])`. An index is a path element, written by +/// [`index_element`]. `None` for a base with no nameable root (`&5`, a call result). +pub fn base_and_path(e: &Expr) -> Option<(Symbol, Vec)> { + match e { + Expr::Identifier(id) => Some((id.name.clone(), Vec::new())), + Expr::MemberAccess(m) => { + let (root, mut path) = base_and_path(&m.base)?; + path.push(m.member.clone()); + Some((root, path)) + } + Expr::IndexAccess(ix) => { + let (root, mut path) = base_and_path(&ix.base)?; + push_path_element(&mut path, index_element(&ix.index)); + Some((root, path)) + } + _ => None, + } +} + +/// Whether two projection paths under the **same** root may name overlapping memory: true when +/// one is a prefix of the other (`[inner]` vs `[inner, v]`) or they match at every shared level. +/// Distinct fields (`[x]` vs `[y]`) and distinct constant indices (`[[0]]` vs `[[1]]`) are +/// disjoint; [`ANY_INDEX`] matches any element. Generic over the path element so the checker's +/// `[String]` and the lowerer's [`Symbol`] paths share it. Returning `true` for paths that are in +/// fact disjoint is always the safe direction: it withholds a `noalias` or reports a conflict. +pub fn paths_may_alias>(a: &[T], b: &[T]) -> bool { + a.iter().zip(b).all(|(x, y)| { + let (x, y) = (x.as_ref(), y.as_ref()); + x == y || [ANY_INDEX, RANGE_INDEX].contains(&x) || [ANY_INDEX, RANGE_INDEX].contains(&y) + }) +} + +/// How a place reads in a message: `q[0].x`, with a dot before each field and none before an +/// index. A tuple's fields, which the parser names `_0`, `_1`, .., read as the program writes +/// them: `t.0`. +pub fn display_place>(root: &str, path: &[T]) -> String { + let mut out = root.to_string(); + for p in path { + let p = p.as_ref(); + if !p.starts_with('[') { + out.push('.'); + } + match p.strip_prefix('_') { + Some(n) if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => out.push_str(n), + _ => out.push_str(p), + } + } + out +} + +/// A moved place as the checker records it, `p.a` or `t._0`, as it reads in a message. +pub fn display_dotted(place: &str) -> String { + let mut parts = place.split('.'); + let root = parts.next().unwrap_or_default(); + let path: Vec<&str> = parts.collect(); + display_place(root, &path) +} +``` + +Explain what this code does, function by function.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/explain2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/explain2.txt new file mode 100644 index 0000000..4118f9c --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/explain2.txt @@ -0,0 +1,129 @@ +<|im_start|>user +`src/hir/check/drop_waits.rs`: + +```rust +//===- check submodule - Vx Compiler ----------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// A `drop` runs with cancellation off, so a cancel cannot stop a wait in it. A `send` or `recv` +// there waits until the time limit of the `drop` when the other end never acts. W1036 warns +// about such a call, and the fix is `send_for` or `recv_for`, or a call of `within` (F6 and F6a +// in docs/discussions/waiting_tasks_channels_and_task_errors.md). A wait in a closure literal +// written as the body of `within` has the limit of the call, so it gets no warning. A closure in +// a variable gets the warning, because the check cannot see that the variable goes to `within`. `wait_limit` runs before cancellation is off, +// and it should return a time and not wait, so W1036 warns about a wait in it too. +// It is a warning, not an error, because the check does not look into the functions that the +// `drop` calls. +// +//===----------------------------------------------------------------------===// + +use super::super::*; + +impl TypeChecker<'_> { + /// Whether `func` is the `drop` of a `Drop` impl: the `drop` that its receiver type uses. + pub(crate) fn is_drop_impl(&mut self, func: &Function) -> bool { + if !func.name.ends_with("drop") && !func.name.contains("$drop$") { + return false; + } + self.is_drop_impl_method(func, "drop") + } + + /// Whether `func` is the `wait_limit` of a `Drop` impl. + pub(crate) fn is_wait_limit_impl(&mut self, func: &Function) -> bool { + if !func.name.contains("wait_limit") { + return false; + } + self.is_drop_impl_method(func, "wait_limit") + } + + /// Whether `func` is the method `method` of the `Drop` impl of its receiver type. + fn is_drop_impl_method(&mut self, func: &Function, method: &str) -> bool { + let Some((_, receiver)) = func.params.first() else { + return false; + }; + let ty = match receiver { + Type::Borrow { inner, .. } | Type::Ref(inner, _) => inner.as_ref().clone(), + ty => ty.clone(), + }; + self.drops_impl_method(&ty, method) + .is_some_and(|name| name.as_ref() == func.name.as_ref()) + } + + /// W1036 when the `drop` of a `Drop` impl calls `method` on a value of type `base`, and the + /// call is a channel wait with no time limit. + pub(crate) fn warn_wait_in_drop(&mut self, base: &Type, method: &str, span: &Span) { + if !(self.in_drop || self.in_wait_limit) || self.within_depth > 0 || self.speculating { + return; + } + let timed = match method { + "send" => "send_for", + "recv" => "recv_for", + _ => return, + }; + let base = match base { + Type::Borrow { inner, .. } | Type::Ref(inner, _) => inner.as_ref(), + ty => ty, + }; + let name = match base { + Type::Struct(n, _) => n.clone(), + Type::GenericInstance(b, _) => match b.as_ref() { + Type::Struct(n, _) => n.clone(), + _ => return, + }, + _ => return, + }; + // The ends whose `send` or `recv` can wait. The `send` of a oneshot and of a watch + // channel does not wait. + let waits = match (method, name.split('<').next()) { + ("send", Some(end)) => matches!(end, "Sender" | "BroadcastSender"), + (_, Some(end)) => matches!( + end, + "Receiver" + | "OneshotReceiver" + | "BroadcastReceiver" + | "WatchReceiver" + | "WorkReceiver" + ), + _ => false, + }; + if !waits { + return; + } + if self.in_wait_limit { + self.errors.warn( + crate::diagnostic::DiagnosticCode::W1036, + format!( + "'{method}' waits in 'wait_limit'. 'wait_limit' runs before the drop, to say \ + how long its waits can take, so it should return a time and not wait" + ), + Some(crate::diagnostic::SourceSpan::from_ast_span(span)), + ); + return; + } + self.errors.warn( + crate::diagnostic::DiagnosticCode::W1036, + format!( + "'{method}' waits with no time limit of its own in a 'drop'. A drop runs with \ + cancellation off, so if the other end of the channel never acts, this wait \ + holds up the drop until the limit of the drop: its type's 'wait_limit', 10 \ + seconds by default. Use '{timed}' with a time limit, or put the wait in the \ + body of 'within'" + ), + Some(crate::diagnostic::SourceSpan::from_ast_span(span)), + ); + } +} +``` + +Explain what this code does, function by function.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/explain3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/explain3.txt new file mode 100644 index 0000000..70bcbd5 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/explain3.txt @@ -0,0 +1,134 @@ +<|im_start|>user +`src/hir/decl_check/bounds.rs`: + +```rust +//===- decl_check submodule - Vx Compiler -----------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// A bound on a type parameter has to name a trait that exists. +// +//===----------------------------------------------------------------------===// + +use super::super::*; + +impl TypeChecker<'_> { + /// Refuse a bound such as `T : NoSuchTrait` whose trait is not declared (E3042). + /// + /// A bound is otherwise only asked when a call binds the parameter, so a misspelled one + /// on a function nobody calls, or on a struct, was never reported. + pub fn check_bounds_name_a_trait(&mut self) { + // (where the bound is written, the parameter, the trait it names, the place of the owner) + let mut unknown: Vec<(String, String, String, decl::DeclPlace)> = Vec::new(); + let traits = &self.env.traits; + let mut collect = + |owner: &str, generics: &[decl::GenericParam], place: &decl::DeclPlace| { + for param in generics { + if let decl::GenericParam::Type { name, bounds } = param { + for bound in bounds { + // `D : Topology` and `M : Memory` mark a topology and a memory + // parameter. They are keywords, not traits. + if matches!(bound.trait_name.as_ref(), "Topology" | "Memory") { + continue; + } + if !traits.contains_key(&bound.trait_name) { + unknown.push(( + owner.to_string(), + name.to_string(), + bound.trait_name.to_string(), + place.clone(), + )); + } + } + } + } + }; + + for s in self.env.structs.values() { + collect(&format!("struct {}", s.name), &s.generics, &s.place); + } + for e in self.env.enums.values() { + collect(&format!("enum {}", e.name), &e.generics, &e.place); + } + for t in self.env.traits.values() { + collect(&format!("trait {}", t.name), &t.generics, &t.place); + // A method signature has no place of its own, so its trait's is used. + for m in &t.methods { + collect( + &format!("method {}::{}", t.name, m.name), + &m.generics, + &t.place, + ); + } + } + for block in self.env.impls.values().flatten() { + let owner = match &block.trait_name { + Some(t) => format!("impl {} for {}", t, block.target_type), + None => format!("impl {}", block.target_type), + }; + collect(&owner, &block.generics, &block.place); + let impl_params: Vec<&str> = block.generics.iter().map(|g| g.name()).collect(); + // A trait default copied into the impl is reported on the trait. + for m in block + .methods + .iter() + .filter(|m| !block.copied_defaults.contains(&m.name)) + { + // A method is also given its impl's parameters, already reported above. + let own: Vec = m + .generics + .iter() + .filter(|g| !impl_params.contains(&g.name())) + .cloned() + .collect(); + collect( + &format!("method {}::{}", block.target_type, m.name), + &own, + &function_place(m), + ); + } + } + for (f, _) in self.env.generic_functions.values() { + collect(&format!("fn {}", f.name), &f.generics, &function_place(f)); + } + + // The tables are hash maps, and a generic method can be listed under its impl and as a + // function, so sort for a stable order and drop the repeats. + unknown.sort_by(|a, b| (&a.0, &a.1, &a.2).cmp(&(&b.0, &b.1, &b.2))); + unknown.dedup_by(|a, b| (&a.0, &a.1, &a.2) == (&b.0, &b.1, &b.2)); + let outside = self.errors.here(); + for (owner, param, trait_name, place) in unknown { + self.errors.point_at(&place, &outside); + self.errors.error_with_code( + crate::diagnostic::DiagnosticCode::E3042, + format!( + "the bound `{param} : {trait_name}` on `{owner}` names no trait; \ + no trait called '{trait_name}' is declared or imported" + ), + None, + ); + } + self.errors.point_back(outside); + } +} + +/// Where a function is written, as a declaration's place. +fn function_place(f: &decl::Function) -> decl::DeclPlace { + decl::DeclPlace { + file: f.file.clone(), + span: f.span, + } +} +``` + +Explain what this code does, function by function.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/write1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/write1.txt new file mode 100644 index 0000000..9e393b6 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/write1.txt @@ -0,0 +1,8 @@ +<|im_start|>user +Write a Python function merge_intervals(intervals) that merges overlapping closed intervals and returns them sorted. Add pytest tests for it, with empty input and touching intervals.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/write2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/write2.txt new file mode 100644 index 0000000..11f00b9 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/write2.txt @@ -0,0 +1,8 @@ +<|im_start|>user +Write a C function `void reverse_words(char *s)` that reverses the order of the words in a string in place, with single spaces between words. Add a main() that tests it.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/write3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/write3.txt new file mode 100644 index 0000000..2bd5648 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/write3.txt @@ -0,0 +1,8 @@ +<|im_start|>user +Write a Rust struct Trie with new, insert, contains and starts_with for lowercase ASCII words. Add unit tests.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/complete1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/complete1.txt new file mode 100644 index 0000000..9e8250e --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/complete1.txt @@ -0,0 +1,101 @@ +<|im_start|>user +`src/hir/flatten/affine.rs`: + +```rust +//===- affine.rs - Vx Compiler --------------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Counted loops that the code generator writes as `affine.for`, so that the affine passes can +// fuse and tile them. docs/discussions/loop_optimizations_in_the_frontend_and_in_mlir.md has the +// rules. +// +//===----------------------------------------------------------------------===// + +use super::*; +use crate::bytecode::AFFINE_FOR_BRANCHES; + +/// Whether the body of a loop can be the body of an `affine.for`: nothing in it leaves the loop, +/// and it holds no region that the MLIR passes lower by splitting its block. +pub(super) fn affine_body(body: &[Statement]) -> bool { + stays_in(body, false) +} + +/// Whether nothing in `stmts` leaves the loop. In a nested loop, `in_loop` is set, and a +/// `break` or `continue` stays in that loop. +fn stays_in(stmts: &[Statement], in_loop: bool) -> bool { + stmts.iter().all(|s| match s { + Statement::Return(_) => false, + Statement::Break(_) | Statement::Continue(_) => in_loop, + Statement::ForLoop(f) => { + exprs_stay_in(std::slice::from_ref(s), in_loop) && stays_in(&f.body, true) + } + Statement::Loop(l) => { + exprs_stay_in(std::slice::from_ref(s), in_loop) && stays_in(&l.body, true) + } + // An unexpanded macro may hold anything. + Statement::MacroCall(_) | Statement::Error(_) => false, + _ => exprs_stay_in(std::slice::from_ref(s), in_loop), + }) +} + +/// Whether the expressions of `stmts`, and the blocks in them, stay in the loop. +fn exprs_stay_in(stmts: &[Statement], in_loop: bool) -> bool { + let mut ok = true; + let mut check = |e: &Expr| { + ok &= match e { + Expr::If(i) => { + stays_in(&i.then_block, in_loop) + && i.else_block.as_ref().is_none_or(|b| stays_in(b, in_loop)) + } + Expr::Match(m) => m.arms.iter().all(|a| stays_in(&a.body, in_loop)), + // The checker makes a `tasks` block and a task body an `UnsafeBlock` with a `task` + // mark, and the lowering of a task splits its block. + Expr::UnsafeBlock(b) => b.task.is_none() && stays_in(&b.stmts, in_loop), + Expr::ComptimeBlock(b) => stays_in(&b.stmts, in_loop), + Expr::SpawnOn(_) + | Expr::TaskBlock(_) + | Expr::InlineMlir(_) + | Expr::Closure(_) + | Expr::MacroCall(_) => false, + _ => true, + } + }; + for s in stmts { + // A nested loop's body is checked by `stays_in`. Only its own expressions are here. + match s { + Statement::ForLoop(f) => { + crate::syntax::visit_expr(&f.iterable, &mut check); + f.invariants + .iter() + .for_each(|e| crate::syntax::visit_expr(e, &mut check)); + } + Statement::Loop(l) => l + .invariants + .iter() + .for_each(|e| crate::syntax::visit_expr(e, &mut check)), + _ => crate::syntax::visit_exprs(std::slice::from_ref(s), &mut check), + } + } + ok +} + +impl Lowerer<'_> { + /// Whether `v` can be a bound of an `affine.for` here: a constant, a value from before the + /// outermost open affine loop, or the variable of an open affine loop. + fn affine_bound(&self, v: &Val) -> bool { + let r = v.reg.0 as usize; + match self.affine_open.first() { + None => true, +``` + +This file stops in the middle. Continue it from exactly where it stops. Output only the rest of the file.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/complete2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/complete2.txt new file mode 100644 index 0000000..d8f89e1 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/complete2.txt @@ -0,0 +1,111 @@ +<|im_start|>user +`utils/memalg/shakedown.py`: + +```python +#!/usr/bin/env python3 +"""Predict -> measure -> compare, end to end. + +The dry run. Its output is an error table for one memory link on the machine we already +own, and its purpose is to find bugs in OUR harness -- a wrong formula, a mislabeled column, a +unit mismatch -- before any GPU time is paid for. The MLSys admission matrix was dry-run the same +way and it caught an 8x arithmetic error before any money was spent. + +Three steps, each of which can fail loudly: + + predict generate a Vx program that transfers a tile of each swept size, compile it against the + machine file, and harvest `--diagnostics-json` -> predicted picoseconds per hop. + measure run the C benchmark -> achieved copy time per size. + compare join on byte count, report signed relative error. + +The join is on `bytes`, which is why the extractor had to emit it: without a byte +count in the prediction record there is nothing to join on and the two halves cannot be related at +all. +""" + +import argparse +import csv +import json +import os +import subprocess +import sys +import tempfile + +# The tile shapes swept. Square f32 tiles, so bytes = 4*d*d; chosen so the byte counts line up +# with the measurement's powers of two. +DIMS = [32, 64, 128, 256, 512, 1024, 2048, 4096] + + +def tile_bytes(d): + return 4 * d * d + + +def predict(vxc, machine, workdir): + """Compile one probe program per size and harvest its predicted hop costs. + + One program per size rather than one program with every size: the resident-set check would + reject a program holding every tile at once, and a rejected compile emits no routes. + """ + out = {} + for d in DIMS: + src = os.path.join(workdir, f"probe_{d}.vx") + with open(src, "w") as f: + f.write( + "fn main() -> i32 {\n" + f" let tile : Tensor = Tensor([{d}, {d}]);\n" + " let _h = transfer(tile, Memory::HBM);\n" + " return 0;\n" + "}\n" + ) + js = os.path.join(workdir, f"probe_{d}.json") + proc = subprocess.run( + [vxc, "--machine", machine, src, "--diagnostics-json", js, "--emit-mlir"], + capture_output=True, + text=True, + ) + if not os.path.exists(js): + print(f" !! no diagnostics for {d}x{d}: {proc.stderr.strip()[:200]}", file=sys.stderr) + continue + rec = json.load(open(js)) + for r in rec.get("routes", []): + if r["path"] == ["CPU_DRAM", "HBM"] and r.get("derived_cost") is not None: + if r.get("derived_unit") != "ps": + # A cycle-denominated cost cannot be compared against a wall-clock measurement + # without a declared clock. Refusing beats silently treating cycles as ps. + print( + f" !! {d}x{d}: predicted unit is {r['derived_unit']}, not ps -- " + "cannot compare against wall-clock without a clock figure", + file=sys.stderr, + ) + continue + out[r["bytes"]] = r["derived_cost"] + return out + + +def measure(binary): + proc = subprocess.run([binary], capture_output=True, text=True, check=True) + rows = {} + for row in csv.DictReader(proc.stdout.splitlines()): + rows[int(row["bytes"])] = { + "ns": float(row["median_ns"]), + "q1": float(row["q1_ns"]), + "q3": float(row["q3_ns"]), + "copy_gbps": float(row["copy_GBps"]), + "traffic_gbps": float(row["traffic_GBps"]), + } + return rows + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--vxc", default="target/release/vxc") + ap.add_argument("--machine", default="fleet/m4-uma.vx") + ap.add_argument("--bench", default="utils/memalg/measure_link") + ap.add_argument("--out", default=None, help="write the error table here as CSV") +``` + +This file stops in the middle. Continue it from exactly where it stops. Output only the rest of the file.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/complete3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/complete3.txt new file mode 100644 index 0000000..8dac3a8 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/complete3.txt @@ -0,0 +1,133 @@ +<|im_start|>user +`stdlib/rust_core/src/io.rs`: + +```rust +//===- io.rs - Vx Compiler -------------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file implements the standard library I/O primitives. +// It contains the Rust-side FFI implementations for file system operations, +// console printing, and basic input/output functionality exposed to Vx programs. +// +//===----------------------------------------------------------------------===// +//! FFI bindings for `std::fs::File`. + +use crate::{instantiate_file_ffi, instantiate_stdio_ffi}; + +instantiate_file_ffi!(crate::ffi::io::off_the_worker); +instantiate_stdio_ffi!(); + +/// While a task runs, each thread keeps what it prints until a newline, and then writes the +/// whole line at once. So the lines of tasks that print at the same time do not mix. With no +/// task running, each piece is written at once, as before, so its order with output from C is +/// the order of the calls. +pub(crate) mod lines { + use std::cell::RefCell; + use std::io::Write; + use std::sync::atomic::{AtomicUsize, Ordering}; + + static RUNNING_TASKS: AtomicUsize = AtomicUsize::new(0); + + thread_local! { + static LINE: RefCell> = const { RefCell::new(Vec::new()) }; + /// Set between the two `vx_print_to_stderr` calls around an `eprint!` or a `panic`. + static TO_STDERR: std::cell::Cell = const { std::cell::Cell::new(false) }; + } + + pub(crate) fn set_stderr(on: bool) { + TO_STDERR.with(|flag| flag.set(on)); + } + + /// Swaps the line and the stderr flag of this thread with these. The shared runtime gives + /// each fiber its own, so that the lines of two fibers on one thread do not mix. + pub(crate) fn swap_with_thread(line: &mut Vec, to_stderr: &mut bool) { + LINE.with(|l| std::mem::swap(&mut *l.borrow_mut(), line)); + TO_STDERR.with(|flag| *to_stderr = flag.replace(*to_stderr)); + } + + /// Takes what this thread keeps of its line. + #[cfg(test)] + pub(crate) fn take_line() -> Vec { + LINE.with(|l| std::mem::take(&mut *l.borrow_mut())) + } + + pub(crate) fn task_started() { + RUNNING_TASKS.fetch_add(1, Ordering::SeqCst); + } + + /// At the end of a task on its own thread: writes what is left of its line. + pub(crate) fn task_ended() { + flush(); + RUNNING_TASKS.fetch_sub(1, Ordering::SeqCst); + } + + /// Writes what is left of this thread's line. + pub(crate) fn flush() { + LINE.with(|line| { + let mut line = line.borrow_mut(); + if !line.is_empty() { + let mut out = std::io::stdout().lock(); + let _ = out.write_all(&line); + let _ = out.flush(); + line.clear(); + } + }); + } + + pub(crate) fn print(text: &str) { + // Standard error is not buffered, and a task's line on it is not kept apart. + if TO_STDERR.with(|flag| flag.get()) { + let _ = std::io::stderr().lock().write_all(text.as_bytes()); + return; + } + LINE.with(|line| { + let mut line = line.borrow_mut(); + if RUNNING_TASKS.load(Ordering::SeqCst) == 0 && line.is_empty() { + let mut out = std::io::stdout().lock(); + let _ = out.write_all(text.as_bytes()); + let _ = out.flush(); + return; + } + line.extend_from_slice(text.as_bytes()); + if let Some(end) = line.iter().rposition(|&b| b == b'\n') { + let mut out = std::io::stdout().lock(); + let _ = out.write_all(&line[..=end]); + let _ = out.flush(); + line.drain(..=end); + } + }); + } +} + +#[no_mangle] +pub extern "C" fn print_i32(val: i32) -> i32 { + lines::print(&format!("{}", val)); + 0 +} + +#[no_mangle] +pub extern "C" fn print_i64(val: i64) -> i32 { + lines::print(&format!("{}", val)); + 0 +} + +/// The unsigned counterparts of `print_i32`/`print_i64`. MLIR's integer types are signless, +/// so a Vx `u64` and `i64` reach codegen as the same `i64` and only the element type says +/// which is which; without these every value above the signed range printed as a negative +/// number. One per width, so the element type alone decides the call. +#[no_mangle] +pub extern "C" fn print_u8(val: u8) -> i32 { + lines::print(&format!("{}", val)); +``` + +This file stops in the middle. Continue it from exactly where it stops. Output only the rest of the file.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/edit1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/edit1.txt new file mode 100644 index 0000000..0ac411a --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/edit1.txt @@ -0,0 +1,127 @@ +<|im_start|>user +`scripts/tools/differential_fuzz/generators/tensors.py`: + +```python +"""Functions that build tensors in nested blocks and return one, often early. + +`g(n, k)` makes tensors of length `n` in nested `if`s and `for` loops, adds to them, and +returns one, possibly from inside a block. `main` calls it for four values of `k` and prints +every element. The Rust twin uses `Vec`. Aimed at the freeing of heap buffers: an early +return from nested blocks is where #993 and #1014 were. + +Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +See LICENSE for license information. +SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +""" + +import random + +from fuzzlib import Program + +class Gen: + def __init__(self, rng): + self.rng = rng + self.count = 0 + + def fresh(self): + self.count += 1 + return f"v{self.count}" + + def val(self, ints): + r = self.rng.random() + if r < 0.3 or not ints: + return str(self.rng.randint(0, 9)) + a = self.rng.choice(ints) + if r < 0.7: + return f"({a} + {self.rng.choice(ints + ['1', '2'])})" + return a + + def body(self, tensors, ints, depth): + out = [] + for _ in range(self.rng.randint(1, 4)): + k = self.rng.random() + if k < 0.25 or not tensors: + t = self.fresh() + out.append(("new", t)) + tensors = tensors + [t] + elif k < 0.5: + out.append(("fill", self.rng.choice(tensors), self.val(ints))) + elif k < 0.65 and depth < 3: + out.append(("if", self.val(ints), self.body(tensors, ints, depth + 1), + self.body(tensors, ints, depth + 1) if self.rng.random() < 0.5 else None)) + elif k < 0.8 and depth < 3: + iv = f"i{depth}" + out.append(("for", iv, self.rng.randint(0, 3), self.body(tensors, ints + [iv], depth + 1))) + elif k < 0.9 and depth > 0: + out.append(("ret", self.val(ints), self.rng.choice(tensors))) + else: + a, b = self.rng.choice(tensors), self.rng.choice(tensors) + out.append(("add", a, b)) + return out + +def render(stmts, lang, ind): + pad = " " * ind + L = [] + for s in stmts: + if s[0] == "new": + if lang == "vx": + L += [f"{pad}let mut {s[1]} = Tensor([n]);", f"{pad}for j in 0..n {{", f"{pad} {s[1]}[j] = 0;", f"{pad}}}"] + else: + L += [f"{pad}let mut {s[1]}: Vec = vec![0; n as usize];"] + elif s[0] == "fill": + idx = "j" if lang == "vx" else "j as usize" + L += [f"{pad}for j in 0..n {{", f"{pad} {s[1]}[{idx}] = {s[1]}[{idx}] + j + {s[2]};", f"{pad}}}"] + elif s[0] == "add": + idx = "j" if lang == "vx" else "j as usize" + L += [f"{pad}for j in 0..n {{", f"{pad} {s[1]}[{idx}] = {s[1]}[{idx}] + {s[2]}[{idx}];", f"{pad}}}"] + elif s[0] == "if": + L.append(f"{pad}if ({s[1]}) % 2 == 0 {{") + L += render(s[2], lang, ind + 1) + if s[3] is not None: + L.append(f"{pad}}} else {{") + L += render(s[3], lang, ind + 1) + L.append(f"{pad}}}") + elif s[0] == "for": + L.append(f"{pad}for {s[1]} in 0..{s[2]} {{") + L += render(s[3], lang, ind + 1) + L.append(f"{pad}}}") + elif s[0] == "ret": + L.append(f"{pad}if ({s[1]}) % 3 == 0 {{") + L.append(f"{pad} return {s[2]};") + L.append(f"{pad}}}") + return L + + +def generate(seed): + rng = random.Random(seed) + g = Gen(rng) + tree = g.body([], ["k"], 0) + last = rng.choice([s[1] for s in tree if s[0] == "new"] or ["NONE"]) + if last == "NONE": + tree.insert(0, ("new", "v0")) + last = "v0" + returned = next(s for s in tree if s[0] == "new" and s[1] == last) + + def source(stmts, lang): + if lang == "vx": + return "\n".join( + ["fn g(n : i32, k : i32) -> Tensor {"] + render(stmts, "vx", 1) + + [f" return {last};", "}", "", "fn main() -> i32 {", " for k in 0..4 {", + " let r = g(3, k);", " for j in 0..3 {", " print(r[j]);", + " print!(\" \");", " }", " }", " return 0;", "}", ""]) + return "\n".join( + ["#![allow(unused, unused_mut, unused_variables, unreachable_code)]", + "fn g(n: i32, k: i32) -> Vec {"] + render(stmts, "rs", 1) + + [f" return {last};", "}", "fn main() {", " let mut s = String::new();", + " for k in 0..4 { let r = g(3, k); for j in 0..3 { s += &format!(\"{} \", r[j]); } }", + " print!(\"{}\", s);", "}", ""]) + + return Program(tree, source, keep=lambda stmt, block: stmt is returned) +``` + +Add a type hint to every function parameter and return value. Output the whole file, and change nothing else.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/edit2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/edit2.txt new file mode 100644 index 0000000..022308f --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/edit2.txt @@ -0,0 +1,131 @@ +<|im_start|>user +`src/hir/check/host_waits.rs`: + +```rust +//===- check submodule - Vx Compiler ----------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// A channel end or a lock stays on the host (M6 in +// docs/discussions/waiting_tasks_channels_and_task_errors.md). A GPU does not promise that a +// block of threads makes progress, so a kernel that waits for the host while the host waits for +// the kernel never ends. A `spawn on` body for a device that names one gets E6038. +// +//===----------------------------------------------------------------------===// + +use super::super::*; + +impl TypeChecker<'_> { + /// Whether code on `top` runs on a device, not on the host. A GPU that shares the memory of + /// the host still runs on the device. + pub(crate) fn runs_on_a_device(&self, top: &Topology) -> bool { + match top { + Topology::CPU + | Topology::CpuAvx512 + | Topology::CpuNeon + | Topology::AMX + | Topology::Current => false, + Topology::GPU(_) | Topology::NPU(_) | Topology::AccCore(_) | Topology::ANE => true, + Topology::Slice(inner, ..) => self.runs_on_a_device(inner), + Topology::Custom(..) => { + self.transfer_cost_graph.default_memory_for(top) + != self.transfer_cost_graph.default_memory_for(&Topology::CPU) + } + } + } + + /// E6038 when the device body being checked names `name`, of type `ty`, and `ty` holds a + /// channel end or a lock. True when it reported the error. + pub(crate) fn report_host_only_on_a_device( + &mut self, + name: &str, + ty: &Type, + span: &Span, + ) -> bool { + let Some(spawn) = self.device_spawn else { + return false; + }; + // A generic function that the body calls is checked with the topology of the host. + if self.speculating || !self.runs_on_a_device(&self.active_topology) { + return false; + } + let Some(why) = self.host_only_part(ty, &mut Vec::new()) else { + return false; + }; + self.unreadable_reported.insert(*span); + self.errors.error_with_code( + crate::diagnostic::DiagnosticCode::E6038, + format!( + "the body of the `spawn on` at line {} runs on {}, and it uses '{name}': {why}. A \ + channel end and a lock stay on the host, because a wait on the device for the \ + host can wait forever. Use '{name}' before the `spawn on`, or after it", + spawn.line, + self.active_topology.display_name() + ), + Some(crate::diagnostic::SourceSpan::from_ast_span(span)), + ); + true + } + + /// The chain of fields from `ty` to a channel end or a lock in it, or `None` when it holds + /// none. + fn host_only_part(&mut self, ty: &Type, visiting: &mut Vec) -> Option { + match ty { + Type::Borrow { inner, .. } + | Type::Ref(inner, _) + | Type::Verified(inner) + | Type::Distinct(inner) + | Type::DisjointRanges(inner) + | Type::Pinned(inner, _) => self.host_only_part(inner, visiting), + Type::Struct(..) | Type::Enum(..) | Type::GenericInstance(..) => { + if self.implements_host_only(ty) { + return Some(format!("'{ty}' can wait for the host")); + } + let (name, args) = match ty { + Type::GenericInstance(base, args) => match base.as_ref() { + Type::Struct(n, _) | Type::Enum(n, _) => (n.clone(), args.clone()), + _ => return None, + }, + Type::Struct(n, _) | Type::Enum(n, _) => (n.clone(), Vec::new()), + _ => return None, + }; + if visiting.contains(ty) { + return None; + } + visiting.push(ty.clone()); + let why = self + .held_types(&name, &args) + .into_iter() + .find_map(|(field, held)| { + self.host_only_part(&held, visiting).map(|inner| { + format!("{field} of '{ty}' has type '{held}', and {inner}") + }) + }); + visiting.pop(); + why + } + _ => None, + } + } + + /// Whether the standard library marks `ty` with `impl HostOnly`, as it does for a channel end + /// and a lock. + fn implements_host_only(&mut self, ty: &Type) -> bool { + let blocks = self.env.impls.get("HostOnly").cloned().unwrap_or_default(); + blocks + .iter() + .any(|ib| self.unify_types(&ib.target_type, ty, &mut std::collections::HashMap::new())) + } +} +``` + +Add a `///` doc comment above every function that has none. Output the whole file, and change nothing else.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/edit3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/edit3.txt new file mode 100644 index 0000000..032730c --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/edit3.txt @@ -0,0 +1,133 @@ +<|im_start|>user +`utils/memalg/measure_link.c`: + +```c +// measure_link.c -- achieved copy bandwidth across a size sweep (the per-seam protocol). +// +// The measurement half of the shakedown. Emits one CSV row per (size, rep-median) so the compare +// step joins it against the compiler's predictions by byte count. +// +// Protocol, mirroring what the M-series will do on rented hardware, so that the *protocol* is what +// gets debugged here rather than on a metered box: +// +// * log-spaced sizes from 4 KiB to 256 MiB, both to catch a latency floor at the small end and +// to get past every cache at the large end; +// * >= 9 reps, median reported with IQR, because a mean over a noisy laptop is not a measurement; +// * a warm-up rep per size, discarded -- the first touch pays page faults, and on a lazily-mapped +// allocation that is a first-touch cost, not a bandwidth; +// * buffers re-touched between reps so the copy is not reading from a cache it just filled; +// * `clock_gettime(CLOCK_MONOTONIC)`, never wall time. +// +// Reports BOTH the copy rate (bytes copied / time) and the traffic rate (2x that, since a memcpy +// reads a byte and writes a byte). Which of the two a declared "memory bandwidth" figure should be +// compared against is exactly the sort of question a dry run is supposed to force into the open -- +// so the harness reports both rather than picking one and hiding the choice. +// +// cc -O2 measure_link.c -o measure_link && ./measure_link > raw.csv +#include +#include +#include +#include + +#ifndef REPS +#define REPS 11 +#endif + +static double now_sec(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (double)ts.tv_sec + (double)ts.tv_nsec * 1e-9; +} + +static int cmp_double(const void *a, const void *b) { + double x = *(const double *)a, y = *(const double *)b; + return (x > y) - (x < y); +} + +int main(void) { + // 4 KiB .. 256 MiB, log-spaced (x2). The small end is where a bandwidth-only model is expected + // to under-predict cost because a latency floor dominates; measuring that crossover IS a result. + size_t sizes[64]; + int n = 0; + for (size_t s = 4096; s <= (256ul << 20); s *= 2) sizes[n++] = s; + + printf("bytes,median_ns,q1_ns,q3_ns,copy_GBps,traffic_GBps,reps\n"); + + for (int i = 0; i < n; ++i) { + size_t bytes = sizes[i]; + char *src = malloc(bytes); + char *dst = malloc(bytes); + if (!src || !dst) { + fprintf(stderr, "alloc failed at %zu bytes\n", bytes); + free(src); free(dst); + continue; + } + // First touch every page so the timed region measures copying, not faulting. + memset(src, 0x5a, bytes); + memset(dst, 0x00, bytes); + + memcpy(dst, src, bytes); // warm-up, discarded + + // How many copies per timed region. `CLOCK_MONOTONIC` on this machine has ~1 us granularity, + // so a single 4 KiB copy times as either 0 or 1000 ns -- which yields an infinite bandwidth + // and, worse, looks like a number. Timing a calibrated batch and dividing is the fix, and + // finding this on the laptop instead of on a rented box is the whole point of the dry run. + // + // The batch is grown until the timed region is >= TARGET_NS, so the clock's granularity is a + // negligible fraction of what is being measured at every size. + const double TARGET_NS = 5e6; // 5 ms + long iters = 1; + for (;;) { + double t0 = now_sec(); + for (long k = 0; k < iters; ++k) memcpy(dst, src, bytes); + double elapsed = (now_sec() - t0) * 1e9; + if (elapsed >= TARGET_NS || iters >= (1L << 30)) break; + // Scale straight to the target rather than doubling, with a floor so a zero reading (the + // very case this loop exists for) still makes progress. + long next = elapsed > 0 ? (long)(iters * TARGET_NS / elapsed) + 1 : iters * 8; + iters = next > iters ? next : iters * 2; + } + + double samples[REPS]; + for (int r = 0; r < REPS; ++r) { + double t0 = now_sec(); + for (long k = 0; k < iters; ++k) memcpy(dst, src, bytes); + double t1 = now_sec(); + samples[r] = (t1 - t0) * 1e9 / (double)iters; // ns per copy + } + // Keep the result observable so the copy cannot be optimised away. + volatile char sink = dst[bytes - 1]; + (void)sink; + + qsort(samples, REPS, sizeof(double), cmp_double); + double med = samples[REPS / 2]; + double q1 = samples[REPS / 4]; + double q3 = samples[(3 * REPS) / 4]; + if (med <= 0.0) { + // Still unmeasurable. Report it as missing rather than as an infinite bandwidth: a row that + // says nothing is recoverable, a row that says `inf` gets averaged into a result. + fprintf(stderr, "%zu bytes: unmeasurable even at %ld iters/rep -- row skipped\n", bytes, + iters); + free(src); + free(dst); + continue; + } + double copy_gbps = (double)bytes / med; // bytes/ns == GB/s + double traffic_gbps = 2.0 * copy_gbps; // a memcpy reads AND writes + + printf("%zu,%.1f,%.1f,%.1f,%.2f,%.2f,%d\n", bytes, med, q1, q3, copy_gbps, traffic_gbps, REPS); + fflush(stdout); + + free(src); + free(dst); + } + return 0; +} +``` + +Add a one-line comment above every function that says what it does. Output the whole file, and change nothing else.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/explain1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/explain1.txt new file mode 100644 index 0000000..86e53dd --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/explain1.txt @@ -0,0 +1,125 @@ +<|im_start|>user +`src/hir/places.rs`: + +```rust +//===- places.rs - Vx Compiler ---------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +//! Shared "place" helpers — one derivation of *which memory an lvalue names* and *whether two paths +//! overlap*, used by both the borrow checker (conflict detection, `expr.rs`) and the flat lowerer +//! (alias-scope disjointness, `flatten.rs`). +//! +//! These facts used to be computed twice -- the checker's `extract_base_and_path` and its three +//! inline overlap loops, and the lowerer's `place_base_path` / `paths_may_alias`. Both were sound +//! but duplicated; this module is the single source both now call. The borrow checker keeps its +//! `Vec` representation (its `BorrowRecord` stores string paths) by adapting +//! `base_and_path` at the boundary; the overlap predicate is generic over the path element, so +//! `Vec` and `Vec` share it without conversion. +use crate::symbol::Symbol; +use crate::syntax::Expr; + +/// The path element for an index: `[3]` for an integer literal, and [`ANY_INDEX`] for anything +/// else, which may be any element. So `q[0]` and `q[1]` are different places, and `q[i]` may be +/// either of them. +pub fn index_element(index: &Expr) -> String { + match index { + Expr::Range(_) => RANGE_INDEX.to_string(), + Expr::Number(n) => match n.value.parse::() { + Ok(k) => format!("[{k}]"), + Err(_) => ANY_INDEX.to_string(), + }, + _ => ANY_INDEX.to_string(), + } +} + +/// The path element of an index whose value is not known: it may name any element. +pub const ANY_INDEX: &str = "[?]"; + +/// The path element of a range index, `q[1..3]`: some rows of `q`. The result keeps its first +/// dimension, so an index after it, `q[1..3][1]`, picks a row of `q` again, not a column. +pub const RANGE_INDEX: &str = "[..]"; + +/// Add `elem` to the end of `path`. An index after a range is a row of the same dimension, so +/// it joins the range into [`ANY_INDEX`], and a range after a range stays a range. +pub fn push_path_element + From>(path: &mut Vec, elem: String) { + if let Some(last) = path.last_mut() { + if last.as_ref() == RANGE_INDEX && elem.starts_with('[') { + if elem != RANGE_INDEX { + *last = T::from(ANY_INDEX.to_string()); + } + return; + } + } + path.push(T::from(elem)); +} + +/// The root local and projection path of an lvalue: `o.x.y` -> `(o, [x, y])`, `q[0].x` -> +/// `(q, [[0], x])`, a bare local -> `(o, [])`. An index is a path element, written by +/// [`index_element`]. `None` for a base with no nameable root (`&5`, a call result). +pub fn base_and_path(e: &Expr) -> Option<(Symbol, Vec)> { + match e { + Expr::Identifier(id) => Some((id.name.clone(), Vec::new())), + Expr::MemberAccess(m) => { + let (root, mut path) = base_and_path(&m.base)?; + path.push(m.member.clone()); + Some((root, path)) + } + Expr::IndexAccess(ix) => { + let (root, mut path) = base_and_path(&ix.base)?; + push_path_element(&mut path, index_element(&ix.index)); + Some((root, path)) + } + _ => None, + } +} + +/// Whether two projection paths under the **same** root may name overlapping memory: true when +/// one is a prefix of the other (`[inner]` vs `[inner, v]`) or they match at every shared level. +/// Distinct fields (`[x]` vs `[y]`) and distinct constant indices (`[[0]]` vs `[[1]]`) are +/// disjoint; [`ANY_INDEX`] matches any element. Generic over the path element so the checker's +/// `[String]` and the lowerer's [`Symbol`] paths share it. Returning `true` for paths that are in +/// fact disjoint is always the safe direction: it withholds a `noalias` or reports a conflict. +pub fn paths_may_alias>(a: &[T], b: &[T]) -> bool { + a.iter().zip(b).all(|(x, y)| { + let (x, y) = (x.as_ref(), y.as_ref()); + x == y || [ANY_INDEX, RANGE_INDEX].contains(&x) || [ANY_INDEX, RANGE_INDEX].contains(&y) + }) +} + +/// How a place reads in a message: `q[0].x`, with a dot before each field and none before an +/// index. A tuple's fields, which the parser names `_0`, `_1`, .., read as the program writes +/// them: `t.0`. +pub fn display_place>(root: &str, path: &[T]) -> String { + let mut out = root.to_string(); + for p in path { + let p = p.as_ref(); + if !p.starts_with('[') { + out.push('.'); + } + match p.strip_prefix('_') { + Some(n) if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => out.push_str(n), + _ => out.push_str(p), + } + } + out +} + +/// A moved place as the checker records it, `p.a` or `t._0`, as it reads in a message. +pub fn display_dotted(place: &str) -> String { + let mut parts = place.split('.'); + let root = parts.next().unwrap_or_default(); + let path: Vec<&str> = parts.collect(); + display_place(root, &path) +} +``` + +Explain what this code does, function by function.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/explain2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/explain2.txt new file mode 100644 index 0000000..75cc3ff --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/explain2.txt @@ -0,0 +1,128 @@ +<|im_start|>user +`src/hir/check/drop_waits.rs`: + +```rust +//===- check submodule - Vx Compiler ----------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// A `drop` runs with cancellation off, so a cancel cannot stop a wait in it. A `send` or `recv` +// there waits until the time limit of the `drop` when the other end never acts. W1036 warns +// about such a call, and the fix is `send_for` or `recv_for`, or a call of `within` (F6 and F6a +// in docs/discussions/waiting_tasks_channels_and_task_errors.md). A wait in a closure literal +// written as the body of `within` has the limit of the call, so it gets no warning. A closure in +// a variable gets the warning, because the check cannot see that the variable goes to `within`. `wait_limit` runs before cancellation is off, +// and it should return a time and not wait, so W1036 warns about a wait in it too. +// It is a warning, not an error, because the check does not look into the functions that the +// `drop` calls. +// +//===----------------------------------------------------------------------===// + +use super::super::*; + +impl TypeChecker<'_> { + /// Whether `func` is the `drop` of a `Drop` impl: the `drop` that its receiver type uses. + pub(crate) fn is_drop_impl(&mut self, func: &Function) -> bool { + if !func.name.ends_with("drop") && !func.name.contains("$drop$") { + return false; + } + self.is_drop_impl_method(func, "drop") + } + + /// Whether `func` is the `wait_limit` of a `Drop` impl. + pub(crate) fn is_wait_limit_impl(&mut self, func: &Function) -> bool { + if !func.name.contains("wait_limit") { + return false; + } + self.is_drop_impl_method(func, "wait_limit") + } + + /// Whether `func` is the method `method` of the `Drop` impl of its receiver type. + fn is_drop_impl_method(&mut self, func: &Function, method: &str) -> bool { + let Some((_, receiver)) = func.params.first() else { + return false; + }; + let ty = match receiver { + Type::Borrow { inner, .. } | Type::Ref(inner, _) => inner.as_ref().clone(), + ty => ty.clone(), + }; + self.drops_impl_method(&ty, method) + .is_some_and(|name| name.as_ref() == func.name.as_ref()) + } + + /// W1036 when the `drop` of a `Drop` impl calls `method` on a value of type `base`, and the + /// call is a channel wait with no time limit. + pub(crate) fn warn_wait_in_drop(&mut self, base: &Type, method: &str, span: &Span) { + if !(self.in_drop || self.in_wait_limit) || self.within_depth > 0 || self.speculating { + return; + } + let timed = match method { + "send" => "send_for", + "recv" => "recv_for", + _ => return, + }; + let base = match base { + Type::Borrow { inner, .. } | Type::Ref(inner, _) => inner.as_ref(), + ty => ty, + }; + let name = match base { + Type::Struct(n, _) => n.clone(), + Type::GenericInstance(b, _) => match b.as_ref() { + Type::Struct(n, _) => n.clone(), + _ => return, + }, + _ => return, + }; + // The ends whose `send` or `recv` can wait. The `send` of a oneshot and of a watch + // channel does not wait. + let waits = match (method, name.split('<').next()) { + ("send", Some(end)) => matches!(end, "Sender" | "BroadcastSender"), + (_, Some(end)) => matches!( + end, + "Receiver" + | "OneshotReceiver" + | "BroadcastReceiver" + | "WatchReceiver" + | "WorkReceiver" + ), + _ => false, + }; + if !waits { + return; + } + if self.in_wait_limit { + self.errors.warn( + crate::diagnostic::DiagnosticCode::W1036, + format!( + "'{method}' waits in 'wait_limit'. 'wait_limit' runs before the drop, to say \ + how long its waits can take, so it should return a time and not wait" + ), + Some(crate::diagnostic::SourceSpan::from_ast_span(span)), + ); + return; + } + self.errors.warn( + crate::diagnostic::DiagnosticCode::W1036, + format!( + "'{method}' waits with no time limit of its own in a 'drop'. A drop runs with \ + cancellation off, so if the other end of the channel never acts, this wait \ + holds up the drop until the limit of the drop: its type's 'wait_limit', 10 \ + seconds by default. Use '{timed}' with a time limit, or put the wait in the \ + body of 'within'" + ), + Some(crate::diagnostic::SourceSpan::from_ast_span(span)), + ); + } +} +``` + +Explain what this code does, function by function.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/explain3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/explain3.txt new file mode 100644 index 0000000..a0c208f --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/explain3.txt @@ -0,0 +1,133 @@ +<|im_start|>user +`src/hir/decl_check/bounds.rs`: + +```rust +//===- decl_check submodule - Vx Compiler -----------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// A bound on a type parameter has to name a trait that exists. +// +//===----------------------------------------------------------------------===// + +use super::super::*; + +impl TypeChecker<'_> { + /// Refuse a bound such as `T : NoSuchTrait` whose trait is not declared (E3042). + /// + /// A bound is otherwise only asked when a call binds the parameter, so a misspelled one + /// on a function nobody calls, or on a struct, was never reported. + pub fn check_bounds_name_a_trait(&mut self) { + // (where the bound is written, the parameter, the trait it names, the place of the owner) + let mut unknown: Vec<(String, String, String, decl::DeclPlace)> = Vec::new(); + let traits = &self.env.traits; + let mut collect = + |owner: &str, generics: &[decl::GenericParam], place: &decl::DeclPlace| { + for param in generics { + if let decl::GenericParam::Type { name, bounds } = param { + for bound in bounds { + // `D : Topology` and `M : Memory` mark a topology and a memory + // parameter. They are keywords, not traits. + if matches!(bound.trait_name.as_ref(), "Topology" | "Memory") { + continue; + } + if !traits.contains_key(&bound.trait_name) { + unknown.push(( + owner.to_string(), + name.to_string(), + bound.trait_name.to_string(), + place.clone(), + )); + } + } + } + } + }; + + for s in self.env.structs.values() { + collect(&format!("struct {}", s.name), &s.generics, &s.place); + } + for e in self.env.enums.values() { + collect(&format!("enum {}", e.name), &e.generics, &e.place); + } + for t in self.env.traits.values() { + collect(&format!("trait {}", t.name), &t.generics, &t.place); + // A method signature has no place of its own, so its trait's is used. + for m in &t.methods { + collect( + &format!("method {}::{}", t.name, m.name), + &m.generics, + &t.place, + ); + } + } + for block in self.env.impls.values().flatten() { + let owner = match &block.trait_name { + Some(t) => format!("impl {} for {}", t, block.target_type), + None => format!("impl {}", block.target_type), + }; + collect(&owner, &block.generics, &block.place); + let impl_params: Vec<&str> = block.generics.iter().map(|g| g.name()).collect(); + // A trait default copied into the impl is reported on the trait. + for m in block + .methods + .iter() + .filter(|m| !block.copied_defaults.contains(&m.name)) + { + // A method is also given its impl's parameters, already reported above. + let own: Vec = m + .generics + .iter() + .filter(|g| !impl_params.contains(&g.name())) + .cloned() + .collect(); + collect( + &format!("method {}::{}", block.target_type, m.name), + &own, + &function_place(m), + ); + } + } + for (f, _) in self.env.generic_functions.values() { + collect(&format!("fn {}", f.name), &f.generics, &function_place(f)); + } + + // The tables are hash maps, and a generic method can be listed under its impl and as a + // function, so sort for a stable order and drop the repeats. + unknown.sort_by(|a, b| (&a.0, &a.1, &a.2).cmp(&(&b.0, &b.1, &b.2))); + unknown.dedup_by(|a, b| (&a.0, &a.1, &a.2) == (&b.0, &b.1, &b.2)); + let outside = self.errors.here(); + for (owner, param, trait_name, place) in unknown { + self.errors.point_at(&place, &outside); + self.errors.error_with_code( + crate::diagnostic::DiagnosticCode::E3042, + format!( + "the bound `{param} : {trait_name}` on `{owner}` names no trait; \ + no trait called '{trait_name}' is declared or imported" + ), + None, + ); + } + self.errors.point_back(outside); + } +} + +/// Where a function is written, as a declaration's place. +fn function_place(f: &decl::Function) -> decl::DeclPlace { + decl::DeclPlace { + file: f.file.clone(), + span: f.span, + } +} +``` + +Explain what this code does, function by function.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/write1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/write1.txt new file mode 100644 index 0000000..316ba64 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/write1.txt @@ -0,0 +1,7 @@ +<|im_start|>user +Write a Python function merge_intervals(intervals) that merges overlapping closed intervals and returns them sorted. Add pytest tests for it, with empty input and touching intervals.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/write2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/write2.txt new file mode 100644 index 0000000..bcb9afb --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/write2.txt @@ -0,0 +1,7 @@ +<|im_start|>user +Write a C function `void reverse_words(char *s)` that reverses the order of the words in a string in place, with single spaces between words. Add a main() that tests it.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/write3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/write3.txt new file mode 100644 index 0000000..d992c11 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/write3.txt @@ -0,0 +1,7 @@ +<|im_start|>user +Write a Rust struct Trie with new, insert, contains and starts_with for lowercase ASCII words. Add unit tests.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/tokens.csv b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/tokens.csv new file mode 100644 index 0000000..68741a9 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/tokens.csv @@ -0,0 +1,31 @@ +prompt,tokens +context/ctx64,64 +context/ctx512,512 +context/ctx2048,2048 +context/ctx8192,8192 +context/ctx16384,16384 +context/ctx32768,32768 +twelve/edit1,1799 +twelve/edit2,1577 +twelve/edit3,2251 +twelve/complete1,1726 +twelve/complete2,1608 +twelve/complete3,1508 +twelve/write1,41 +twelve/write2,52 +twelve/write3,39 +twelve/explain1,1384 +twelve/explain2,1549 +twelve/explain3,1915 +heldout/edit1,1668 +heldout/edit2,1286 +heldout/edit3,1605 +heldout/complete1,1044 +heldout/complete2,1086 +heldout/complete3,1288 +heldout/write1,44 +heldout/write2,52 +heldout/write3,35 +heldout/explain1,1503 +heldout/explain2,1330 +heldout/explain3,1257 diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/complete1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/complete1.txt new file mode 100644 index 0000000..e4f8827 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/complete1.txt @@ -0,0 +1,130 @@ +<|im_start|>user +`src/report.rs`: + +```rust +//===- report.rs - Vx Compiler ---------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// What the memory-algebra analysis found, in the shape a consumer reads it in: resident sets, +// transfer routes and their costs, and counted traffic. +// +// These are the checker's output, not the checker's working state, which is why they live outside +// hir/. --diagnostics-json is a report format, and a report format that imports the type checker's +// internals cannot change without the checker changing too. +// +//===----------------------------------------------------------------------===// + +/// One memory space's working set for a function: the granule-rounded sum of the tiles placed +/// there, against the space's declared capacity. Recorded for *every* placed space, not only +/// those that overflow — an admitted program emits no capacity diagnostic, so this is the only +/// place its resident total appears. Downstream that total is what turns a capacity verdict into +/// an engine's required memory utilization (#285). See [`crate::hir::env::TypeChecker::resident_sets`]. +#[derive(Debug, Clone, PartialEq)] +pub struct ResidentSet { + pub space: crate::syntax::MemorySpace, + /// The device whose copy of the space this is (`Card[1]`), when the space is the memory of a + /// topology with more than one device. Each device has its own copy and its own working set. + pub device: Option, + /// Granule-rounded sum of tiles placed in this space by one function. + pub total_bytes: u64, + pub capacity_bytes: u64, + pub tiles: usize, + /// Whether the space is declared `overcommit` (an overflow is W1028, not E6010). + pub overcommit: bool, +} + +/// A resolved `transfer`: the chain of memory spaces the value actually moves through and the +/// declared cost of each hop. A direct transfer has one hop; a multi-hop route (synthesized when +/// no direct edge exists) has one per staging step. `derived_cost` is the bandwidth-roofline cost +/// when the declarations make it computable, which is what the emitted `vx.transfer` carries. +/// See [`crate::hir::env::TypeChecker::staging_routes`] (#282). +#[derive(Debug, Clone, PartialEq)] +pub struct StagingRoute { + /// The spaces traversed, source first: `[CPU_DRAM, HBM3e, SMEM]`. + pub path: Vec, + /// Per-edge declared cost, one shorter than `path`; `None` for an edge with no declared cost. + pub edge_costs: Vec>, + /// The cost graph's total for the whole route. + pub total_cost: u32, + /// Bandwidth-derived (roofline) cost, when the declarations supply bandwidths. + /// + /// `u64`, not `u32`: a picosecond-resolution time cost overflows `u32` at 4.3 ms, which a + /// multi-gigabyte host transfer exceeds, and a saturated cost would read as a slow transfer + /// rather than a missing one. + pub derived_cost: Option, + /// Bytes this transfer moves, when the shape is statically known. + /// + /// Without it a harvested cost cannot be interpreted: "260064 ps" is not a prediction unless + /// the size it is a cost *of* travels with it, and comparing predicted against measured needs + /// both. `None` for a dynamically-shaped tensor, where no cost is derivable either. + pub bytes: Option, + /// Which cost source produced `derived_cost`. The two are mutually exclusive per edge (E6013), + /// so this names the one that applied rather than a precedence winner — and it is what tells a + /// consumer whether a residual is attributable to a declared link figure or to an inferred + /// containment roofline. + pub cost_source: Option, + /// The unit `derived_cost` is in — cycles, or picoseconds. Carried rather than dropped because + /// one program's routes legitimately mix them: an on-die hop declared `B/cyc` and a host link + /// declared `GB/s` produce costs of different *dimension*, and a harvested prediction that does + /// not say which is not a prediction. (The fleet's `HBM->L2` and `L2->SMEM` are exactly this + /// pair.) + pub derived_unit: Option, + /// Which composition law priced a containment route: `sum` or `bottleneck`. + /// + /// `None` for a link-rate hop, which has one leg and so composes nothing. Carried because the + /// two laws differ by ~2x on a multi-hop walk and a harvested prediction that does not say + /// which one applied cannot be re-scored later -- the same reason `derived_unit` is carried. + pub composition: Option, + /// Bytes moved per space, derived from code (#353). `None` when the movement cannot be + /// counted statically, in which case `traffic_absent_reason` says why -- a guess here would + /// be indistinguishable from a measurement in the record a campaign harvests, which is the + /// same reason `derived_cost` is `None` rather than 0 when no bandwidth is declared. + pub traffic: Option, + /// Why `traffic` is `None`. `None` when traffic is present. + pub traffic_absent_reason: Option, +} + +/// Bytes read and written against one placed buffer by a `spawn` region (#353). +/// +/// Per BUFFER, not just per space, because the amplification this stage exists to show is a +/// fact about a particular tensor: a streamed operand is re-read on every outer iteration +/// while the blocked one is read once. Summed into their shared space they +/// become one number that hides which of them is the problem. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BufferTraffic { + pub buffer: String, + pub space: crate::syntax::MemorySpace, + pub read_bytes: u64, + pub written_bytes: u64, +} + +/// What one `spawn on(...)` region moves, counted from its indexed accesses and the static +/// trip counts of the loops around them (#353). +/// +/// The transfer-hop counts say what it costs to GET a tile to a space. This says what the +/// kernel then does with it, which is where re-reading lives: a tile staged once and read +/// sixteen times is sixteen reads, and no declared edge cost can say so because the movement +/// across the edge happened exactly once. +#[derive(Debug, Clone, PartialEq)] +pub struct SpawnRegionTraffic { + /// The function the `spawn` appears in. + pub function: String, + /// The topology the region runs on, as its display name. + pub topology: String, + /// Aggregate per space, or `None` when the region could not be counted exactly. + pub traffic: Option, + /// Per placed buffer, sorted by name. Empty when `traffic` is `None`. +``` + +This file stops in the middle. Continue it from exactly where it stops. Output only the rest of the file.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/complete2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/complete2.txt new file mode 100644 index 0000000..64b29cb --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/complete2.txt @@ -0,0 +1,146 @@ +<|im_start|>user +`scripts/tools/check_doc_examples.py`: + +```python +#!/usr/bin/env python3 +"""Compile every Vx example in the documentation. + +Documentation drifts silently because nothing executes it. An audit of this repository found the +README's own headline example did not parse, a tutorial teaching a topology syntax that was never +implemented, `grad` documented with the wrong arity, and a grammar production admitting two types +the parser rejects. Every one of those had been correct when written. + +This makes that class of error a build failure. + + python3 scripts/tools/check_doc_examples.py # check everything + python3 scripts/tools/check_doc_examples.py --list # show what would be checked + python3 scripts/tools/check_doc_examples.py README.md # check specific files + +A block is checked when it is fenced ```vx or ```rust, contains a top-level declaration, and is +not skipped by one of the rules below. To exempt a block deliberately, put + + + +on the line before its fence, ideally with a reason. + +Most blocks are only parsed. A block marked + + + +is compiled and run instead, and what it prints must equal the ```text block that follows it +(one short line, such as "It prints:", may come between them). + +The hand-written pages under `www/` are checked as well, through their `
` blocks. The
+landing page carries the most-read Vx code on the site and was the only code on it that nothing
+compiled -- everything in the book is covered because the book is markdown. The same skip comment
+works there, on the line before the `
`.
+
+Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions.
+See LICENSE for license information.
+SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+"""
+
+import html
+import os
+import re
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+FENCE = re.compile(
+    r"(?:\s*\n)?```(vx|rust)\n(.*?)```", re.S
+)
+# The expected output, after at most one short line such as "It prints:".
+OUTPUT = re.compile(r"\s*(?:[^`\n]+\n\s*)?```text\n(.*?)```", re.S)
+
+# The same idea for the hand-written pages: a 
 block, optionally preceded by the skip
+# comment. Their code carries syntax highlighting as  tags, which are stripped before the
+# body is compiled.
+HTML_BLOCK = re.compile(
+    r"(?:()\s*\n?\s*)?
(.*?)
", re.S +) +TAG = re.compile(r"<[^>]+>") + +# A block has to declare something to be a compilable unit. Bare statements are illustrative +# fragments and are left alone. +DECLARES = re.compile(r"^\s*(fn |pub fn |unsafe fn |safe fn |struct |enum |trait |impl |extern |macro_rules!|Memory |Topology )", re.M) + +# Constructs that exist in Rust and not in Vx. Architecture documents embed compiler internals in +# ```rust fences, and those are Rust, not examples of the language. +RUST_ONLY = re.compile( + r"^\s*use\s+\w|#\[|#!\[|\bpub\s+(struct|enum|mod|const|trait)\b|\bcrate::|" + r"&self\b|&mut self\b|\bimpl\s+\w+\s+for\s+\w+\s*\{[^}]*fn\s+\w+\s*\(\s*&|" + # Types and idioms from the standard Rust library that Vx has no equivalent of. The + # architecture documents embed real compiler internals, and these are what give them away. + r"\bArc<|\bRc<|\bWeak<|\bRefCell<|\bMutex<|\bRwLock<|\bBox +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/complete3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/complete3.txt new file mode 100644 index 0000000..4452b50 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/complete3.txt @@ -0,0 +1,136 @@ +<|im_start|>user +`src/session.rs`: + +```rust +//===- session.rs - Vx Compiler --------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines the core compiler session and local worker states. +// It orchestrates the compilation pipeline across multiple threads, managing shared +// diagnostics, module registries, and global state required during the lowering +// of Vx source code to MLIR. +// +//===----------------------------------------------------------------------===// +use crate::bytecode::HirInstruction; +use crate::gid::{TypeId, UnboundedFunctionMetadata}; +use std::sync::Arc; + +// The frozen nominal-type registry (layouts + module indices + cycle-checked). Built once per +// compilation at the Phase 2 freeze point and shared read-only across worker threads. Re-exported +// here so `GlobalSession` and the verifier name it via `session`, but the type lives in `registry`. +pub use crate::registry::ImmutableGlobalRegistry; + +/// Represents the frozen past of the compilation process. +/// It contains everything compiled before the current phase. +/// +/// # Data-Oriented Design (DOD) Constraints +/// This session deliberately separates dynamic compiler metadata into strictly +/// typed, homogeneous arenas rather than using a single polymorphic `Enum` array +/// (e.g., `enum SlowPathData { Function(...), Generics(...) }`). +/// +/// 1. **Cache-Line Density**: `UnboundedFunctionMetadata` is a dense structure of `u64` +/// bitfields. Iterating over it is highly predictable. `Vec`, however, +/// is a heap-allocated fat pointer with variable lengths. Mixing them would introduce +/// unpredictable struct padding and pointer-chasing overhead. +/// 2. **Hardware Prefetching**: By keeping `generics_arena` separate, the CPU's spatial +/// prefetcher can stream through the dense `slow_path_arena` at maximum bandwidth +/// during the critical lifetime subtyping pass, without stalling on scattered `Vec` pointers. +pub struct GlobalSession { + pub epoch: u64, + /// How this compilation forms a generic instantiation's identity. + /// + /// A per-compilation fact, frozen with the rest of the epoch, because that is what it is: two + /// compilations in one process may legitimately want different strategies, and a worker must + /// not be able to observe a choice that belongs to someone else's compile. It lived in a + /// process-global until Vx#381 -- set from `--intern-mode` on one thread and read by every + /// worker from inside the parallel type-check. + pub intern_mode: crate::intern_mode::InternMode, + /// `-fauto-schedule-levels`: an `across` loop on an arch that cannot launch its levels runs + /// as a plain `for` that carries its level, instead of E6032. + pub auto_schedule_levels: bool, + pub registry: Arc, + + /// The dense, homogeneous arena for complex parameter and lifetime evaluation. + /// Accessed heavily during Phase 1 type-checking and borrow checking. + pub slow_path_arena: Arc>, + + /// The heterogeneous arena for structural generic instantiations. + /// Separated to prevent cache fragmentation in the `slow_path_arena`. + pub generics_arena: Arc>, + pub generics_offsets: Arc>, +} + +impl GlobalSession { + /// A session with an *empty* frozen registry — for callers that don't build one (the + /// sequential driver, unit tests). The parallel pipeline uses [`Self::with_registry`]. + pub fn new(epoch: u64) -> Self { + Self::with_registry( + epoch, + ImmutableGlobalRegistry::build_and_validate(Vec::new()) + .expect("an empty registry is always valid"), + ) + } + + /// A session holding the frozen registry built at the Phase 2 freeze point. + pub fn with_registry(epoch: u64, registry: ImmutableGlobalRegistry) -> Self { + Self { + epoch, + intern_mode: crate::intern_mode::InternMode::Deferred, + auto_schedule_levels: false, + registry: Arc::new(registry), + slow_path_arena: Arc::new(Vec::new()), + generics_arena: Arc::new(Vec::new()), + generics_offsets: Arc::new(Vec::new()), + } + } + + /// The same session with a chosen interning strategy. Consuming rather than a setter, because + /// the session is frozen once it is shared: every worker holds an `Arc` of it and reads it by + /// `&`, so it must be settled before it is wrapped. + pub fn in_intern_mode(mut self, mode: crate::intern_mode::InternMode) -> Self { + self.intern_mode = mode; + self + } + + /// The same session with `-fauto-schedule-levels` on or off. + pub fn auto_schedule_levels(mut self, on: bool) -> Self { + self.auto_schedule_levels = on; + self + } +} + +/// Represents the mutable present of a single worker thread during Phase 1. +pub struct LocalWorkerState { + pub global: Arc, + + // Completely lock-free, thread-local mutation + pub local_slow_path_arena: Vec, + pub local_generics_arena: Vec, + pub local_generics_offsets: Vec<(usize, usize)>, + + // The flat arrays replacing the AST + pub local_type_stream: Vec, // array of 256-bit GIDs + pub local_hir_stream: Vec, + + /// Tensor-type side table: `GID -> (element, shape)` for every tensor type this function's stream + /// references. Tensor GIDs are content hashes (not invertible) and tensors are structural (never + /// in the nominal registry), so codegen can't reconstruct a tensor's memref type from the stream + /// alone -- most acutely for `TensorAlloc`. The lowerer records it here as it emits tensor values; + /// the flat codegen consumes it (the tensor analogue of the registry's struct `layouts`). + pub local_tensor_types: Vec<(TypeId, crate::syntax::ElementType, Vec)>, + + /// String side table: the string-literal bytes for each `PrintStr` this function's stream emits, +``` + +This file stops in the middle. Continue it from exactly where it stops. Output only the rest of the file.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/edit1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/edit1.txt new file mode 100644 index 0000000..2acb824 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/edit1.txt @@ -0,0 +1,183 @@ +<|im_start|>user +`scripts/tools/gen_error_index.py`: + +```python +#!/usr/bin/env python3 +"""Generate the diagnostic index from the compiler's own diagnostic table. + +`src/diagnostic.rs` is the single place every code is declared, each with a doc comment saying +what it means and a section header grouping it. That makes it the only honest source for a +reference: a hand-written index drifts the moment someone adds a code, and 78 of the 113 codes +were undocumented anywhere before this existed. + + python3 scripts/tools/gen_error_index.py # write the index + python3 scripts/tools/gen_error_index.py --check # fail if it is out of date + +Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +See LICENSE for license information. +SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +""" + +import re +import subprocess +import sys +from pathlib import Path + +SOURCE = Path("src/diagnostic.rs") +OUTPUT = Path("www/book/src/error-index.md") + +# The section headers in diagnostic.rs are terse. These say what the stage actually does, so the +# index reads as a guide rather than as a dump of the enum. +SECTION_BLURB = { + "Warnings": "Reported without stopping the compile. A warning means the program is accepted " + "but something in it is probably not what was intended.", + "Parser Errors": "Raised while turning source text into an AST. The program is not " + "syntactically valid Vx.", + "Name Resolution Errors": "Raised when a name cannot be resolved to a declaration, or " + "resolves to something of the wrong kind.", + "Type Errors": "Raised by the type checker. Vx performs no implicit numeric conversion, so " + "many of these are mismatches that a language with coercion would have silently accepted.", + "Borrow/Ownership Errors": "Raised by the borrow checker and the linear-type rules. These " + "rule out use-after-move, aliasing violations and lifetimes that outlive what they point at.", + "Safety Errors": "Raised where an operation needs an `unsafe` context and does not have one.", + "Topology/Hardware Errors": "Raised by the placement and capacity rules — the checks that " + "make Vx different from a single-address-space language. A value in the wrong memory space, " + "a region on the wrong device, a working set that does not fit, or a transfer with no " + "declared route.", + "Tensor/Math Errors": "Raised on tensor shapes and numeric operations, including shape " + "mismatches that are decided at compile time.", + "Contract/Verification Errors": "Raised when a `requires`, `ensures` or `invariant` clause " + "cannot be discharged, or when a seam obligation is left unproven.", +} + +HEADER = """# Diagnostic index + +Every code that the Vx compiler defines, and what it means. Some codes, among them the parser's +`E1xxx` codes, do not appear in the compiler's messages yet +([Vx#3227](https://github.com/vx-lang/Vx/issues/3227)). + +Codes are grouped by the compilation stage that raises them, and the group is readable off the +number: `E1xxx` is the parser, `E3xxx` the type checker, `E6xxx` the placement and capacity rules, +and so on. A `W` prefix is a warning rather than an error. + +> This file is generated from `src/diagnostic.rs` by `scripts/tools/gen_error_index.py`. Edit the +> doc comments on the codes there, not this file. + +Every code below links to its own page, which carries the message the compiler emits and, where +the test suite has one, a program that triggers it. + +""" + + +def parse(source_text): + """Yield (section, code, description) in declaration order.""" + section = None + pending = [] + + for line in source_text.splitlines(): + stripped = line.strip() + + header = re.match(r"//\s*---\s*(.+?)\s*\((?:[EW]\dxxx)\)\s*---", stripped) + if header: + section = header.group(1) + pending = [] + continue + + doc = re.match(r"///\s?(.*)", stripped) + if doc: + pending.append(doc.group(1).strip()) + continue + + code = re.match(r"^([EW][0-9]{4}),$", stripped) + if code: + yield section, code.group(1), " ".join(p for p in pending if p).strip() + pending = [] + continue + + # Anything else (attributes, blank lines, the enum braces) resets the doc buffer only if + # it is a real statement; blank lines inside a doc block are kept. + if stripped and not stripped.startswith("#"): + pending = [] + + +def render(entries): + out = [HEADER] + by_section = {} + for section, code, desc in entries: + by_section.setdefault(section or "Uncategorised", []).append((code, desc)) + + out.append("## Contents\n") + for section in by_section: + anchor = section.lower().replace(" ", "-").replace("/", "") + codes = [c for c, _ in by_section[section]] + out.append(f"- [{section}](#{anchor}) — `{codes[0]}`–`{codes[-1]}` ({len(codes)} codes)") + out.append("") + + for section, items in by_section.items(): + out.append(f"## {section}\n") + blurb = SECTION_BLURB.get(section) + if blurb: + out.append(f"{blurb}\n") + out.append("| Code | Meaning |") + out.append("| --- | --- |") + for code, desc in items: + # Each code also has a page of its own at vxlang.org/errors/, with the message and a + # program that triggers it. Root-relative, so mdBook leaves it alone. + out.append(f"| [`{code}`](/errors/{code}/) | {desc or '—'} |") + out.append("") + + total = sum(len(v) for v in by_section.values()) + out.append("______________________________________________________________________\n") + out.append(f"{total} diagnostics.\n") + return "\n".join(out) + + +def main(): + if not SOURCE.exists(): + print(f"error: {SOURCE} not found; run from the repository root", file=sys.stderr) + return 1 + + entries = list(parse(SOURCE.read_text())) + if not entries: + print("error: no diagnostic codes parsed -- has the table's shape changed?", file=sys.stderr) + return 1 + + rendered = render(entries) + + # Matches the shape mdformat produces, so the generated file needs no follow-up pass. + + try: + rendered = subprocess.run( + ["mdformat", "-"], input=rendered, capture_output=True, text=True, check=True + ).stdout + except (FileNotFoundError, subprocess.CalledProcessError): + pass # mdformat is optional locally; CI has it. + + if "--check" in sys.argv: + current = OUTPUT.read_text() if OUTPUT.exists() else "" + if current != rendered: + print( + f"error: {OUTPUT} is out of date.\n" + f" Run: python3 {Path(__file__).as_posix()}", + file=sys.stderr, + ) + return 1 + print(f"{OUTPUT} is up to date ({len(entries)} diagnostics)") + return 0 + + OUTPUT.write_text(rendered) + print(f"wrote {OUTPUT} ({len(entries)} diagnostics)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) +``` + +Add a type hint to every function parameter and return value. Output the whole file, and change nothing else.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/edit2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/edit2.txt new file mode 100644 index 0000000..e53583a --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/edit2.txt @@ -0,0 +1,152 @@ +<|im_start|>user +`src/hash.rs`: + +```rust +//===- hash.rs - Vx Compiler -----------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file provides specialized, stable hashing utilities for the compiler. +// It implements robust hash generation for type IDs, module signatures, and +// anonymous structural types, ensuring consistent symbol mangling and metadata +// serialization across incremental builds. +// +//===----------------------------------------------------------------------===// +/// 64-bit FNV-1a parameters (standard offset basis + prime). FNV is **project-controlled and stable +/// across toolchains** — unlike `FxHasher`/`DefaultHasher`, whose algorithms may change between +/// library/compiler releases. GID word 0/1 are content hashes that must reproduce byte-for-byte +/// across builds and machines (reproducible builds, cross-crate identity), so the algorithm cannot +/// be an unpinned dependency. This mirrors the FNV scheme `arch.rs` already hand-rolls for dispatch +/// ids, for the same reason. See #195. FNV-1a is *not* cryptographic: accidental collisions are +/// negligible but not impossible, so `ImmutableGlobalRegistry::build_and_validate` additionally +/// rejects any two distinct symbols that land on the same GID. +const FNV_OFFSET_BASIS_64: u64 = 0xcbf2_9ce4_8422_2325; +const FNV_PRIME_64: u64 = 0x0000_0100_0000_01b3; + +/// Streaming 64-bit FNV-1a: fold `bytes` into a running `hash` (seeded with the offset basis on the +/// first call, then chained) so multi-field def paths hash deterministically as one stream. +#[inline] +fn fnv1a_64(hash: u64, bytes: &[u8]) -> u64 { + let mut hash = hash; + for b in bytes { + hash ^= *b as u64; + hash = hash.wrapping_mul(FNV_PRIME_64); + } + hash +} + +/// Computes the stable 64-bit content hash (GID word 0) for a given module path. +pub fn compute_module_hash(module_path: &str) -> u64 { + fnv1a_64(FNV_OFFSET_BASIS_64, module_path.as_bytes()) +} + +/// Represents the stable topological path to a definition (struct, enum, closure). +/// This prevents incremental compilation breakage when anonymous types are re-ordered. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum DefPath<'a> { + /// A named, top-level symbol (e.g., `MyStruct`). + Named(&'a str), + /// An anonymous closure or comptime block, defined by its structural layout + /// or its position within a specific parent item, rather than file line number. + Anonymous { + parent_hash: u64, + structural_hash: u64, + }, +} + +impl<'a> DefPath<'a> { + /// Computes the deterministic 64-bit Word 1 for the TypeId (stable FNV-1a; see [`fnv1a_64`]). + pub fn compute_symbol_hash(&self) -> u64 { + match self { + DefPath::Named(name) => { + // 0 is the discriminator for Named. + let h = fnv1a_64(FNV_OFFSET_BASIS_64, &[0u8]); + fnv1a_64(h, name.as_bytes()) + } + DefPath::Anonymous { + parent_hash, + structural_hash, + } => { + // 1 is the discriminator for Anonymous; fold the two u64 fields in a fixed byte + // order so the hash is architecture-independent. + let mut h = fnv1a_64(FNV_OFFSET_BASIS_64, &[1u8]); + h = fnv1a_64(h, &parent_hash.to_le_bytes()); + fnv1a_64(h, &structural_hash.to_le_bytes()) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Pins the exact algorithm + constants (#195). These are FNV-1a-64 golden values computed + /// independently; if the hash ever silently changes (e.g. someone swaps back to a std hasher), + /// every previously emitted GID / serialized metadata would break, and this catches it. + #[test] + fn hash_is_stable_fnv1a_golden_values() { + assert_eq!(compute_module_hash("crate::a"), 0xdbc1_8e8e_2c15_a207); + assert_eq!( + DefPath::Named("Foo").compute_symbol_hash(), + 0xed6f_617e_4534_5949 + ); + } + + /// Empty input hashes to the bare offset basis (the FNV-1a identity) — a sanity anchor on the + /// seeding. + #[test] + fn empty_module_path_is_offset_basis() { + assert_eq!(compute_module_hash(""), FNV_OFFSET_BASIS_64); + } + + #[test] + fn test_named_defpath_stability() { + let path1 = DefPath::Named("MyStruct"); + let path2 = DefPath::Named("MyStruct"); + assert_eq!(path1.compute_symbol_hash(), path2.compute_symbol_hash()); + + let path3 = DefPath::Named("OtherStruct"); + assert_ne!(path1.compute_symbol_hash(), path3.compute_symbol_hash()); + } + + #[test] + fn test_anonymous_defpath_stability() { + let parent = DefPath::Named("ParentFn").compute_symbol_hash(); + + let anon1 = DefPath::Anonymous { + parent_hash: parent, + structural_hash: 0x12345678, + }; + + let anon2 = DefPath::Anonymous { + parent_hash: parent, + structural_hash: 0x12345678, + }; + + assert_eq!(anon1.compute_symbol_hash(), anon2.compute_symbol_hash()); + + let anon_different_structure = DefPath::Anonymous { + parent_hash: parent, + structural_hash: 0x87654321, + }; + + assert_ne!( + anon1.compute_symbol_hash(), + anon_different_structure.compute_symbol_hash() + ); + } +} +``` + +Add a `///` doc comment above every function that has none. Output the whole file, and change nothing else.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/edit3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/edit3.txt new file mode 100644 index 0000000..a8c37da --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/edit3.txt @@ -0,0 +1,207 @@ +<|im_start|>user +`runtime/vx_mlir_shims.c`: + +```c +/*===- vx_mlir_shims.c - Vx Compiler ------------------------------*- C -*-===*\ +|* *| +|* Part of the Vx Project, under the Apache License v2.0 with LLVM *| +|* Exceptions. *| +|* See LICENSE for license information. *| +|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| +|* *| +\*===----------------------------------------------------------------------===*/ +/* The half-precision memref printers MLIR does not export in the form emitted + * code calls. + * + * `libmlir_runner_utils` exports printMemrefF32, F64, I32 and I64 both plainly + * and packed as `_mlir_ciface_*`, but the half-precision printers ONLY packed + * -- `nm` on MLIR 22 shows `_mlir_ciface_printMemrefBF16` and no plain + * `printMemrefBF16`. Codegen emits the plain call, so a bf16 program could not + * link, run, or emit an object. Its RUN line only emits MLIR, so nothing + * noticed. + * + * `llvm.emit_c_interface` on the declaration does not fix it: MLIR then gives + * the function a body and the ExecutionEngine wants `_mlir_printMemrefBF16` + * instead, which no library exports either. Supplying the plain symbol here is + * what closes it, and it belongs beside the runtime rather than in vx_std_core + * -- the standard library has no MLIR dependency and should not gain one to + * print a tensor. + * + * MLIR's unpacked convention for `memref<*xT>` passes (rank, pointer to the + * ranked descriptor). The packed entry point takes a pointer to exactly that + * pair. + */ + +#include +#include +#include +#include + +typedef struct { + int64_t rank; + void *descriptor; +} VxUnrankedMemRef; + +extern void _mlir_ciface_printMemrefBF16(void *unranked); +extern void _mlir_ciface_printMemrefF16(void *unranked); +extern void _mlir_ciface_printMemrefI8(void *unranked); +extern void _mlir_ciface_printMemrefI16(void *unranked); + +void printMemrefBF16(int64_t rank, void *descriptor) { + VxUnrankedMemRef packed = {rank, descriptor}; + _mlir_ciface_printMemrefBF16(&packed); +} + +void printMemrefF16(int64_t rank, void *descriptor) { + VxUnrankedMemRef packed = {rank, descriptor}; + _mlir_ciface_printMemrefF16(&packed); +} + +/* The integer tensor printers MLIR does not supply in the form codegen calls, + * or prints wrongly. MLIR has no unsigned integer type: a `u32` tensor is a + * memref of `i32`, and MLIR's printMemrefI32 reads 4000000000 as -294967296. + * printMemrefU8/U16/U32/U64 read the elements unsigned. printMemrefI8 cannot + * use MLIR's printer at all -- it prints each element as a character (`100` + * prints as `d`) -- so it is ours, reading the bytes signed like a scalar + * `i8`. All of them print the header line and the brackets, spaces and commas + * of MemRefDataPrinter in MemRefUtils.h, so the text does not depend on which + * printer a type chose. + */ + +typedef struct { + void *allocated; + void *aligned; + int64_t offset; + int64_t sizes_and_strides[]; +} VxRankedMemRef; + +static void vx_print_spaces(int64_t count) { + for (int64_t i = 0; i < count; ++i) + putchar(' '); +} + +/* The compiler sends only the element kinds that vx_print_element prints, so + * any other kind is a compiler bug. The program stops in every build: an + * `assert` is compiled out when NDEBUG is set, and the tensor would then print + * wrong values or none. */ +_Noreturn static void vx_no_element_printer(int bytes, int is_signed) { + fprintf(stderr, "[Vx] FATAL: no printer for a %d-byte %s tensor element\n", + bytes, is_signed ? "signed" : "unsigned"); + abort(); +} + +/* `bytes` is the element size. The signed branch is only for `i8`: MLIR prints + * `i16` itself, and the wide signed types keep MLIR's own printers. */ +static void vx_print_element(const void *base, int64_t at, int bytes, + int is_signed) { + if (is_signed) { + if (bytes != 1) + vx_no_element_printer(bytes, is_signed); + printf("%d", (int)((const int8_t *)base)[at]); + return; + } + switch (bytes) { + case 1: + printf("%u", (unsigned)((const uint8_t *)base)[at]); + return; + case 2: + printf("%u", (unsigned)((const uint16_t *)base)[at]); + return; + case 4: + printf("%" PRIu32, ((const uint32_t *)base)[at]); + return; + case 8: + printf("%" PRIu64, ((const uint64_t *)base)[at]); + return; + } + vx_no_element_printer(bytes, is_signed); +} + +static void vx_print_data(const void *base, int bytes, int is_signed, + int64_t dim, int64_t rank, int64_t offset, + const int64_t *sizes, const int64_t *strides) { + if (dim == 0) { + vx_print_element(base, offset, bytes, is_signed); + return; + } + printf("["); + vx_print_data(base, bytes, is_signed, dim - 1, rank, offset, sizes + 1, + strides + 1); + if (sizes[0] <= 1) { + printf("]"); + return; + } + printf(", "); + if (dim > 1) + printf("\n"); + for (int64_t i = 1; i + 1 < sizes[0]; ++i) { + vx_print_spaces(rank - dim + 1); + vx_print_data(base, bytes, is_signed, dim - 1, rank, + offset + i * strides[0], sizes + 1, strides + 1); + printf(", "); + if (dim > 1) + printf("\n"); + } + vx_print_spaces(rank - dim + 1); + vx_print_data(base, bytes, is_signed, dim - 1, rank, + offset + strides[0] * (sizes[0] - 1), sizes + 1, strides + 1); + printf("]"); +} + +static void vx_print_memref(int64_t rank, void *descriptor, int bytes, + int is_signed) { + const VxRankedMemRef *m = (const VxRankedMemRef *)descriptor; + const int64_t *sizes = m->sizes_and_strides; + const int64_t *strides = m->sizes_and_strides + rank; + printf("Unranked Memref base@ = %p rank = %" PRId64 " offset = %" PRId64 + " sizes = [", + m->aligned, rank, m->offset); + for (int64_t i = 0; i < rank; ++i) + printf(i ? ", %" PRId64 : "%" PRId64, sizes[i]); + printf("] strides = ["); + for (int64_t i = 0; i < rank; ++i) + printf(i ? ", %" PRId64 : "%" PRId64, strides[i]); + printf("] data = \n"); + if (rank == 0) + printf("["); + vx_print_data(m->aligned, bytes, is_signed, rank, rank, m->offset, sizes, + strides); + if (rank == 0) + printf("]"); + printf("\n"); + fflush(stdout); +} + +void printMemrefI8(int64_t rank, void *descriptor) { + vx_print_memref(rank, descriptor, 1, 1); +} + +void printMemrefI16(int64_t rank, void *descriptor) { + VxUnrankedMemRef packed = {rank, descriptor}; + _mlir_ciface_printMemrefI16(&packed); +} + +void printMemrefU8(int64_t rank, void *descriptor) { + vx_print_memref(rank, descriptor, 1, 0); +} + +void printMemrefU16(int64_t rank, void *descriptor) { + vx_print_memref(rank, descriptor, 2, 0); +} + +void printMemrefU32(int64_t rank, void *descriptor) { + vx_print_memref(rank, descriptor, 4, 0); +} + +void printMemrefU64(int64_t rank, void *descriptor) { + vx_print_memref(rank, descriptor, 8, 0); +} +``` + +Add a one-line comment above every function that says what it does. Output the whole file, and change nothing else.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/explain1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/explain1.txt new file mode 100644 index 0000000..3a16598 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/explain1.txt @@ -0,0 +1,153 @@ +<|im_start|>user +`src/suggest.rs`: + +```rust +//===- suggest.rs - Vx Compiler ------------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Provides "did you mean?" suggestions for name resolution errors using +// Levenshtein edit distance. Used by E2001-E2007 diagnostics. +// +//===----------------------------------------------------------------------===// + +/// Compute Levenshtein edit distance between two strings. +pub fn levenshtein(a: &str, b: &str) -> usize { + let a_len = a.len(); + let b_len = b.len(); + + if a_len == 0 { + return b_len; + } + if b_len == 0 { + return a_len; + } + + let mut prev_row: Vec = (0..=b_len).collect(); + let mut curr_row = vec![0; b_len + 1]; + + for (i, a_char) in a.chars().enumerate() { + curr_row[0] = i + 1; + for (j, b_char) in b.chars().enumerate() { + let cost = if a_char == b_char { 0 } else { 1 }; + curr_row[j + 1] = (prev_row[j + 1] + 1) + .min(curr_row[j] + 1) + .min(prev_row[j] + cost); + } + std::mem::swap(&mut prev_row, &mut curr_row); + } + + prev_row[b_len] +} + +/// Find the closest match to `target` from a list of `candidates`. +/// Returns `None` if no candidate is within `max_dist` edits. +pub fn closest_match<'a>(target: &str, candidates: &[&'a str], max_dist: usize) -> Option<&'a str> { + candidates + .iter() + .filter_map(|c| { + let dist = levenshtein(target, c); + if dist > 0 && dist <= max_dist { + Some((*c, dist)) + } else { + None + } + }) + .min_by_key(|(_, d)| *d) + .map(|(c, _)| c) +} + +/// Suggest a correction for a name, using a dynamic max distance based on name length. +/// Short names (1-3 chars) allow 1 edit, medium names (4-7) allow 2, longer allow 3. +pub fn suggest_name<'a>(target: &str, candidates: &[&'a str]) -> Option<&'a str> { + let max_dist = match target.len() { + 0 => return None, + 1..=3 => 1, + 4..=7 => 2, + _ => 3, + }; + closest_match(target, candidates, max_dist) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_levenshtein_identical() { + assert_eq!(levenshtein("hello", "hello"), 0); + } + + #[test] + fn test_levenshtein_empty() { + assert_eq!(levenshtein("", "abc"), 3); + assert_eq!(levenshtein("abc", ""), 3); + assert_eq!(levenshtein("", ""), 0); + } + + #[test] + fn test_levenshtein_one_edit() { + assert_eq!(levenshtein("count", "conut"), 2); // transposition = 2 edits + assert_eq!(levenshtein("count", "counr"), 1); // substitution + assert_eq!(levenshtein("count", "coun"), 1); // deletion + assert_eq!(levenshtein("count", "counts"), 1); // insertion + } + + #[test] + fn test_levenshtein_multiple_edits() { + assert_eq!(levenshtein("kitten", "sitting"), 3); + } + + #[test] + fn test_closest_match_found() { + let candidates = vec!["count", "counter", "amount", "mount"]; + assert_eq!(closest_match("counr", &candidates, 2), Some("count")); + } + + #[test] + fn test_closest_match_too_far() { + let candidates = vec!["apple", "banana", "cherry"]; + assert_eq!(closest_match("xyz", &candidates, 2), None); + } + + #[test] + fn test_closest_match_exact_excluded() { + // Exact matches (distance 0) should be excluded since the name is already correct + let candidates = vec!["count", "counter"]; + assert_eq!(closest_match("count", &candidates, 2), Some("counter")); + } + + #[test] + fn test_suggest_name_short() { + let candidates = vec!["x", "y", "z", "a"]; + // 'b' is distance 1 from all candidates, so one will be returned + assert!(suggest_name("b", &candidates).is_some()); + } + + #[test] + fn test_suggest_name_medium() { + let candidates = vec!["counter", "count", "amount"]; + // 'contr' (len 5) allows max_dist=2; 'count' is dist 2 from 'contr' + let result = suggest_name("contr", &candidates); + assert!(result == Some("count") || result == Some("counter")); + } + + #[test] + fn test_suggest_name_empty() { + let candidates = vec!["x", "y"]; + assert_eq!(suggest_name("", &candidates), None); + } +} +``` + +Explain what this code does, function by function.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/explain2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/explain2.txt new file mode 100644 index 0000000..c7e5699 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/explain2.txt @@ -0,0 +1,144 @@ +<|im_start|>user +`src/decline.rs`: + +```rust +//===- decline.rs - Vx Compiler --------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Why the flat path gave up on a function. +// +// The flat lowerer declines whatever it cannot lower yet, and the AST path stays the oracle for +// that function. Declining is expected. Declining without saying why is what makes "how much of +// the language does the flat path carry" a reading exercise instead of a query. +// +// A leaf module: both the flattener and the flat emitter produce these, and the corpus sweep +// counts them. +// +//===----------------------------------------------------------------------===// + +use std::fmt; + +/// Why one function did not lower through the flat path. +/// +/// Every variant names something the flat path does not do *yet*. None of them is an error: a +/// declined function compiles through the AST path and produces the same MLIR. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum Decline { + /// An expression the flat lowerer has no case for. Carries the `Expr` variant name. + UnsupportedExpr(&'static str), + + /// A statement the flat lowerer has no case for. Carries the `Statement` variant name. + UnsupportedStmt(&'static str), + + /// A callee with no signature in the registry -- an ambiguous cross-module name dropped from + /// `fn_sigs`, or an unregistered symbol. + UnresolvedCallee(String), + + /// A builtin called with operands the flat path does not lower: the wrong arity, or a tensor + /// whose rank or element type the emitted kernel does not accept. + BuiltinShape { + builtin: &'static str, + why: &'static str, + }, + + /// A value whose lowered type is not the one this construct needs -- indexing something that + /// is not a pointer, taking a field of a nominal the flat path has no layout for. + TypeNotModelled { what: &'static str }, + + /// A construct the flat path lowers only in memory mode, reached in register mode. + NeedsMemoryMode { construct: &'static str }, + + /// Something the flat path does not lower yet that is none of the above. `what` is a short + /// fixed phrase, never a formatted value, so the histogram groups. + Unsupported { what: &'static str }, + + /// A gap in the flat *emitter* that has not been given a phrase of its own yet, naming the + /// source line that produced it. + /// + /// The emitter bails from roughly 190 places, most of which no corpus program has ever + /// reached. Writing a description for each up front would be 190 guesses about which ones + /// matter. Carrying the site instead means the histogram names the exact line to describe, + /// and only the lines something actually reaches get the work. + EmitterGap { site: &'static str }, +} + +impl Decline { + /// A stable key for grouping. Deliberately drops the payload of the variants that carry one: + /// a histogram of "unresolved callee `foo`, unresolved callee `bar`" answers nothing that + /// "unresolved callee x2" does not. + pub fn key(&self) -> &'static str { + match self { + Decline::UnsupportedExpr(_) => "unsupported-expr", + Decline::UnsupportedStmt(_) => "unsupported-stmt", + Decline::UnresolvedCallee(_) => "unresolved-callee", + Decline::BuiltinShape { .. } => "builtin-shape", + Decline::TypeNotModelled { .. } => "type-not-modelled", + Decline::NeedsMemoryMode { .. } => "needs-memory-mode", + Decline::Unsupported { .. } => "unsupported", + Decline::EmitterGap { .. } => "emitter-gap", + } + } + + /// The key plus the one detail that says *which* construct, for a histogram that names the + /// work rather than the category: `unsupported-expr(Closure)`. + pub fn detail_key(&self) -> String { + match self { + Decline::UnsupportedExpr(k) => format!("unsupported-expr({k})"), + Decline::UnsupportedStmt(k) => format!("unsupported-stmt({k})"), + Decline::UnresolvedCallee(_) => "unresolved-callee".to_string(), + Decline::BuiltinShape { builtin, .. } => format!("builtin-shape({builtin})"), + Decline::TypeNotModelled { what } => format!("type-not-modelled({what})"), + Decline::NeedsMemoryMode { construct } => format!("needs-memory-mode({construct})"), + Decline::Unsupported { what } => format!("unsupported({what})"), + Decline::EmitterGap { site } => format!("emitter-gap({site})"), + } + } +} + +impl fmt::Display for Decline { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Decline::UnsupportedExpr(k) => write!(f, "no flat lowering for the {k} expression"), + Decline::UnsupportedStmt(k) => write!(f, "no flat lowering for the {k} statement"), + Decline::UnresolvedCallee(n) => write!(f, "no signature for the callee '{n}'"), + Decline::BuiltinShape { builtin, why } => { + write!(f, "'{builtin}' called with {why}") + } + Decline::TypeNotModelled { what } => write!(f, "{what}"), + Decline::NeedsMemoryMode { construct } => { + write!(f, "{construct} lowers only in memory mode") + } + Decline::Unsupported { what } => write!(f, "no flat lowering for {what}"), + Decline::EmitterGap { site } => write!(f, "an emitter gap at {site}"), + } + } +} + +/// What a lowering step returns: the value, or the reason the flat path gave up. +pub type Lowered = Result; + +/// An emitter bail-out that has no phrase of its own yet, stamped with where it is. +/// +/// A macro rather than a function so `line!()` expands at the bail site. +#[macro_export] +macro_rules! emitter_gap { + () => { + $crate::decline::Decline::EmitterGap { + site: concat!(file!(), ":", line!()), + } + }; +} +``` + +Explain what this code does, function by function.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/explain3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/explain3.txt new file mode 100644 index 0000000..dd94476 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/explain3.txt @@ -0,0 +1,236 @@ +<|im_start|>user +`src/error.rs`: + +```rust +//===- error.rs - Vx Compiler ----------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines the error handling and diagnostic reporting infrastructure. +// It provides formatting routines to display rich compiler errors with source code +// snippets, line numbers, and colorful annotations to help developers quickly +// identify and resolve syntax or semantic issues. +// +//===----------------------------------------------------------------------===// + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Error(pub String); + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0) + } +} + +/// Render an error with the source line it points at and a caret under the place. `file` is +/// printed before the line and column, as `file:line:column`, when the source came from one. +pub fn format_compiler_error( + source: &str, + file: Option<&str>, + line: usize, + col: usize, + len: usize, + msg: &str, +) -> String { + if line > 0 { + if let Some(src_line) = source.lines().nth(line - 1) { + let mut out = String::with_capacity(msg.len() + src_line.len() * 2 + 64); + use std::fmt::Write; + match file { + Some(file) => { + let _ = writeln!(out, "Error at {}:{}:{}: {}", file, line, col, msg); + } + None => { + let _ = writeln!(out, "Error at {}:{}: {}", line, col, msg); + } + } + + out.push_str(src_line); + out.push('\n'); + + let mut pointer = String::new(); + for (i, c) in src_line.chars().enumerate() { + if i < col - 1 { + if c == '\t' { + pointer.push('\t'); + } else { + pointer.push(' '); + } + } else { + break; + } + } + + // Replace up to 4 trailing spaces with tildes for better visual anchoring + let mut prefix_tildes = 0; + while prefix_tildes < 4 && pointer.ends_with(' ') { + pointer.pop(); + prefix_tildes += 1; + } + for _ in 0..prefix_tildes { + pointer.push('~'); + } + + for _ in 0..len { + pointer.push('^'); + } + pointer.push_str("~~~~"); + out.push_str(&pointer); + out.push('\n'); + return out; + } + } + + // Fallback if line is out of bounds + match file { + Some(file) => format!("Error at {}:{}:{}: {}\n", file, line, col, msg), + None => format!("Error at {}:{}: {}\n", line, col, msg), + } +} + +pub fn format_compiler_warning( + source: &str, + line: usize, + col: usize, + len: usize, + code: Option, + msg: &str, +) -> String { + let code_str = match code { + Some(c) => format!("[{}]", c), + None => String::new(), + }; + + if line > 0 { + if let Some(src_line) = source.lines().nth(line - 1) { + let mut out = String::with_capacity(msg.len() + src_line.len() * 2 + 64); + use std::fmt::Write; + let _ = writeln!(out, "Warning{} at {}:{}: {}", code_str, line, col, msg); + + out.push_str(src_line); + out.push('\n'); + + let mut pointer = String::new(); + for (i, c) in src_line.chars().enumerate() { + if i < col - 1 { + if c == '\t' { + pointer.push('\t'); + } else { + pointer.push(' '); + } + } else { + break; + } + } + + // Replace up to 4 trailing spaces with tildes for better visual anchoring + let mut prefix_tildes = 0; + while prefix_tildes < 4 && pointer.ends_with(' ') { + pointer.pop(); + prefix_tildes += 1; + } + for _ in 0..prefix_tildes { + pointer.push('~'); + } + + for _ in 0..len { + pointer.push('^'); + } + pointer.push_str("~~~~"); + out.push_str(&pointer); + out.push('\n'); + return out; + } + } + + // Fallback if line is out of bounds + format!("Warning{} at {}:{}: {}\n", code_str, line, col, msg) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_format_compiler_error_len_1_with_padding() { + // " + " (col = 5) + let source = " + "; + let formatted = format_compiler_error(source, None, 1, 5, 1, "Expected operand"); + + // Should produce: + // Error at 1:5: Expected operand + // + + // ~~~~^~~~~ + let expected = "Error at 1:5: Expected operand\n + \n~~~~^~~~~\n"; + assert_eq!(formatted, expected); + } + + #[test] + fn test_format_compiler_error_len_1_no_padding() { + // "+ " (col = 1) + let source = "+ "; + let formatted = format_compiler_error(source, None, 1, 1, 1, "Unexpected"); + + // Should produce: + // Error at 1:1: Unexpected + // + + // ^~~~~ + let expected = "Error at 1:1: Unexpected\n+ \n^~~~~\n"; + assert_eq!(formatted, expected); + } + + #[test] + fn test_format_compiler_error_len_4() { + // "asdf" (col = 1) + let source = "asdf"; + let formatted = format_compiler_error(source, None, 1, 1, 4, "Unknown identifier"); + + // Should produce: + // Error at 1:1: Unknown identifier + // asdf + // ^^^^~~~~ + let expected = "Error at 1:1: Unknown identifier\nasdf\n^^^^~~~~\n"; + assert_eq!(formatted, expected); + } + + #[test] + fn test_format_compiler_error_len_4_with_padding() { + // " asdf" (col = 5) - full 4 spaces of padding + let source = " asdf"; + let formatted = format_compiler_error(source, None, 1, 5, 4, "Unknown identifier"); + + // Should produce: + // Error at 1:5: Unknown identifier + // asdf + // ~~~~^^^^~~~~ + let expected = "Error at 1:5: Unknown identifier\n asdf\n~~~~^^^^~~~~\n"; + assert_eq!(formatted, expected); + } + + #[test] + fn test_format_compiler_error_len_4_with_partial_padding() { + // " asdf" (col = 3) - only 2 spaces of padding available to replace + let source = " asdf"; + let formatted = format_compiler_error(source, None, 1, 3, 4, "Unknown identifier"); + + // Should produce: + // Error at 1:3: Unknown identifier + // asdf + // ~~^^^^~~~~ + let expected = "Error at 1:3: Unknown identifier\n asdf\n~~^^^^~~~~\n"; + assert_eq!(formatted, expected); + } +} +``` + +Explain what this code does, function by function.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/write1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/write1.txt new file mode 100644 index 0000000..a9a637f --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/write1.txt @@ -0,0 +1,8 @@ +<|im_start|>user +Write a Python module with a class LRUCache that has get, put and a capacity, built on OrderedDict. Add pytest tests for it.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/write2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/write2.txt new file mode 100644 index 0000000..2b5a941 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/write2.txt @@ -0,0 +1,8 @@ +<|im_start|>user +Write a C function `int parse_csv_line(const char *line, char **fields, int max_fields)` that handles quoted fields and doubled quotes inside them. Add a main() that tests it.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/write3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/write3.txt new file mode 100644 index 0000000..3f4730e --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/write3.txt @@ -0,0 +1,8 @@ +<|im_start|>user +Write a Rust struct RingBuffer with new, push, pop, len, is_empty and an iterator. Add unit tests.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/complete1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/complete1.txt new file mode 100644 index 0000000..14de931 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/complete1.txt @@ -0,0 +1,129 @@ +<|im_start|>user +`src/report.rs`: + +```rust +//===- report.rs - Vx Compiler ---------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// What the memory-algebra analysis found, in the shape a consumer reads it in: resident sets, +// transfer routes and their costs, and counted traffic. +// +// These are the checker's output, not the checker's working state, which is why they live outside +// hir/. --diagnostics-json is a report format, and a report format that imports the type checker's +// internals cannot change without the checker changing too. +// +//===----------------------------------------------------------------------===// + +/// One memory space's working set for a function: the granule-rounded sum of the tiles placed +/// there, against the space's declared capacity. Recorded for *every* placed space, not only +/// those that overflow — an admitted program emits no capacity diagnostic, so this is the only +/// place its resident total appears. Downstream that total is what turns a capacity verdict into +/// an engine's required memory utilization (#285). See [`crate::hir::env::TypeChecker::resident_sets`]. +#[derive(Debug, Clone, PartialEq)] +pub struct ResidentSet { + pub space: crate::syntax::MemorySpace, + /// The device whose copy of the space this is (`Card[1]`), when the space is the memory of a + /// topology with more than one device. Each device has its own copy and its own working set. + pub device: Option, + /// Granule-rounded sum of tiles placed in this space by one function. + pub total_bytes: u64, + pub capacity_bytes: u64, + pub tiles: usize, + /// Whether the space is declared `overcommit` (an overflow is W1028, not E6010). + pub overcommit: bool, +} + +/// A resolved `transfer`: the chain of memory spaces the value actually moves through and the +/// declared cost of each hop. A direct transfer has one hop; a multi-hop route (synthesized when +/// no direct edge exists) has one per staging step. `derived_cost` is the bandwidth-roofline cost +/// when the declarations make it computable, which is what the emitted `vx.transfer` carries. +/// See [`crate::hir::env::TypeChecker::staging_routes`] (#282). +#[derive(Debug, Clone, PartialEq)] +pub struct StagingRoute { + /// The spaces traversed, source first: `[CPU_DRAM, HBM3e, SMEM]`. + pub path: Vec, + /// Per-edge declared cost, one shorter than `path`; `None` for an edge with no declared cost. + pub edge_costs: Vec>, + /// The cost graph's total for the whole route. + pub total_cost: u32, + /// Bandwidth-derived (roofline) cost, when the declarations supply bandwidths. + /// + /// `u64`, not `u32`: a picosecond-resolution time cost overflows `u32` at 4.3 ms, which a + /// multi-gigabyte host transfer exceeds, and a saturated cost would read as a slow transfer + /// rather than a missing one. + pub derived_cost: Option, + /// Bytes this transfer moves, when the shape is statically known. + /// + /// Without it a harvested cost cannot be interpreted: "260064 ps" is not a prediction unless + /// the size it is a cost *of* travels with it, and comparing predicted against measured needs + /// both. `None` for a dynamically-shaped tensor, where no cost is derivable either. + pub bytes: Option, + /// Which cost source produced `derived_cost`. The two are mutually exclusive per edge (E6013), + /// so this names the one that applied rather than a precedence winner — and it is what tells a + /// consumer whether a residual is attributable to a declared link figure or to an inferred + /// containment roofline. + pub cost_source: Option, + /// The unit `derived_cost` is in — cycles, or picoseconds. Carried rather than dropped because + /// one program's routes legitimately mix them: an on-die hop declared `B/cyc` and a host link + /// declared `GB/s` produce costs of different *dimension*, and a harvested prediction that does + /// not say which is not a prediction. (The fleet's `HBM->L2` and `L2->SMEM` are exactly this + /// pair.) + pub derived_unit: Option, + /// Which composition law priced a containment route: `sum` or `bottleneck`. + /// + /// `None` for a link-rate hop, which has one leg and so composes nothing. Carried because the + /// two laws differ by ~2x on a multi-hop walk and a harvested prediction that does not say + /// which one applied cannot be re-scored later -- the same reason `derived_unit` is carried. + pub composition: Option, + /// Bytes moved per space, derived from code (#353). `None` when the movement cannot be + /// counted statically, in which case `traffic_absent_reason` says why -- a guess here would + /// be indistinguishable from a measurement in the record a campaign harvests, which is the + /// same reason `derived_cost` is `None` rather than 0 when no bandwidth is declared. + pub traffic: Option, + /// Why `traffic` is `None`. `None` when traffic is present. + pub traffic_absent_reason: Option, +} + +/// Bytes read and written against one placed buffer by a `spawn` region (#353). +/// +/// Per BUFFER, not just per space, because the amplification this stage exists to show is a +/// fact about a particular tensor: a streamed operand is re-read on every outer iteration +/// while the blocked one is read once. Summed into their shared space they +/// become one number that hides which of them is the problem. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BufferTraffic { + pub buffer: String, + pub space: crate::syntax::MemorySpace, + pub read_bytes: u64, + pub written_bytes: u64, +} + +/// What one `spawn on(...)` region moves, counted from its indexed accesses and the static +/// trip counts of the loops around them (#353). +/// +/// The transfer-hop counts say what it costs to GET a tile to a space. This says what the +/// kernel then does with it, which is where re-reading lives: a tile staged once and read +/// sixteen times is sixteen reads, and no declared edge cost can say so because the movement +/// across the edge happened exactly once. +#[derive(Debug, Clone, PartialEq)] +pub struct SpawnRegionTraffic { + /// The function the `spawn` appears in. + pub function: String, + /// The topology the region runs on, as its display name. + pub topology: String, + /// Aggregate per space, or `None` when the region could not be counted exactly. + pub traffic: Option, + /// Per placed buffer, sorted by name. Empty when `traffic` is `None`. +``` + +This file stops in the middle. Continue it from exactly where it stops. Output only the rest of the file.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/complete2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/complete2.txt new file mode 100644 index 0000000..24b2590 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/complete2.txt @@ -0,0 +1,145 @@ +<|im_start|>user +`scripts/tools/check_doc_examples.py`: + +```python +#!/usr/bin/env python3 +"""Compile every Vx example in the documentation. + +Documentation drifts silently because nothing executes it. An audit of this repository found the +README's own headline example did not parse, a tutorial teaching a topology syntax that was never +implemented, `grad` documented with the wrong arity, and a grammar production admitting two types +the parser rejects. Every one of those had been correct when written. + +This makes that class of error a build failure. + + python3 scripts/tools/check_doc_examples.py # check everything + python3 scripts/tools/check_doc_examples.py --list # show what would be checked + python3 scripts/tools/check_doc_examples.py README.md # check specific files + +A block is checked when it is fenced ```vx or ```rust, contains a top-level declaration, and is +not skipped by one of the rules below. To exempt a block deliberately, put + + + +on the line before its fence, ideally with a reason. + +Most blocks are only parsed. A block marked + + + +is compiled and run instead, and what it prints must equal the ```text block that follows it +(one short line, such as "It prints:", may come between them). + +The hand-written pages under `www/` are checked as well, through their `
` blocks. The
+landing page carries the most-read Vx code on the site and was the only code on it that nothing
+compiled -- everything in the book is covered because the book is markdown. The same skip comment
+works there, on the line before the `
`.
+
+Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions.
+See LICENSE for license information.
+SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+"""
+
+import html
+import os
+import re
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+FENCE = re.compile(
+    r"(?:\s*\n)?```(vx|rust)\n(.*?)```", re.S
+)
+# The expected output, after at most one short line such as "It prints:".
+OUTPUT = re.compile(r"\s*(?:[^`\n]+\n\s*)?```text\n(.*?)```", re.S)
+
+# The same idea for the hand-written pages: a 
 block, optionally preceded by the skip
+# comment. Their code carries syntax highlighting as  tags, which are stripped before the
+# body is compiled.
+HTML_BLOCK = re.compile(
+    r"(?:()\s*\n?\s*)?
(.*?)
", re.S +) +TAG = re.compile(r"<[^>]+>") + +# A block has to declare something to be a compilable unit. Bare statements are illustrative +# fragments and are left alone. +DECLARES = re.compile(r"^\s*(fn |pub fn |unsafe fn |safe fn |struct |enum |trait |impl |extern |macro_rules!|Memory |Topology )", re.M) + +# Constructs that exist in Rust and not in Vx. Architecture documents embed compiler internals in +# ```rust fences, and those are Rust, not examples of the language. +RUST_ONLY = re.compile( + r"^\s*use\s+\w|#\[|#!\[|\bpub\s+(struct|enum|mod|const|trait)\b|\bcrate::|" + r"&self\b|&mut self\b|\bimpl\s+\w+\s+for\s+\w+\s*\{[^}]*fn\s+\w+\s*\(\s*&|" + # Types and idioms from the standard Rust library that Vx has no equivalent of. The + # architecture documents embed real compiler internals, and these are what give them away. + r"\bArc<|\bRc<|\bWeak<|\bRefCell<|\bMutex<|\bRwLock<|\bBox +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/complete3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/complete3.txt new file mode 100644 index 0000000..402843f --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/complete3.txt @@ -0,0 +1,135 @@ +<|im_start|>user +`src/session.rs`: + +```rust +//===- session.rs - Vx Compiler --------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines the core compiler session and local worker states. +// It orchestrates the compilation pipeline across multiple threads, managing shared +// diagnostics, module registries, and global state required during the lowering +// of Vx source code to MLIR. +// +//===----------------------------------------------------------------------===// +use crate::bytecode::HirInstruction; +use crate::gid::{TypeId, UnboundedFunctionMetadata}; +use std::sync::Arc; + +// The frozen nominal-type registry (layouts + module indices + cycle-checked). Built once per +// compilation at the Phase 2 freeze point and shared read-only across worker threads. Re-exported +// here so `GlobalSession` and the verifier name it via `session`, but the type lives in `registry`. +pub use crate::registry::ImmutableGlobalRegistry; + +/// Represents the frozen past of the compilation process. +/// It contains everything compiled before the current phase. +/// +/// # Data-Oriented Design (DOD) Constraints +/// This session deliberately separates dynamic compiler metadata into strictly +/// typed, homogeneous arenas rather than using a single polymorphic `Enum` array +/// (e.g., `enum SlowPathData { Function(...), Generics(...) }`). +/// +/// 1. **Cache-Line Density**: `UnboundedFunctionMetadata` is a dense structure of `u64` +/// bitfields. Iterating over it is highly predictable. `Vec`, however, +/// is a heap-allocated fat pointer with variable lengths. Mixing them would introduce +/// unpredictable struct padding and pointer-chasing overhead. +/// 2. **Hardware Prefetching**: By keeping `generics_arena` separate, the CPU's spatial +/// prefetcher can stream through the dense `slow_path_arena` at maximum bandwidth +/// during the critical lifetime subtyping pass, without stalling on scattered `Vec` pointers. +pub struct GlobalSession { + pub epoch: u64, + /// How this compilation forms a generic instantiation's identity. + /// + /// A per-compilation fact, frozen with the rest of the epoch, because that is what it is: two + /// compilations in one process may legitimately want different strategies, and a worker must + /// not be able to observe a choice that belongs to someone else's compile. It lived in a + /// process-global until Vx#381 -- set from `--intern-mode` on one thread and read by every + /// worker from inside the parallel type-check. + pub intern_mode: crate::intern_mode::InternMode, + /// `-fauto-schedule-levels`: an `across` loop on an arch that cannot launch its levels runs + /// as a plain `for` that carries its level, instead of E6032. + pub auto_schedule_levels: bool, + pub registry: Arc, + + /// The dense, homogeneous arena for complex parameter and lifetime evaluation. + /// Accessed heavily during Phase 1 type-checking and borrow checking. + pub slow_path_arena: Arc>, + + /// The heterogeneous arena for structural generic instantiations. + /// Separated to prevent cache fragmentation in the `slow_path_arena`. + pub generics_arena: Arc>, + pub generics_offsets: Arc>, +} + +impl GlobalSession { + /// A session with an *empty* frozen registry — for callers that don't build one (the + /// sequential driver, unit tests). The parallel pipeline uses [`Self::with_registry`]. + pub fn new(epoch: u64) -> Self { + Self::with_registry( + epoch, + ImmutableGlobalRegistry::build_and_validate(Vec::new()) + .expect("an empty registry is always valid"), + ) + } + + /// A session holding the frozen registry built at the Phase 2 freeze point. + pub fn with_registry(epoch: u64, registry: ImmutableGlobalRegistry) -> Self { + Self { + epoch, + intern_mode: crate::intern_mode::InternMode::Deferred, + auto_schedule_levels: false, + registry: Arc::new(registry), + slow_path_arena: Arc::new(Vec::new()), + generics_arena: Arc::new(Vec::new()), + generics_offsets: Arc::new(Vec::new()), + } + } + + /// The same session with a chosen interning strategy. Consuming rather than a setter, because + /// the session is frozen once it is shared: every worker holds an `Arc` of it and reads it by + /// `&`, so it must be settled before it is wrapped. + pub fn in_intern_mode(mut self, mode: crate::intern_mode::InternMode) -> Self { + self.intern_mode = mode; + self + } + + /// The same session with `-fauto-schedule-levels` on or off. + pub fn auto_schedule_levels(mut self, on: bool) -> Self { + self.auto_schedule_levels = on; + self + } +} + +/// Represents the mutable present of a single worker thread during Phase 1. +pub struct LocalWorkerState { + pub global: Arc, + + // Completely lock-free, thread-local mutation + pub local_slow_path_arena: Vec, + pub local_generics_arena: Vec, + pub local_generics_offsets: Vec<(usize, usize)>, + + // The flat arrays replacing the AST + pub local_type_stream: Vec, // array of 256-bit GIDs + pub local_hir_stream: Vec, + + /// Tensor-type side table: `GID -> (element, shape)` for every tensor type this function's stream + /// references. Tensor GIDs are content hashes (not invertible) and tensors are structural (never + /// in the nominal registry), so codegen can't reconstruct a tensor's memref type from the stream + /// alone -- most acutely for `TensorAlloc`. The lowerer records it here as it emits tensor values; + /// the flat codegen consumes it (the tensor analogue of the registry's struct `layouts`). + pub local_tensor_types: Vec<(TypeId, crate::syntax::ElementType, Vec)>, + + /// String side table: the string-literal bytes for each `PrintStr` this function's stream emits, +``` + +This file stops in the middle. Continue it from exactly where it stops. Output only the rest of the file.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/edit1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/edit1.txt new file mode 100644 index 0000000..d90c707 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/edit1.txt @@ -0,0 +1,182 @@ +<|im_start|>user +`scripts/tools/gen_error_index.py`: + +```python +#!/usr/bin/env python3 +"""Generate the diagnostic index from the compiler's own diagnostic table. + +`src/diagnostic.rs` is the single place every code is declared, each with a doc comment saying +what it means and a section header grouping it. That makes it the only honest source for a +reference: a hand-written index drifts the moment someone adds a code, and 78 of the 113 codes +were undocumented anywhere before this existed. + + python3 scripts/tools/gen_error_index.py # write the index + python3 scripts/tools/gen_error_index.py --check # fail if it is out of date + +Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +See LICENSE for license information. +SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +""" + +import re +import subprocess +import sys +from pathlib import Path + +SOURCE = Path("src/diagnostic.rs") +OUTPUT = Path("www/book/src/error-index.md") + +# The section headers in diagnostic.rs are terse. These say what the stage actually does, so the +# index reads as a guide rather than as a dump of the enum. +SECTION_BLURB = { + "Warnings": "Reported without stopping the compile. A warning means the program is accepted " + "but something in it is probably not what was intended.", + "Parser Errors": "Raised while turning source text into an AST. The program is not " + "syntactically valid Vx.", + "Name Resolution Errors": "Raised when a name cannot be resolved to a declaration, or " + "resolves to something of the wrong kind.", + "Type Errors": "Raised by the type checker. Vx performs no implicit numeric conversion, so " + "many of these are mismatches that a language with coercion would have silently accepted.", + "Borrow/Ownership Errors": "Raised by the borrow checker and the linear-type rules. These " + "rule out use-after-move, aliasing violations and lifetimes that outlive what they point at.", + "Safety Errors": "Raised where an operation needs an `unsafe` context and does not have one.", + "Topology/Hardware Errors": "Raised by the placement and capacity rules — the checks that " + "make Vx different from a single-address-space language. A value in the wrong memory space, " + "a region on the wrong device, a working set that does not fit, or a transfer with no " + "declared route.", + "Tensor/Math Errors": "Raised on tensor shapes and numeric operations, including shape " + "mismatches that are decided at compile time.", + "Contract/Verification Errors": "Raised when a `requires`, `ensures` or `invariant` clause " + "cannot be discharged, or when a seam obligation is left unproven.", +} + +HEADER = """# Diagnostic index + +Every code that the Vx compiler defines, and what it means. Some codes, among them the parser's +`E1xxx` codes, do not appear in the compiler's messages yet +([Vx#3227](https://github.com/vx-lang/Vx/issues/3227)). + +Codes are grouped by the compilation stage that raises them, and the group is readable off the +number: `E1xxx` is the parser, `E3xxx` the type checker, `E6xxx` the placement and capacity rules, +and so on. A `W` prefix is a warning rather than an error. + +> This file is generated from `src/diagnostic.rs` by `scripts/tools/gen_error_index.py`. Edit the +> doc comments on the codes there, not this file. + +Every code below links to its own page, which carries the message the compiler emits and, where +the test suite has one, a program that triggers it. + +""" + + +def parse(source_text): + """Yield (section, code, description) in declaration order.""" + section = None + pending = [] + + for line in source_text.splitlines(): + stripped = line.strip() + + header = re.match(r"//\s*---\s*(.+?)\s*\((?:[EW]\dxxx)\)\s*---", stripped) + if header: + section = header.group(1) + pending = [] + continue + + doc = re.match(r"///\s?(.*)", stripped) + if doc: + pending.append(doc.group(1).strip()) + continue + + code = re.match(r"^([EW][0-9]{4}),$", stripped) + if code: + yield section, code.group(1), " ".join(p for p in pending if p).strip() + pending = [] + continue + + # Anything else (attributes, blank lines, the enum braces) resets the doc buffer only if + # it is a real statement; blank lines inside a doc block are kept. + if stripped and not stripped.startswith("#"): + pending = [] + + +def render(entries): + out = [HEADER] + by_section = {} + for section, code, desc in entries: + by_section.setdefault(section or "Uncategorised", []).append((code, desc)) + + out.append("## Contents\n") + for section in by_section: + anchor = section.lower().replace(" ", "-").replace("/", "") + codes = [c for c, _ in by_section[section]] + out.append(f"- [{section}](#{anchor}) — `{codes[0]}`–`{codes[-1]}` ({len(codes)} codes)") + out.append("") + + for section, items in by_section.items(): + out.append(f"## {section}\n") + blurb = SECTION_BLURB.get(section) + if blurb: + out.append(f"{blurb}\n") + out.append("| Code | Meaning |") + out.append("| --- | --- |") + for code, desc in items: + # Each code also has a page of its own at vxlang.org/errors/, with the message and a + # program that triggers it. Root-relative, so mdBook leaves it alone. + out.append(f"| [`{code}`](/errors/{code}/) | {desc or '—'} |") + out.append("") + + total = sum(len(v) for v in by_section.values()) + out.append("______________________________________________________________________\n") + out.append(f"{total} diagnostics.\n") + return "\n".join(out) + + +def main(): + if not SOURCE.exists(): + print(f"error: {SOURCE} not found; run from the repository root", file=sys.stderr) + return 1 + + entries = list(parse(SOURCE.read_text())) + if not entries: + print("error: no diagnostic codes parsed -- has the table's shape changed?", file=sys.stderr) + return 1 + + rendered = render(entries) + + # Matches the shape mdformat produces, so the generated file needs no follow-up pass. + + try: + rendered = subprocess.run( + ["mdformat", "-"], input=rendered, capture_output=True, text=True, check=True + ).stdout + except (FileNotFoundError, subprocess.CalledProcessError): + pass # mdformat is optional locally; CI has it. + + if "--check" in sys.argv: + current = OUTPUT.read_text() if OUTPUT.exists() else "" + if current != rendered: + print( + f"error: {OUTPUT} is out of date.\n" + f" Run: python3 {Path(__file__).as_posix()}", + file=sys.stderr, + ) + return 1 + print(f"{OUTPUT} is up to date ({len(entries)} diagnostics)") + return 0 + + OUTPUT.write_text(rendered) + print(f"wrote {OUTPUT} ({len(entries)} diagnostics)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) +``` + +Add a type hint to every function parameter and return value. Output the whole file, and change nothing else.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/edit2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/edit2.txt new file mode 100644 index 0000000..a8d2349 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/edit2.txt @@ -0,0 +1,151 @@ +<|im_start|>user +`src/hash.rs`: + +```rust +//===- hash.rs - Vx Compiler -----------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file provides specialized, stable hashing utilities for the compiler. +// It implements robust hash generation for type IDs, module signatures, and +// anonymous structural types, ensuring consistent symbol mangling and metadata +// serialization across incremental builds. +// +//===----------------------------------------------------------------------===// +/// 64-bit FNV-1a parameters (standard offset basis + prime). FNV is **project-controlled and stable +/// across toolchains** — unlike `FxHasher`/`DefaultHasher`, whose algorithms may change between +/// library/compiler releases. GID word 0/1 are content hashes that must reproduce byte-for-byte +/// across builds and machines (reproducible builds, cross-crate identity), so the algorithm cannot +/// be an unpinned dependency. This mirrors the FNV scheme `arch.rs` already hand-rolls for dispatch +/// ids, for the same reason. See #195. FNV-1a is *not* cryptographic: accidental collisions are +/// negligible but not impossible, so `ImmutableGlobalRegistry::build_and_validate` additionally +/// rejects any two distinct symbols that land on the same GID. +const FNV_OFFSET_BASIS_64: u64 = 0xcbf2_9ce4_8422_2325; +const FNV_PRIME_64: u64 = 0x0000_0100_0000_01b3; + +/// Streaming 64-bit FNV-1a: fold `bytes` into a running `hash` (seeded with the offset basis on the +/// first call, then chained) so multi-field def paths hash deterministically as one stream. +#[inline] +fn fnv1a_64(hash: u64, bytes: &[u8]) -> u64 { + let mut hash = hash; + for b in bytes { + hash ^= *b as u64; + hash = hash.wrapping_mul(FNV_PRIME_64); + } + hash +} + +/// Computes the stable 64-bit content hash (GID word 0) for a given module path. +pub fn compute_module_hash(module_path: &str) -> u64 { + fnv1a_64(FNV_OFFSET_BASIS_64, module_path.as_bytes()) +} + +/// Represents the stable topological path to a definition (struct, enum, closure). +/// This prevents incremental compilation breakage when anonymous types are re-ordered. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum DefPath<'a> { + /// A named, top-level symbol (e.g., `MyStruct`). + Named(&'a str), + /// An anonymous closure or comptime block, defined by its structural layout + /// or its position within a specific parent item, rather than file line number. + Anonymous { + parent_hash: u64, + structural_hash: u64, + }, +} + +impl<'a> DefPath<'a> { + /// Computes the deterministic 64-bit Word 1 for the TypeId (stable FNV-1a; see [`fnv1a_64`]). + pub fn compute_symbol_hash(&self) -> u64 { + match self { + DefPath::Named(name) => { + // 0 is the discriminator for Named. + let h = fnv1a_64(FNV_OFFSET_BASIS_64, &[0u8]); + fnv1a_64(h, name.as_bytes()) + } + DefPath::Anonymous { + parent_hash, + structural_hash, + } => { + // 1 is the discriminator for Anonymous; fold the two u64 fields in a fixed byte + // order so the hash is architecture-independent. + let mut h = fnv1a_64(FNV_OFFSET_BASIS_64, &[1u8]); + h = fnv1a_64(h, &parent_hash.to_le_bytes()); + fnv1a_64(h, &structural_hash.to_le_bytes()) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Pins the exact algorithm + constants (#195). These are FNV-1a-64 golden values computed + /// independently; if the hash ever silently changes (e.g. someone swaps back to a std hasher), + /// every previously emitted GID / serialized metadata would break, and this catches it. + #[test] + fn hash_is_stable_fnv1a_golden_values() { + assert_eq!(compute_module_hash("crate::a"), 0xdbc1_8e8e_2c15_a207); + assert_eq!( + DefPath::Named("Foo").compute_symbol_hash(), + 0xed6f_617e_4534_5949 + ); + } + + /// Empty input hashes to the bare offset basis (the FNV-1a identity) — a sanity anchor on the + /// seeding. + #[test] + fn empty_module_path_is_offset_basis() { + assert_eq!(compute_module_hash(""), FNV_OFFSET_BASIS_64); + } + + #[test] + fn test_named_defpath_stability() { + let path1 = DefPath::Named("MyStruct"); + let path2 = DefPath::Named("MyStruct"); + assert_eq!(path1.compute_symbol_hash(), path2.compute_symbol_hash()); + + let path3 = DefPath::Named("OtherStruct"); + assert_ne!(path1.compute_symbol_hash(), path3.compute_symbol_hash()); + } + + #[test] + fn test_anonymous_defpath_stability() { + let parent = DefPath::Named("ParentFn").compute_symbol_hash(); + + let anon1 = DefPath::Anonymous { + parent_hash: parent, + structural_hash: 0x12345678, + }; + + let anon2 = DefPath::Anonymous { + parent_hash: parent, + structural_hash: 0x12345678, + }; + + assert_eq!(anon1.compute_symbol_hash(), anon2.compute_symbol_hash()); + + let anon_different_structure = DefPath::Anonymous { + parent_hash: parent, + structural_hash: 0x87654321, + }; + + assert_ne!( + anon1.compute_symbol_hash(), + anon_different_structure.compute_symbol_hash() + ); + } +} +``` + +Add a `///` doc comment above every function that has none. Output the whole file, and change nothing else.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/edit3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/edit3.txt new file mode 100644 index 0000000..6b9b566 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/edit3.txt @@ -0,0 +1,206 @@ +<|im_start|>user +`runtime/vx_mlir_shims.c`: + +```c +/*===- vx_mlir_shims.c - Vx Compiler ------------------------------*- C -*-===*\ +|* *| +|* Part of the Vx Project, under the Apache License v2.0 with LLVM *| +|* Exceptions. *| +|* See LICENSE for license information. *| +|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| +|* *| +\*===----------------------------------------------------------------------===*/ +/* The half-precision memref printers MLIR does not export in the form emitted + * code calls. + * + * `libmlir_runner_utils` exports printMemrefF32, F64, I32 and I64 both plainly + * and packed as `_mlir_ciface_*`, but the half-precision printers ONLY packed + * -- `nm` on MLIR 22 shows `_mlir_ciface_printMemrefBF16` and no plain + * `printMemrefBF16`. Codegen emits the plain call, so a bf16 program could not + * link, run, or emit an object. Its RUN line only emits MLIR, so nothing + * noticed. + * + * `llvm.emit_c_interface` on the declaration does not fix it: MLIR then gives + * the function a body and the ExecutionEngine wants `_mlir_printMemrefBF16` + * instead, which no library exports either. Supplying the plain symbol here is + * what closes it, and it belongs beside the runtime rather than in vx_std_core + * -- the standard library has no MLIR dependency and should not gain one to + * print a tensor. + * + * MLIR's unpacked convention for `memref<*xT>` passes (rank, pointer to the + * ranked descriptor). The packed entry point takes a pointer to exactly that + * pair. + */ + +#include +#include +#include +#include + +typedef struct { + int64_t rank; + void *descriptor; +} VxUnrankedMemRef; + +extern void _mlir_ciface_printMemrefBF16(void *unranked); +extern void _mlir_ciface_printMemrefF16(void *unranked); +extern void _mlir_ciface_printMemrefI8(void *unranked); +extern void _mlir_ciface_printMemrefI16(void *unranked); + +void printMemrefBF16(int64_t rank, void *descriptor) { + VxUnrankedMemRef packed = {rank, descriptor}; + _mlir_ciface_printMemrefBF16(&packed); +} + +void printMemrefF16(int64_t rank, void *descriptor) { + VxUnrankedMemRef packed = {rank, descriptor}; + _mlir_ciface_printMemrefF16(&packed); +} + +/* The integer tensor printers MLIR does not supply in the form codegen calls, + * or prints wrongly. MLIR has no unsigned integer type: a `u32` tensor is a + * memref of `i32`, and MLIR's printMemrefI32 reads 4000000000 as -294967296. + * printMemrefU8/U16/U32/U64 read the elements unsigned. printMemrefI8 cannot + * use MLIR's printer at all -- it prints each element as a character (`100` + * prints as `d`) -- so it is ours, reading the bytes signed like a scalar + * `i8`. All of them print the header line and the brackets, spaces and commas + * of MemRefDataPrinter in MemRefUtils.h, so the text does not depend on which + * printer a type chose. + */ + +typedef struct { + void *allocated; + void *aligned; + int64_t offset; + int64_t sizes_and_strides[]; +} VxRankedMemRef; + +static void vx_print_spaces(int64_t count) { + for (int64_t i = 0; i < count; ++i) + putchar(' '); +} + +/* The compiler sends only the element kinds that vx_print_element prints, so + * any other kind is a compiler bug. The program stops in every build: an + * `assert` is compiled out when NDEBUG is set, and the tensor would then print + * wrong values or none. */ +_Noreturn static void vx_no_element_printer(int bytes, int is_signed) { + fprintf(stderr, "[Vx] FATAL: no printer for a %d-byte %s tensor element\n", + bytes, is_signed ? "signed" : "unsigned"); + abort(); +} + +/* `bytes` is the element size. The signed branch is only for `i8`: MLIR prints + * `i16` itself, and the wide signed types keep MLIR's own printers. */ +static void vx_print_element(const void *base, int64_t at, int bytes, + int is_signed) { + if (is_signed) { + if (bytes != 1) + vx_no_element_printer(bytes, is_signed); + printf("%d", (int)((const int8_t *)base)[at]); + return; + } + switch (bytes) { + case 1: + printf("%u", (unsigned)((const uint8_t *)base)[at]); + return; + case 2: + printf("%u", (unsigned)((const uint16_t *)base)[at]); + return; + case 4: + printf("%" PRIu32, ((const uint32_t *)base)[at]); + return; + case 8: + printf("%" PRIu64, ((const uint64_t *)base)[at]); + return; + } + vx_no_element_printer(bytes, is_signed); +} + +static void vx_print_data(const void *base, int bytes, int is_signed, + int64_t dim, int64_t rank, int64_t offset, + const int64_t *sizes, const int64_t *strides) { + if (dim == 0) { + vx_print_element(base, offset, bytes, is_signed); + return; + } + printf("["); + vx_print_data(base, bytes, is_signed, dim - 1, rank, offset, sizes + 1, + strides + 1); + if (sizes[0] <= 1) { + printf("]"); + return; + } + printf(", "); + if (dim > 1) + printf("\n"); + for (int64_t i = 1; i + 1 < sizes[0]; ++i) { + vx_print_spaces(rank - dim + 1); + vx_print_data(base, bytes, is_signed, dim - 1, rank, + offset + i * strides[0], sizes + 1, strides + 1); + printf(", "); + if (dim > 1) + printf("\n"); + } + vx_print_spaces(rank - dim + 1); + vx_print_data(base, bytes, is_signed, dim - 1, rank, + offset + strides[0] * (sizes[0] - 1), sizes + 1, strides + 1); + printf("]"); +} + +static void vx_print_memref(int64_t rank, void *descriptor, int bytes, + int is_signed) { + const VxRankedMemRef *m = (const VxRankedMemRef *)descriptor; + const int64_t *sizes = m->sizes_and_strides; + const int64_t *strides = m->sizes_and_strides + rank; + printf("Unranked Memref base@ = %p rank = %" PRId64 " offset = %" PRId64 + " sizes = [", + m->aligned, rank, m->offset); + for (int64_t i = 0; i < rank; ++i) + printf(i ? ", %" PRId64 : "%" PRId64, sizes[i]); + printf("] strides = ["); + for (int64_t i = 0; i < rank; ++i) + printf(i ? ", %" PRId64 : "%" PRId64, strides[i]); + printf("] data = \n"); + if (rank == 0) + printf("["); + vx_print_data(m->aligned, bytes, is_signed, rank, rank, m->offset, sizes, + strides); + if (rank == 0) + printf("]"); + printf("\n"); + fflush(stdout); +} + +void printMemrefI8(int64_t rank, void *descriptor) { + vx_print_memref(rank, descriptor, 1, 1); +} + +void printMemrefI16(int64_t rank, void *descriptor) { + VxUnrankedMemRef packed = {rank, descriptor}; + _mlir_ciface_printMemrefI16(&packed); +} + +void printMemrefU8(int64_t rank, void *descriptor) { + vx_print_memref(rank, descriptor, 1, 0); +} + +void printMemrefU16(int64_t rank, void *descriptor) { + vx_print_memref(rank, descriptor, 2, 0); +} + +void printMemrefU32(int64_t rank, void *descriptor) { + vx_print_memref(rank, descriptor, 4, 0); +} + +void printMemrefU64(int64_t rank, void *descriptor) { + vx_print_memref(rank, descriptor, 8, 0); +} +``` + +Add a one-line comment above every function that says what it does. Output the whole file, and change nothing else.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/explain1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/explain1.txt new file mode 100644 index 0000000..07afd8c --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/explain1.txt @@ -0,0 +1,152 @@ +<|im_start|>user +`src/suggest.rs`: + +```rust +//===- suggest.rs - Vx Compiler ------------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Provides "did you mean?" suggestions for name resolution errors using +// Levenshtein edit distance. Used by E2001-E2007 diagnostics. +// +//===----------------------------------------------------------------------===// + +/// Compute Levenshtein edit distance between two strings. +pub fn levenshtein(a: &str, b: &str) -> usize { + let a_len = a.len(); + let b_len = b.len(); + + if a_len == 0 { + return b_len; + } + if b_len == 0 { + return a_len; + } + + let mut prev_row: Vec = (0..=b_len).collect(); + let mut curr_row = vec![0; b_len + 1]; + + for (i, a_char) in a.chars().enumerate() { + curr_row[0] = i + 1; + for (j, b_char) in b.chars().enumerate() { + let cost = if a_char == b_char { 0 } else { 1 }; + curr_row[j + 1] = (prev_row[j + 1] + 1) + .min(curr_row[j] + 1) + .min(prev_row[j] + cost); + } + std::mem::swap(&mut prev_row, &mut curr_row); + } + + prev_row[b_len] +} + +/// Find the closest match to `target` from a list of `candidates`. +/// Returns `None` if no candidate is within `max_dist` edits. +pub fn closest_match<'a>(target: &str, candidates: &[&'a str], max_dist: usize) -> Option<&'a str> { + candidates + .iter() + .filter_map(|c| { + let dist = levenshtein(target, c); + if dist > 0 && dist <= max_dist { + Some((*c, dist)) + } else { + None + } + }) + .min_by_key(|(_, d)| *d) + .map(|(c, _)| c) +} + +/// Suggest a correction for a name, using a dynamic max distance based on name length. +/// Short names (1-3 chars) allow 1 edit, medium names (4-7) allow 2, longer allow 3. +pub fn suggest_name<'a>(target: &str, candidates: &[&'a str]) -> Option<&'a str> { + let max_dist = match target.len() { + 0 => return None, + 1..=3 => 1, + 4..=7 => 2, + _ => 3, + }; + closest_match(target, candidates, max_dist) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_levenshtein_identical() { + assert_eq!(levenshtein("hello", "hello"), 0); + } + + #[test] + fn test_levenshtein_empty() { + assert_eq!(levenshtein("", "abc"), 3); + assert_eq!(levenshtein("abc", ""), 3); + assert_eq!(levenshtein("", ""), 0); + } + + #[test] + fn test_levenshtein_one_edit() { + assert_eq!(levenshtein("count", "conut"), 2); // transposition = 2 edits + assert_eq!(levenshtein("count", "counr"), 1); // substitution + assert_eq!(levenshtein("count", "coun"), 1); // deletion + assert_eq!(levenshtein("count", "counts"), 1); // insertion + } + + #[test] + fn test_levenshtein_multiple_edits() { + assert_eq!(levenshtein("kitten", "sitting"), 3); + } + + #[test] + fn test_closest_match_found() { + let candidates = vec!["count", "counter", "amount", "mount"]; + assert_eq!(closest_match("counr", &candidates, 2), Some("count")); + } + + #[test] + fn test_closest_match_too_far() { + let candidates = vec!["apple", "banana", "cherry"]; + assert_eq!(closest_match("xyz", &candidates, 2), None); + } + + #[test] + fn test_closest_match_exact_excluded() { + // Exact matches (distance 0) should be excluded since the name is already correct + let candidates = vec!["count", "counter"]; + assert_eq!(closest_match("count", &candidates, 2), Some("counter")); + } + + #[test] + fn test_suggest_name_short() { + let candidates = vec!["x", "y", "z", "a"]; + // 'b' is distance 1 from all candidates, so one will be returned + assert!(suggest_name("b", &candidates).is_some()); + } + + #[test] + fn test_suggest_name_medium() { + let candidates = vec!["counter", "count", "amount"]; + // 'contr' (len 5) allows max_dist=2; 'count' is dist 2 from 'contr' + let result = suggest_name("contr", &candidates); + assert!(result == Some("count") || result == Some("counter")); + } + + #[test] + fn test_suggest_name_empty() { + let candidates = vec!["x", "y"]; + assert_eq!(suggest_name("", &candidates), None); + } +} +``` + +Explain what this code does, function by function.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/explain2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/explain2.txt new file mode 100644 index 0000000..be0ac30 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/explain2.txt @@ -0,0 +1,143 @@ +<|im_start|>user +`src/decline.rs`: + +```rust +//===- decline.rs - Vx Compiler --------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Why the flat path gave up on a function. +// +// The flat lowerer declines whatever it cannot lower yet, and the AST path stays the oracle for +// that function. Declining is expected. Declining without saying why is what makes "how much of +// the language does the flat path carry" a reading exercise instead of a query. +// +// A leaf module: both the flattener and the flat emitter produce these, and the corpus sweep +// counts them. +// +//===----------------------------------------------------------------------===// + +use std::fmt; + +/// Why one function did not lower through the flat path. +/// +/// Every variant names something the flat path does not do *yet*. None of them is an error: a +/// declined function compiles through the AST path and produces the same MLIR. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum Decline { + /// An expression the flat lowerer has no case for. Carries the `Expr` variant name. + UnsupportedExpr(&'static str), + + /// A statement the flat lowerer has no case for. Carries the `Statement` variant name. + UnsupportedStmt(&'static str), + + /// A callee with no signature in the registry -- an ambiguous cross-module name dropped from + /// `fn_sigs`, or an unregistered symbol. + UnresolvedCallee(String), + + /// A builtin called with operands the flat path does not lower: the wrong arity, or a tensor + /// whose rank or element type the emitted kernel does not accept. + BuiltinShape { + builtin: &'static str, + why: &'static str, + }, + + /// A value whose lowered type is not the one this construct needs -- indexing something that + /// is not a pointer, taking a field of a nominal the flat path has no layout for. + TypeNotModelled { what: &'static str }, + + /// A construct the flat path lowers only in memory mode, reached in register mode. + NeedsMemoryMode { construct: &'static str }, + + /// Something the flat path does not lower yet that is none of the above. `what` is a short + /// fixed phrase, never a formatted value, so the histogram groups. + Unsupported { what: &'static str }, + + /// A gap in the flat *emitter* that has not been given a phrase of its own yet, naming the + /// source line that produced it. + /// + /// The emitter bails from roughly 190 places, most of which no corpus program has ever + /// reached. Writing a description for each up front would be 190 guesses about which ones + /// matter. Carrying the site instead means the histogram names the exact line to describe, + /// and only the lines something actually reaches get the work. + EmitterGap { site: &'static str }, +} + +impl Decline { + /// A stable key for grouping. Deliberately drops the payload of the variants that carry one: + /// a histogram of "unresolved callee `foo`, unresolved callee `bar`" answers nothing that + /// "unresolved callee x2" does not. + pub fn key(&self) -> &'static str { + match self { + Decline::UnsupportedExpr(_) => "unsupported-expr", + Decline::UnsupportedStmt(_) => "unsupported-stmt", + Decline::UnresolvedCallee(_) => "unresolved-callee", + Decline::BuiltinShape { .. } => "builtin-shape", + Decline::TypeNotModelled { .. } => "type-not-modelled", + Decline::NeedsMemoryMode { .. } => "needs-memory-mode", + Decline::Unsupported { .. } => "unsupported", + Decline::EmitterGap { .. } => "emitter-gap", + } + } + + /// The key plus the one detail that says *which* construct, for a histogram that names the + /// work rather than the category: `unsupported-expr(Closure)`. + pub fn detail_key(&self) -> String { + match self { + Decline::UnsupportedExpr(k) => format!("unsupported-expr({k})"), + Decline::UnsupportedStmt(k) => format!("unsupported-stmt({k})"), + Decline::UnresolvedCallee(_) => "unresolved-callee".to_string(), + Decline::BuiltinShape { builtin, .. } => format!("builtin-shape({builtin})"), + Decline::TypeNotModelled { what } => format!("type-not-modelled({what})"), + Decline::NeedsMemoryMode { construct } => format!("needs-memory-mode({construct})"), + Decline::Unsupported { what } => format!("unsupported({what})"), + Decline::EmitterGap { site } => format!("emitter-gap({site})"), + } + } +} + +impl fmt::Display for Decline { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Decline::UnsupportedExpr(k) => write!(f, "no flat lowering for the {k} expression"), + Decline::UnsupportedStmt(k) => write!(f, "no flat lowering for the {k} statement"), + Decline::UnresolvedCallee(n) => write!(f, "no signature for the callee '{n}'"), + Decline::BuiltinShape { builtin, why } => { + write!(f, "'{builtin}' called with {why}") + } + Decline::TypeNotModelled { what } => write!(f, "{what}"), + Decline::NeedsMemoryMode { construct } => { + write!(f, "{construct} lowers only in memory mode") + } + Decline::Unsupported { what } => write!(f, "no flat lowering for {what}"), + Decline::EmitterGap { site } => write!(f, "an emitter gap at {site}"), + } + } +} + +/// What a lowering step returns: the value, or the reason the flat path gave up. +pub type Lowered = Result; + +/// An emitter bail-out that has no phrase of its own yet, stamped with where it is. +/// +/// A macro rather than a function so `line!()` expands at the bail site. +#[macro_export] +macro_rules! emitter_gap { + () => { + $crate::decline::Decline::EmitterGap { + site: concat!(file!(), ":", line!()), + } + }; +} +``` + +Explain what this code does, function by function.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/explain3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/explain3.txt new file mode 100644 index 0000000..f08793b --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/explain3.txt @@ -0,0 +1,235 @@ +<|im_start|>user +`src/error.rs`: + +```rust +//===- error.rs - Vx Compiler ----------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines the error handling and diagnostic reporting infrastructure. +// It provides formatting routines to display rich compiler errors with source code +// snippets, line numbers, and colorful annotations to help developers quickly +// identify and resolve syntax or semantic issues. +// +//===----------------------------------------------------------------------===// + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Error(pub String); + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0) + } +} + +/// Render an error with the source line it points at and a caret under the place. `file` is +/// printed before the line and column, as `file:line:column`, when the source came from one. +pub fn format_compiler_error( + source: &str, + file: Option<&str>, + line: usize, + col: usize, + len: usize, + msg: &str, +) -> String { + if line > 0 { + if let Some(src_line) = source.lines().nth(line - 1) { + let mut out = String::with_capacity(msg.len() + src_line.len() * 2 + 64); + use std::fmt::Write; + match file { + Some(file) => { + let _ = writeln!(out, "Error at {}:{}:{}: {}", file, line, col, msg); + } + None => { + let _ = writeln!(out, "Error at {}:{}: {}", line, col, msg); + } + } + + out.push_str(src_line); + out.push('\n'); + + let mut pointer = String::new(); + for (i, c) in src_line.chars().enumerate() { + if i < col - 1 { + if c == '\t' { + pointer.push('\t'); + } else { + pointer.push(' '); + } + } else { + break; + } + } + + // Replace up to 4 trailing spaces with tildes for better visual anchoring + let mut prefix_tildes = 0; + while prefix_tildes < 4 && pointer.ends_with(' ') { + pointer.pop(); + prefix_tildes += 1; + } + for _ in 0..prefix_tildes { + pointer.push('~'); + } + + for _ in 0..len { + pointer.push('^'); + } + pointer.push_str("~~~~"); + out.push_str(&pointer); + out.push('\n'); + return out; + } + } + + // Fallback if line is out of bounds + match file { + Some(file) => format!("Error at {}:{}:{}: {}\n", file, line, col, msg), + None => format!("Error at {}:{}: {}\n", line, col, msg), + } +} + +pub fn format_compiler_warning( + source: &str, + line: usize, + col: usize, + len: usize, + code: Option, + msg: &str, +) -> String { + let code_str = match code { + Some(c) => format!("[{}]", c), + None => String::new(), + }; + + if line > 0 { + if let Some(src_line) = source.lines().nth(line - 1) { + let mut out = String::with_capacity(msg.len() + src_line.len() * 2 + 64); + use std::fmt::Write; + let _ = writeln!(out, "Warning{} at {}:{}: {}", code_str, line, col, msg); + + out.push_str(src_line); + out.push('\n'); + + let mut pointer = String::new(); + for (i, c) in src_line.chars().enumerate() { + if i < col - 1 { + if c == '\t' { + pointer.push('\t'); + } else { + pointer.push(' '); + } + } else { + break; + } + } + + // Replace up to 4 trailing spaces with tildes for better visual anchoring + let mut prefix_tildes = 0; + while prefix_tildes < 4 && pointer.ends_with(' ') { + pointer.pop(); + prefix_tildes += 1; + } + for _ in 0..prefix_tildes { + pointer.push('~'); + } + + for _ in 0..len { + pointer.push('^'); + } + pointer.push_str("~~~~"); + out.push_str(&pointer); + out.push('\n'); + return out; + } + } + + // Fallback if line is out of bounds + format!("Warning{} at {}:{}: {}\n", code_str, line, col, msg) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_format_compiler_error_len_1_with_padding() { + // " + " (col = 5) + let source = " + "; + let formatted = format_compiler_error(source, None, 1, 5, 1, "Expected operand"); + + // Should produce: + // Error at 1:5: Expected operand + // + + // ~~~~^~~~~ + let expected = "Error at 1:5: Expected operand\n + \n~~~~^~~~~\n"; + assert_eq!(formatted, expected); + } + + #[test] + fn test_format_compiler_error_len_1_no_padding() { + // "+ " (col = 1) + let source = "+ "; + let formatted = format_compiler_error(source, None, 1, 1, 1, "Unexpected"); + + // Should produce: + // Error at 1:1: Unexpected + // + + // ^~~~~ + let expected = "Error at 1:1: Unexpected\n+ \n^~~~~\n"; + assert_eq!(formatted, expected); + } + + #[test] + fn test_format_compiler_error_len_4() { + // "asdf" (col = 1) + let source = "asdf"; + let formatted = format_compiler_error(source, None, 1, 1, 4, "Unknown identifier"); + + // Should produce: + // Error at 1:1: Unknown identifier + // asdf + // ^^^^~~~~ + let expected = "Error at 1:1: Unknown identifier\nasdf\n^^^^~~~~\n"; + assert_eq!(formatted, expected); + } + + #[test] + fn test_format_compiler_error_len_4_with_padding() { + // " asdf" (col = 5) - full 4 spaces of padding + let source = " asdf"; + let formatted = format_compiler_error(source, None, 1, 5, 4, "Unknown identifier"); + + // Should produce: + // Error at 1:5: Unknown identifier + // asdf + // ~~~~^^^^~~~~ + let expected = "Error at 1:5: Unknown identifier\n asdf\n~~~~^^^^~~~~\n"; + assert_eq!(formatted, expected); + } + + #[test] + fn test_format_compiler_error_len_4_with_partial_padding() { + // " asdf" (col = 3) - only 2 spaces of padding available to replace + let source = " asdf"; + let formatted = format_compiler_error(source, None, 1, 3, 4, "Unknown identifier"); + + // Should produce: + // Error at 1:3: Unknown identifier + // asdf + // ~~^^^^~~~~ + let expected = "Error at 1:3: Unknown identifier\n asdf\n~~^^^^~~~~\n"; + assert_eq!(formatted, expected); + } +} +``` + +Explain what this code does, function by function.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/write1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/write1.txt new file mode 100644 index 0000000..4c6ec5f --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/write1.txt @@ -0,0 +1,7 @@ +<|im_start|>user +Write a Python module with a class LRUCache that has get, put and a capacity, built on OrderedDict. Add pytest tests for it.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/write2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/write2.txt new file mode 100644 index 0000000..ff6783d --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/write2.txt @@ -0,0 +1,7 @@ +<|im_start|>user +Write a C function `int parse_csv_line(const char *line, char **fields, int max_fields)` that handles quoted fields and doubled quotes inside them. Add a main() that tests it.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/write3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/write3.txt new file mode 100644 index 0000000..4c6caf4 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/write3.txt @@ -0,0 +1,7 @@ +<|im_start|>user +Write a Rust struct RingBuffer with new, push, pop, len, is_empty and an iterator. Add unit tests.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/run.sh b/docs/benchmarks/2026-11-20-qwen36-m4/run.sh new file mode 100755 index 0000000..4180b54 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/run.sh @@ -0,0 +1,223 @@ +#!/bin/bash +# The benchmark of the Qwen3.6 app against llama.cpp on an M4, as docs/benchmarking_policy.md of +# the Vx repository asks. Run it under `caffeinate -dims`, on a Mac with no other work. It writes +# logs/, log.txt and env.txt into OUT. Then `parse.py OUT` writes runs.csv and summary.md. +# +# 1. Flash attention of llama.cpp: on and off at the 2,048-token prompt. The later stages use +# the setting with the faster median. +# 2. llama-bench: pp512, pp2048 and pp8192, and tg128 after 0 to 32,768 tokens, 5 repetitions. +# 3. Table A: 256 generated tokens after 64 to 32,768 prompt tokens. +# 4. Table P: the prompts of 512 to 8,192 tokens, PROMPT_RUNS times in one process. The first +# run includes the first launch of each kernel. The runs after it show the time in a session. +# 5. Table T: the draft lengths, on the 12 tuning prompts, once each. The app tries each length of +# DRAFTS, and llama-speculative-simple with the MTP heads each of MTP_DRAFTS. Table C uses the +# length with the fastest geometric mean. llama-speculative-simple with n-gram drafts +# (ngram-mod and ngram-cache) keeps the settings of llama.cpp: ngram-cache always drafts 8 +# tokens. llama-lookup is not in the benchmark: on this model its text differs from that +# of llama-completion, and its log has errors from llama_decode. +# 6. Table C: the 12 held-out prompts, 512 generated tokens. The programs are the app, the app +# with --draft, llama-completion, and llama-speculative-simple with ngram-cache, ngram-mod +# and the MTP heads. +# +# Each case runs ROUNDS times. Round 2 runs the programs in the reverse order. Before each run, the +# script waits until no other process uses more than 20% of a CPU and the GPU is idle, and then +# waits COOL seconds more. A run takes about 1 to 2 minutes, so all the stages take about 10 hours. +# Build llama.cpp from its commit b1b770d with llama-timing.patch. Without the patch, +# llama-speculative-simple stops the clock of the prompt before the GPU ends the prompt, and counts +# the rest of the prompt in the time of the generated tokens. +# STAGES selects the stages: fa, bench, A, P, T and C. Without the stage fa, give FA=on or FA=off. +# Without the stage T, give DRAFT and MTP_N. A short test can also set CONTEXTS, +# P_CONTEXTS, PROMPTS, A_TOKENS, TOKENS and the lists of draft lengths. The report uses the defaults. +set -u +HERE=$(cd "$(dirname "$0")" && pwd) +OUT=${OUT:-$HERE/out} +ROUNDS=${ROUNDS:-3} +COOL=${COOL:-30} +STAGES=${STAGES:-fa bench A P T C} +DRAFTS=${DRAFTS:-3 5 7 9 11 15} +MTP_DRAFTS=${MTP_DRAFTS:-1 2 3 4 6} +PROMPT_RUNS=${PROMPT_RUNS:-3} +CONTEXTS=${CONTEXTS:-64 512 2048 8192 16384 32768} +P_CONTEXTS=${P_CONTEXTS:-512 2048 8192} +PROMPTS=${PROMPTS:-edit1 complete1 write1 explain1 edit2 complete2 write2 explain2 edit3 complete3 write3 explain3} +A_TOKENS=${A_TOKENS:-256} +TOKENS=${TOKENS:-512} +VXC=${VXC:?the release vxc} +FLEET=${FLEET:?the fleet/ folder of that vxc} +QV=${QV:-$(cd "$HERE/../../.." && pwd)} +VXW=${VXW:?the weight file of the app} +VXT=${VXT:?the tokenizer file of the app} +GGUF=${GGUF:?the GGUF file} +MTP=${MTP:?the GGUF file of the MTP heads} +LB=${LB:?the bin/ folder of llama.cpp} +LLAMA_SRC=${LLAMA_SRC:-$LB/../..} +P=$HERE/prompts +want() { [[ " $STAGES " == *" $1 "* ]]; } +mkdir -p "$OUT/logs" +cd "$OUT" || exit 1 + +gpu_busy() { # the Device Utilization % of the GPU + ioreg -r -d 1 -c IOAccelerator | grep -o '"Device Utilization %"=[0-9]*' | head -1 | cut -d= -f2 +} +quiet() { + while ps -Ao %cpu,comm -r | awk 'NR>1 && $2 !~ /claude|Terminal|WindowServer|kernel_task/ && $1 > 20 {found=1} END {exit !found}' \ + || [ "$(gpu_busy)" -gt 5 ]; do + sleep 10 + done + sleep "$COOL" +} +busy() { ps -Ao %cpu,comm -r | awk 'NR>1 && $2 !~ /claude|Terminal/ {printf "%s %s", $1, $2; exit}' | sed 's|.*/||'; } + +# Each program prints its whole command line first, so that the log has it. +show() { + echo "command: $*" + "$@" +} +vx() { # PROMPT STEPS [options] + local f=$1 n=$2 + shift 2 + show "$VXC" -O2 "$QV/src/main.vx" --package qwen="$QV/src" --host default --machine "$FLEET/m4-uma.vx" -- \ + "$VXW" --tokenizer "$VXT" --prompt-file "$f" --steps "$n" --ignore-eos "$@" +} +llama() { # TOOL PROMPT N CTX [options] + local tool=$1 f=$2 n=$3 c=$4 + shift 4 + show "$LB/$tool" -m "$GGUF" -f "$f" -n "$n" -c "$c" --temp 0 -ngl 99 -fa "$FA" --no-escape --ignore-eos "$@" +} +completion() { llama llama-completion "$@" -no-cnv; } +# llama-speculative-simple refuses a prompt longer than the batch (-b, 2,048 by default). The +# longest prompt has 2,251 tokens. +spec() { llama llama-speculative-simple "$@" -b 4096; } + +run() { # NAME COMMAND...: one run, its output in logs/NAME.txt, a line in log.txt + local name=$1 + shift + quiet + local b g t0 + b=$(busy) + g=$(gpu_busy) + t0=$(date +%Y-%m-%dT%H:%M:%S) + "$@" > "logs/$name.txt" 2>&1 + local rc=$? + echo "$name start=$t0 end=$(date +%Y-%m-%dT%H:%M:%S) rc=$rc busy=[$b] gpu=$g%" | tee -a log.txt +} + +{ + echo "date: $(date), stages: $STAGES" + echo "machine: $(sysctl -n hw.model), $(sysctl -n machdep.cpu.brand_string), $(($(sysctl -n hw.memsize) / 1073741824)) GB" + system_profiler SPDisplaysDataType 2> /dev/null | grep -E "Chipset Model|Total Number of Cores|Metal Support" + echo "macOS: $(sw_vers -productVersion) ($(sw_vers -buildVersion))" + echo "power: $(pmset -g batt | head -1)" + echo "vxc: $("$VXC" --version 2>&1)" + echo "qwen-vx: $(git -C "$QV" log -1 --format='%H %s'), changed files: $(git -C "$QV" status --short -- src | wc -l | tr -d ' ')" + echo "llama.cpp: $("$LB/llama-completion" --version 2>&1 | tr '\n' ' ')" + echo "llama.cpp source: $(git -C "$LLAMA_SRC" log -1 --format=%H), changes: $(git -C "$LLAMA_SRC" diff --stat | tail -1)" + git -C "$LLAMA_SRC" diff > llama.cpp.diff + echo "GGUF: $GGUF $(stat -f %z "$GGUF") bytes" + echo "MTP GGUF: $MTP $(stat -f %z "$MTP") bytes" + echo "app weights: $VXW $(stat -f %z "$VXW") bytes" + echo "app tokenizer: $VXT $(stat -f %z "$VXT") bytes" + echo "rounds: $ROUNDS, cool: $COOL s, prompt runs: $PROMPT_RUNS" + echo "contexts: $CONTEXTS, prompt contexts: $P_CONTEXTS, generated tokens: $A_TOKENS and $TOKENS" + echo "prompts: $PROMPTS" + echo "draft lengths tried: app $DRAFTS, MTP $MTP_DRAFTS" +} >> env.txt + +# The order of the programs in round r: as given in odd rounds, reversed in even rounds. +order() { # R NAME... + local r=$1 + shift + if [ $((r % 2)) = 1 ]; then echo "$@"; else echo "$@" | tr ' ' '\n' | tail -r | tr '\n' ' '; fi +} + +# 1. Flash attention of llama.cpp +if want fa; then + for r in $(seq 1 "$ROUNDS"); do + for fa in $(order "$r" on off); do + FA=$fa run "fa-$fa.ctx2048.r$r" completion "$P/context/llama/ctx2048.txt" 256 4096 + done + done + ms() { grep 'common_perf_print: *eval time' "$1" | sed -E 's/.*\( *([0-9.]+) ms per token.*/\1/'; } + med() { sort -n | awk '{a[NR]=$1} END {print a[int((NR+1)/2)]}'; } + on=$(for f in logs/fa-on.ctx2048.r*.txt; do ms "$f"; done | med) + off=$(for f in logs/fa-off.ctx2048.r*.txt; do ms "$f"; done | med) + FA=$(awk -v a="$on" -v b="$off" 'BEGIN {print (a <= b) ? "on" : "off"}') + echo "flash attention: on $on ms, off $off ms (medians at 2,048 tokens); chosen: $FA" | tee -a log.txt env.txt +fi +FA=${FA:?give FA=on or FA=off, or run the stage fa} +want fa || echo "flash attention: given by FA; chosen: $FA" | tee -a log.txt env.txt + +# 2. llama-bench +want bench && run llama-bench-pp show "$LB/llama-bench" -m "$GGUF" -p 512,2048,8192 -n 0 -r 5 -ngl 99 -fa "$FA" -o md +want bench && run llama-bench-tg show "$LB/llama-bench" -m "$GGUF" -p 0 -n 128 -d 0,2048,8192,16384,32768 -r 5 -ngl 99 -fa "$FA" -o md + +# 3. Table A +want A && for r in $(seq 1 "$ROUNDS"); do + for c in $CONTEXTS; do + for tool in $(order "$r" vx llama); do + if [ "$tool" = vx ]; then + run "A.vx.ctx$c.r$r" vx "$P/context/vx/ctx$c.txt" "$A_TOKENS" + else + run "A.llama.ctx$c.r$r" completion "$P/context/llama/ctx$c.txt" "$A_TOKENS" $((c + 512)) + fi + done + done +done + +# 4. Table P +want P && for r in $(seq 1 "$ROUNDS"); do + for c in $P_CONTEXTS; do + for tool in $(order "$r" vx llama); do + if [ "$tool" = vx ]; then + run "P.vx.ctx$c.r$r" vx "$P/context/vx/ctx$c.txt" 1 --prompt-runs "$PROMPT_RUNS" + else + run "P.llama.ctx$c.r$r" completion "$P/context/llama/ctx$c.txt" 1 $((c + 512)) + fi + done + done +done + +# 5. Table T +if want T; then + cases="vx completion ngram cache" + for d in $DRAFTS; do cases="$cases vxdraft$d"; done + for d in $MTP_DRAFTS; do cases="$cases mtp$d"; done + r=0 + for n in $PROMPTS; do + r=$((r + 1)) + for kind in $(order "$r" $cases); do + f=$P/twelve/llama/$n.txt + case $kind in + vx) run "T.$n.r1.vx" vx "$P/twelve/vx/$n.txt" "$TOKENS" ;; + vxdraft*) run "T.$n.r1.$kind" vx "$P/twelve/vx/$n.txt" "$TOKENS" --draft "${kind#vxdraft}" ;; + completion) run "T.$n.r1.completion" completion "$f" "$TOKENS" 8192 ;; + ngram) run "T.$n.r1.ngram" spec "$f" "$TOKENS" 8192 --spec-type ngram-mod ;; + mtp*) run "T.$n.r1.$kind" spec "$f" "$TOKENS" 8192 --spec-type draft-mtp -md "$MTP" -ngld 99 --spec-draft-n-max "${kind#mtp}" ;; + cache) run "T.$n.r1.cache" spec "$f" "$TOKENS" 8192 --spec-type ngram-cache ;; + esac + done + done + choice=$(python3 "$HERE/parse.py" "$OUT" --choose) || exit 1 + eval "$choice" + echo "draft lengths chosen in table T: $choice" | tee -a log.txt env.txt +else + echo "draft lengths given: DRAFT=${DRAFT:?} MTP_N=${MTP_N:?}" | tee -a log.txt env.txt +fi + +# 6. Table C +want C && for r in $(seq 1 "$ROUNDS"); do + for n in $PROMPTS; do + f=$P/heldout/llama/$n.txt + for kind in $(order "$r" vx vxdraft completion cache ngram mtp); do + case $kind in + vx) run "C.$n.r$r.vx" vx "$P/heldout/vx/$n.txt" "$TOKENS" ;; + vxdraft) run "C.$n.r$r.vxdraft$DRAFT" vx "$P/heldout/vx/$n.txt" "$TOKENS" --draft "$DRAFT" ;; + completion) run "C.$n.r$r.completion" completion "$f" "$TOKENS" 8192 ;; + cache) run "C.$n.r$r.cache" spec "$f" "$TOKENS" 8192 --spec-type ngram-cache ;; + ngram) run "C.$n.r$r.ngram" spec "$f" "$TOKENS" 8192 --spec-type ngram-mod ;; + mtp) run "C.$n.r$r.mtp$MTP_N" spec "$f" "$TOKENS" 8192 --spec-type draft-mtp -md "$MTP" -ngld 99 --spec-draft-n-max "$MTP_N" ;; + esac + done + done +done +echo "done $(date +%Y-%m-%dT%H:%M:%S)" | tee -a log.txt diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/runs.csv b/docs/benchmarks/2026-11-20-qwen36-m4/runs.csv new file mode 100644 index 0000000..187b7c2 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/runs.csv @@ -0,0 +1,457 @@ +table,prompt,kind,round,program,setting,prompt_tokens,llama_prompt_tokens,prompt_ms,first_prompt_ms,later_prompt_ms,ms_per_token,timed_tokens,checks,drafted,accepted,flash_attn,threads,errors,log,start,end,rc,busy,gpu,same_text,same_chars +A,context/ctx16384,ctx,1,llama-completion,,16384,16384,53550.1500,,,32.1600,255,,,,on,4,0,logs/A.llama.ctx16384.r1.txt,2026-11-20T16:45:39,2026-11-20T16:46:51,0,contextstored,0,, +A,context/ctx16384,ctx,2,llama-completion,,16384,16384,53045.7900,,,32.0500,255,,,,on,4,0,logs/A.llama.ctx16384.r2.txt,2026-11-20T17:09:44,2026-11-20T17:10:55,0,com.apple.AppleUserHIDDrivers,0,, +A,context/ctx16384,ctx,3,llama-completion,,16384,16384,53562.2200,,,32.0200,255,,,,on,4,0,logs/A.llama.ctx16384.r3.txt,2026-11-20T17:41:12,2026-11-20T17:42:24,0,mdworker_shared,0,, +A,context/ctx2048,ctx,1,llama-completion,,2048,2048,5044.1700,,,26.3600,255,,,,on,4,0,logs/A.llama.ctx2048.r1.txt,2026-11-20T16:37:30,2026-11-20T16:37:52,0,com.apple.AppleUserHIDDrivers,0,, +A,context/ctx2048,ctx,2,llama-completion,,2048,2048,5055.8200,,,26.4000,255,,,,on,4,0,logs/A.llama.ctx2048.r2.txt,2026-11-20T17:02:10,2026-11-20T17:02:31,0,com.apple.AppleUserHIDDrivers,0,, +A,context/ctx2048,ctx,3,llama-completion,,2048,2048,5050.2400,,,26.5300,255,,,,on,4,0,logs/A.llama.ctx2048.r3.txt,2026-11-20T17:32:45,2026-11-20T17:33:07,0,com.apple.AppleUserHIDDrivers,0,, +A,context/ctx32768,ctx,1,llama-completion,,32768,32768,138248.8000,,,48.3800,255,,,,on,4,0,logs/A.llama.ctx32768.r1.txt,2026-11-20T16:52:11,2026-11-20T16:54:52,0,com.apple.AppleUserHIDDrivers,0,, +A,context/ctx32768,ctx,2,llama-completion,,32768,32768,149487.8800,,,55.0100,255,,,,on,4,0,logs/A.llama.ctx32768.r2.txt,2026-11-20T17:15:06,2026-11-20T17:17:59,0,com.apple.AppleUserHIDDrivers,0,, +A,context/ctx32768,ctx,3,llama-completion,,32768,32768,138360.8300,,,48.9700,255,,,,on,4,0,logs/A.llama.ctx32768.r3.txt,2026-11-20T17:47:51,2026-11-20T17:50:32,0,com.apple.AppleUserHIDDrivers,0,, +A,context/ctx512,ctx,1,llama-completion,,512,512,1215.9400,,,25.8100,255,,,,on,4,0,logs/A.llama.ctx512.r1.txt,2026-11-20T16:34:03,2026-11-20T16:34:21,0,1.1 awk,0,, +A,context/ctx512,ctx,2,llama-completion,,512,512,1217.4700,,,25.8500,255,,,,on,4,0,logs/A.llama.ctx512.r2.txt,2026-11-20T16:58:45,2026-11-20T16:59:02,0,com.apple.AppleUserHIDDrivers,0,, +A,context/ctx512,ctx,3,llama-completion,,512,512,1216.5600,,,25.8300,255,,,,on,4,0,logs/A.llama.ctx512.r3.txt,2026-11-20T17:29:18,2026-11-20T17:29:36,0,launchd,1,, +A,context/ctx64,ctx,1,llama-completion,,64,64,251.3500,,,26.1900,255,,,,on,4,0,logs/A.llama.ctx64.r1.txt,2026-11-20T16:30:42,2026-11-20T16:30:59,0,bash,0,, +A,context/ctx64,ctx,2,llama-completion,,64,64,250.7500,,,25.8100,255,,,,on,4,0,logs/A.llama.ctx64.r2.txt,2026-11-20T16:55:32,2026-11-20T16:55:40,0,syspolicyd,0,, +A,context/ctx64,ctx,3,llama-completion,,64,64,251.6300,,,25.6300,255,,,,on,4,0,logs/A.llama.ctx64.r3.txt,2026-11-20T17:25:49,2026-11-20T17:26:05,0,launchd,0,, +A,context/ctx8192,ctx,1,llama-completion,,8192,8192,22577.2800,,,27.9400,255,,,,on,4,0,logs/A.llama.ctx8192.r1.txt,2026-11-20T16:41:17,2026-11-20T16:41:56,0,com.apple.AppleUserHIDDrivers,0,, +A,context/ctx8192,ctx,2,llama-completion,,8192,8192,22549.6100,,,27.8600,255,,,,on,4,0,logs/A.llama.ctx8192.r2.txt,2026-11-20T17:05:40,2026-11-20T17:06:19,0,com.apple.DriverKit-AppleBCMWLAN,0,, +A,context/ctx8192,ctx,3,llama-completion,,8192,8192,22622.0200,,,27.9800,255,,,,on,4,0,logs/A.llama.ctx8192.r3.txt,2026-11-20T17:36:32,2026-11-20T17:37:11,0,airportd,0,, +A,context/ctx16384,ctx,1,qwen-vx,,16384,,45431.6101,,,26.5495,,,,,,,0,logs/A.vx.ctx16384.r1.txt,2026-11-20T16:42:37,2026-11-20T16:44:59,0,bash,0,, +A,context/ctx16384,ctx,2,qwen-vx,,16384,,45955.1544,,,26.6510,,,,,,,0,logs/A.vx.ctx16384.r2.txt,2026-11-20T17:11:45,2026-11-20T17:14:26,0,airportd,1,, +A,context/ctx16384,ctx,3,qwen-vx,,16384,,45571.6667,,,26.5351,,,,,,,0,logs/A.vx.ctx16384.r3.txt,2026-11-20T17:37:52,2026-11-20T17:40:32,0,airportd,0,, +A,context/ctx2048,ctx,1,qwen-vx,,2048,,4156.5099,,,22.8361,,,,,,,0,logs/A.vx.ctx2048.r1.txt,2026-11-20T16:35:01,2026-11-20T16:36:50,0,loginwindow,0,, +A,context/ctx2048,ctx,2,qwen-vx,,2048,,4168.3893,,,22.7898,,,,,,,0,logs/A.vx.ctx2048.r2.txt,2026-11-20T17:03:11,2026-11-20T17:05:00,0,mediaanalysisd,0,, +A,context/ctx2048,ctx,3,qwen-vx,,2048,,4159.5969,,,22.8154,,,,,,,0,logs/A.vx.ctx2048.r3.txt,2026-11-20T17:30:26,2026-11-20T17:32:05,0,mDNSResponder,0,, +A,context/ctx32768,ctx,1,qwen-vx,,32768,,128628.0670,,,43.3858,,,,,,,0,logs/A.vx.ctx32768.r1.txt,2026-11-20T16:47:31,2026-11-20T16:51:31,0,com.apple.DriverKit-AppleBCMWLAN,0,, +A,context/ctx32768,ctx,2,qwen-vx,,32768,,134960.9222,,,47.4971,,,,,,,0,logs/A.vx.ctx32768.r2.txt,2026-11-20T17:18:39,2026-11-20T17:22:43,0,com.apple.AppleUserHIDDrivers,0,, +A,context/ctx32768,ctx,3,qwen-vx,,32768,,129143.4021,,,43.5542,,,,,,,0,logs/A.vx.ctx32768.r3.txt,2026-11-20T17:43:04,2026-11-20T17:47:11,0,com.apple.DriverKit-AppleBCMWLAN,1,, +A,context/ctx512,ctx,1,qwen-vx,,512,,1173.5671,,,22.3585,,,,,,,0,logs/A.vx.ctx512.r1.txt,2026-11-20T16:31:39,2026-11-20T16:33:23,0,com.apple.AppleUserHIDDrivers,0,, +A,context/ctx512,ctx,2,qwen-vx,,512,,1180.0845,,,22.2898,,,,,,,0,logs/A.vx.ctx512.r2.txt,2026-11-20T16:59:43,2026-11-20T17:01:29,0,airportd,0,, +A,context/ctx512,ctx,3,qwen-vx,,512,,1203.1726,,,22.3267,,,,,,,0,logs/A.vx.ctx512.r3.txt,2026-11-20T17:26:45,2026-11-20T17:28:38,0,bash,0,, +A,context/ctx64,ctx,1,qwen-vx,,64,,338.2178,,,22.1689,,,,,,,0,logs/A.vx.ctx64.r1.txt,2026-11-20T16:28:14,2026-11-20T16:30:02,0,Brave,0,, +A,context/ctx64,ctx,2,qwen-vx,,64,,350.7057,,,22.1683,,,,,,,0,logs/A.vx.ctx64.r2.txt,2026-11-20T16:56:20,2026-11-20T16:58:05,0,com.apple.AppleUserHIDDrivers,0,, +A,context/ctx64,ctx,3,qwen-vx,,64,,366.0594,,,22.1402,,,,,,,0,logs/A.vx.ctx64.r3.txt,2026-11-20T17:23:24,2026-11-20T17:25:09,0,dasd,0,, +A,context/ctx8192,ctx,1,qwen-vx,,8192,,18830.1716,,,24.2968,,,,,,,0,logs/A.vx.ctx8192.r1.txt,2026-11-20T16:38:32,2026-11-20T16:40:37,0,airportd,0,, +A,context/ctx8192,ctx,2,qwen-vx,,8192,,18928.0872,,,24.3153,,,,,,,0,logs/A.vx.ctx8192.r2.txt,2026-11-20T17:06:59,2026-11-20T17:09:03,0,com.apple.AppleUserHIDDrivers,0,, +A,context/ctx8192,ctx,3,qwen-vx,,8192,,18850.2197,,,24.3251,,,,,,,0,logs/A.vx.ctx8192.r3.txt,2026-11-20T17:33:47,2026-11-20T17:35:52,0,mediaanalysisd,0,, +C,heldout/complete1,complete,1,llama.cpp ngram-cache,,1044,1044,2569.0000,,,30.5175,514,,241,241,on,4,0,logs/C.complete1.r1.cache.txt,2026-11-21T00:15:19,2026-11-21T00:15:38,0,WindowServer,1,True,2085 +C,heldout/complete1,complete,1,llama-completion,,1044,1044,2579.5700,,,26.1000,511,,,,on,4,0,logs/C.complete1.r1.completion.txt,2026-11-21T00:14:13,2026-11-21T00:14:39,0,WindowServer,0,, +C,heldout/complete1,complete,1,llama.cpp draft-mtp,3,1044,1044,2709.0000,,,17.2097,515,,459,362,on,4,0,logs/C.complete1.r1.mtp3.txt,2026-11-21T00:17:16,2026-11-21T00:17:29,0,WindowServer,0,False,1055 +C,heldout/complete1,complete,1,llama.cpp ngram-mod,,1044,1044,2553.0000,,,26.3957,513,,0,0,on,4,0,logs/C.complete1.r1.ngram.txt,2026-11-21T00:16:19,2026-11-21T00:16:36,0,WindowServer,1,True,2085 +C,heldout/complete1,complete,1,qwen-vx,,1044,,2223.7871,,,22.4825,,,,,,,0,logs/C.complete1.r1.vx.txt,2026-11-21T00:08:53,2026-11-21T00:10:49,0,WindowServer,1,, +C,heldout/complete1,complete,1,qwen-vx --draft,7,1044,,2232.7492,,,22.7991,,10,35,12,,,0,logs/C.complete1.r1.vxdraft7.txt,2026-11-21T00:11:29,2026-11-21T00:13:33,0,WindowServer,0,True,2040 +C,heldout/complete1,complete,2,llama.cpp ngram-cache,,1044,1044,2561.0000,,,30.5895,514,,241,241,on,4,0,logs/C.complete1.r2.cache.txt,2026-11-21T02:00:34,2026-11-21T02:00:54,0,airportd,0,True,2085 +C,heldout/complete1,complete,2,llama-completion,,1044,1044,2563.2300,,,26.3400,511,,,,on,4,0,logs/C.complete1.r2.completion.txt,2026-11-21T02:01:34,2026-11-21T02:01:51,0,Google,0,, +C,heldout/complete1,complete,2,llama.cpp draft-mtp,3,1044,1044,2697.0000,,,17.1922,515,,459,362,on,4,0,logs/C.complete1.r2.mtp3.txt,2026-11-21T01:58:34,2026-11-21T01:58:56,0,com.apple.AppleUserHIDDrivers,1,False,1055 +C,heldout/complete1,complete,2,llama.cpp ngram-mod,,1044,1044,2545.0000,,,26.4717,513,,0,0,on,4,0,logs/C.complete1.r2.ngram.txt,2026-11-21T01:59:37,2026-11-21T01:59:54,0,com.apple.AppleUserHIDDrivers,0,True,2085 +C,heldout/complete1,complete,2,qwen-vx,,1044,,2215.2805,,,22.4727,,,,,,,0,logs/C.complete1.r2.vx.txt,2026-11-21T02:05:15,2026-11-21T02:06:59,0,com.apple.AppleUserHIDDrivers,0,, +C,heldout/complete1,complete,2,qwen-vx --draft,7,1044,,2221.6711,,,22.8054,,10,35,12,,,0,logs/C.complete1.r2.vxdraft7.txt,2026-11-21T02:02:31,2026-11-21T02:04:35,0,com.apple.AppleUserHIDDrivers,0,True,2040 +C,heldout/complete1,complete,3,llama.cpp ngram-cache,,1044,1044,2573.0000,,,30.6012,514,,241,241,on,4,0,logs/C.complete1.r3.cache.txt,2026-11-21T03:55:00,2026-11-21T03:55:20,0,WindowServer,3,True,2085 +C,heldout/complete1,complete,3,llama-completion,,1044,1044,2581.6100,,,26.2900,511,,,,on,4,0,logs/C.complete1.r3.completion.txt,2026-11-21T03:53:54,2026-11-21T03:54:20,0,WindowServer,1,, +C,heldout/complete1,complete,3,llama.cpp draft-mtp,3,1044,1044,2716.0000,,,18.1476,515,,459,362,on,4,0,logs/C.complete1.r3.mtp3.txt,2026-11-21T03:56:57,2026-11-21T03:57:11,0,WindowServer,1,False,1055 +C,heldout/complete1,complete,3,llama.cpp ngram-mod,,1044,1044,2559.0000,,,26.3275,513,,0,0,on,4,0,logs/C.complete1.r3.ngram.txt,2026-11-21T03:56:00,2026-11-21T03:56:17,0,WindowServer,2,True,2085 +C,heldout/complete1,complete,3,qwen-vx,,1044,,2236.5873,,,22.4084,,,,,,,0,logs/C.complete1.r3.vx.txt,2026-11-21T03:48:47,2026-11-21T03:50:40,0,WindowServer,1,, +C,heldout/complete1,complete,3,qwen-vx --draft,7,1044,,2240.2456,,,22.7819,,10,35,12,,,0,logs/C.complete1.r3.vxdraft7.txt,2026-11-21T03:51:20,2026-11-21T03:53:14,0,WindowServer,8,True,2040 +C,heldout/complete2,complete,1,llama.cpp ngram-cache,,1086,1086,2740.0000,,,31.6355,513,,168,168,on,4,0,logs/C.complete2.r1.cache.txt,2026-11-21T00:51:42,2026-11-21T00:52:02,0,WindowServer,1,True,1938 +C,heldout/complete2,complete,1,llama-completion,,1086,1086,2752.1300,,,26.1200,511,,,,on,4,0,logs/C.complete2.r1.completion.txt,2026-11-21T00:50:36,2026-11-21T00:51:02,0,WindowServer,1,, +C,heldout/complete2,complete,1,llama.cpp draft-mtp,3,1086,1086,2879.0000,,,18.1124,516,,461,362,on,4,0,logs/C.complete2.r1.mtp3.txt,2026-11-21T00:53:40,2026-11-21T00:53:54,0,WindowServer,1,True,1938 +C,heldout/complete2,complete,1,llama.cpp ngram-mod,,1086,1086,2724.0000,,,26.4152,513,,0,0,on,4,0,logs/C.complete2.r1.ngram.txt,2026-11-21T00:52:42,2026-11-21T00:53:00,0,WindowServer,1,True,1938 +C,heldout/complete2,complete,1,qwen-vx,,1086,,2288.5244,,,22.4842,,,,,,,0,logs/C.complete2.r1.vx.txt,2026-11-21T00:45:02,2026-11-21T00:47:05,0,WindowServer,1,, +C,heldout/complete2,complete,1,qwen-vx --draft,7,1086,,2274.6572,,,22.6973,,8,26,10,,,0,logs/C.complete2.r1.vxdraft7.txt,2026-11-21T00:47:45,2026-11-21T00:49:56,0,WindowServer,0,True,1934 +C,heldout/complete2,complete,2,llama.cpp ngram-cache,,1086,1086,2734.0000,,,31.6004,513,,168,168,on,4,0,logs/C.complete2.r2.cache.txt,2026-11-21T02:36:37,2026-11-21T02:36:57,0,WindowServer,1,True,1938 +C,heldout/complete2,complete,2,llama-completion,,1086,1086,2740.0400,,,26.1200,511,,,,on,4,0,logs/C.complete2.r2.completion.txt,2026-11-21T02:37:37,2026-11-21T02:37:55,0,WindowServer,1,, +C,heldout/complete2,complete,2,llama.cpp draft-mtp,3,1086,1086,2882.0000,,,17.5543,516,,461,362,on,4,0,logs/C.complete2.r2.mtp3.txt,2026-11-21T02:34:37,2026-11-21T02:34:59,0,com.apple.AppleUserHIDDrivers,0,True,1938 +C,heldout/complete2,complete,2,llama.cpp ngram-mod,,1086,1086,2715.0000,,,26.4698,513,,0,0,on,4,0,logs/C.complete2.r2.ngram.txt,2026-11-21T02:35:39,2026-11-21T02:35:57,0,mediaanalysisd,0,True,1938 +C,heldout/complete2,complete,2,qwen-vx,,1086,,2269.5556,,,22.5463,,,,,,,0,logs/C.complete2.r2.vx.txt,2026-11-21T02:41:17,2026-11-21T02:43:09,0,networkserviceproxy,1,, +C,heldout/complete2,complete,2,qwen-vx --draft,7,1086,,2271.6401,,,22.7341,,8,26,10,,,0,logs/C.complete2.r2.vxdraft7.txt,2026-11-21T02:38:35,2026-11-21T02:40:37,0,Brave,4,True,1934 +C,heldout/complete2,complete,3,llama.cpp ngram-cache,,1086,1086,2744.0000,,,31.6686,513,,168,168,on,4,0,logs/C.complete2.r3.cache.txt,2026-11-21T04:33:57,2026-11-21T04:34:17,0,WindowServer,1,True,1938 +C,heldout/complete2,complete,3,llama-completion,,1086,1086,2754.3700,,,26.1300,511,,,,on,4,0,logs/C.complete2.r3.completion.txt,2026-11-21T04:32:50,2026-11-21T04:33:17,0,WindowServer,1,, +C,heldout/complete2,complete,3,llama.cpp draft-mtp,3,1086,1086,2868.0000,,,17.9826,516,,461,362,on,4,0,logs/C.complete2.r3.mtp3.txt,2026-11-21T04:35:55,2026-11-21T04:36:09,0,WindowServer,1,True,1938 +C,heldout/complete2,complete,3,llama.cpp ngram-mod,,1086,1086,2732.0000,,,26.4405,513,,0,0,on,4,0,logs/C.complete2.r3.ngram.txt,2026-11-21T04:34:57,2026-11-21T04:35:15,0,airportd,1,True,1938 +C,heldout/complete2,complete,3,qwen-vx,,1086,,2278.4038,,,22.4875,,,,,,,0,logs/C.complete2.r3.vx.txt,2026-11-21T04:26:50,2026-11-21T04:28:57,0,WindowServer,1,, +C,heldout/complete2,complete,3,qwen-vx --draft,7,1086,,2276.2482,,,22.6398,,8,26,10,,,0,logs/C.complete2.r3.vxdraft7.txt,2026-11-21T04:29:58,2026-11-21T04:32:00,0,dasd,1,True,1934 +C,heldout/complete3,complete,1,llama.cpp ngram-cache,,1288,1288,3207.0000,,,21.1520,513,,328,328,on,4,0,logs/C.complete3.r1.cache.txt,2026-11-21T01:28:33,2026-11-21T01:28:48,0,WindowServer,0,False,1395 +C,heldout/complete3,complete,1,llama-completion,,1288,1288,3227.9900,,,26.1600,511,,,,on,4,0,logs/C.complete3.r1.completion.txt,2026-11-21T01:27:16,2026-11-21T01:27:43,0,WindowServer,0,, +C,heldout/complete3,complete,1,llama.cpp draft-mtp,3,1288,1288,3368.0000,,,16.7029,515,,428,372,on,4,0,logs/C.complete3.r1.mtp3.txt,2026-11-21T01:30:28,2026-11-21T01:30:42,0,WindowServer,0,False,1395 +C,heldout/complete3,complete,1,llama.cpp ngram-mod,,1288,1288,3190.0000,,,30.0721,513,,41,41,on,4,0,logs/C.complete3.r1.ngram.txt,2026-11-21T01:29:28,2026-11-21T01:29:48,0,WindowServer,0,False,1395 +C,heldout/complete3,complete,1,qwen-vx,,1288,,2710.2742,,,22.6013,,,,,,,0,logs/C.complete3.r1.vx.txt,2026-11-21T01:21:50,2026-11-21T01:23:45,0,WindowServer,0,, +C,heldout/complete3,complete,1,qwen-vx --draft,7,1288,,2708.2827,,,20.2735,,42,231,155,,,0,logs/C.complete3.r1.vxdraft7.txt,2026-11-21T01:24:25,2026-11-21T01:26:36,0,WindowServer,0,True,1384 +C,heldout/complete3,complete,2,llama.cpp ngram-cache,,1288,1288,3221.0000,,,21.1111,513,,328,328,on,4,0,logs/C.complete3.r2.cache.txt,2026-11-21T03:13:51,2026-11-21T03:14:06,0,WindowServer,2,False,1395 +C,heldout/complete3,complete,2,llama-completion,,1288,1288,3220.5700,,,26.5000,511,,,,on,4,0,logs/C.complete3.r2.completion.txt,2026-11-21T03:14:46,2026-11-21T03:15:04,0,WindowServer,2,, +C,heldout/complete3,complete,2,llama.cpp draft-mtp,3,1288,1288,3384.0000,,,16.2214,515,,428,372,on,4,0,logs/C.complete3.r2.mtp3.txt,2026-11-21T03:11:48,2026-11-21T03:12:11,0,launchd,2,False,1395 +C,heldout/complete3,complete,2,llama.cpp ngram-mod,,1288,1288,3196.0000,,,30.2963,513,,41,41,on,4,0,logs/C.complete3.r2.ngram.txt,2026-11-21T03:12:51,2026-11-21T03:13:11,0,WindowServer,2,False,1395 +C,heldout/complete3,complete,2,qwen-vx,,1288,,2718.7490,,,22.4401,,,,,,,0,logs/C.complete3.r2.vx.txt,2026-11-21T03:18:27,2026-11-21T03:20:19,0,WindowServer,6,, +C,heldout/complete3,complete,2,qwen-vx --draft,7,1288,,2716.3320,,,20.2679,,42,231,155,,,0,logs/C.complete3.r2.vxdraft7.txt,2026-11-21T03:15:44,2026-11-21T03:17:47,0,WindowServer,2,True,1384 +C,heldout/complete3,complete,3,llama.cpp ngram-cache,,1288,1288,3213.0000,,,20.9552,513,,328,328,on,4,0,logs/C.complete3.r3.cache.txt,2026-11-21T05:11:05,2026-11-21T05:11:20,0,WindowServer,8,False,1395 +C,heldout/complete3,complete,3,llama-completion,,1288,1288,3219.1100,,,26.1800,511,,,,on,4,0,logs/C.complete3.r3.completion.txt,2026-11-21T05:09:58,2026-11-21T05:10:25,0,WindowServer,1,, +C,heldout/complete3,complete,3,llama.cpp draft-mtp,3,1288,1288,3361.0000,,,16.6835,515,,428,372,on,4,0,logs/C.complete3.r3.mtp3.txt,2026-11-21T05:13:00,2026-11-21T05:13:14,0,WindowServer,5,False,1395 +C,heldout/complete3,complete,3,llama.cpp ngram-mod,,1288,1288,3191.0000,,,30.2554,513,,41,41,on,4,0,logs/C.complete3.r3.ngram.txt,2026-11-21T05:12:00,2026-11-21T05:12:20,0,WindowServer,5,False,1395 +C,heldout/complete3,complete,3,qwen-vx,,1288,,2772.8498,,,22.5281,,,,,,,0,logs/C.complete3.r3.vx.txt,2026-11-21T05:04:43,2026-11-21T05:06:36,0,WindowServer,1,, +C,heldout/complete3,complete,3,qwen-vx --draft,7,1288,,2707.7093,,,20.3162,,42,231,155,,,0,logs/C.complete3.r3.vxdraft7.txt,2026-11-21T05:07:16,2026-11-21T05:09:08,0,WindowServer,8,True,1384 +C,heldout/edit1,edit,1,llama.cpp ngram-cache,,1668,1668,4211.0000,,,18.3327,514,,385,385,on,4,0,logs/C.edit1.r1.cache.txt,2026-11-21T00:06:07,2026-11-21T00:06:22,0,WindowServer,3,True,1768 +C,heldout/edit1,edit,1,llama-completion,,1668,1668,4204.1600,,,26.2100,511,,,,on,4,0,logs/C.edit1.r1.completion.txt,2026-11-21T00:05:00,2026-11-21T00:05:27,0,WindowServer,1,, +C,heldout/edit1,edit,1,llama.cpp draft-mtp,3,1668,1668,4397.0000,,,16.1453,516,,405,381,on,4,0,logs/C.edit1.r1.mtp3.txt,2026-11-21T00:07:58,2026-11-21T00:08:13,0,PerfPowerServices,0,True,1768 +C,heldout/edit1,edit,1,llama.cpp ngram-mod,,1668,1668,4173.0000,,,20.4113,513,,233,233,on,4,0,logs/C.edit1.r1.ngram.txt,2026-11-21T00:07:02,2026-11-21T00:07:18,0,secd,2,True,1768 +C,heldout/edit1,edit,1,qwen-vx,,1668,,3452.7583,,,22.7058,,,,,,,0,logs/C.edit1.r1.vx.txt,2026-11-20T23:59:36,2026-11-21T00:01:39,0,WindowServer,1,, +C,heldout/edit1,edit,1,qwen-vx --draft,7,1668,,3449.5788,,,15.8938,,53,333,298,,,0,logs/C.edit1.r1.vxdraft7.txt,2026-11-21T00:02:19,2026-11-21T00:04:10,0,launchd,1,True,1768 +C,heldout/edit1,edit,2,llama.cpp ngram-cache,,1668,1668,4193.0000,,,18.2315,514,,385,385,on,4,0,logs/C.edit1.r2.cache.txt,2026-11-21T01:51:16,2026-11-21T01:51:31,0,WindowServer,0,True,1768 +C,heldout/edit1,edit,2,llama-completion,,1668,1668,4197.0100,,,26.4000,511,,,,on,4,0,logs/C.edit1.r2.completion.txt,2026-11-21T01:52:11,2026-11-21T01:52:30,0,mdworker_shared,0,, +C,heldout/edit1,edit,2,llama.cpp draft-mtp,3,1668,1668,4384.0000,,,15.9244,516,,405,381,on,4,0,logs/C.edit1.r2.mtp3.txt,2026-11-21T01:49:26,2026-11-21T01:49:40,0,com.apple.DriverKit-AppleBCMWLAN,0,True,1768 +C,heldout/edit1,edit,2,llama.cpp ngram-mod,,1668,1668,4165.0000,,,20.2261,513,,233,233,on,4,0,logs/C.edit1.r2.ngram.txt,2026-11-21T01:50:20,2026-11-21T01:50:36,0,com.apple.DriverKit-AppleBCMWLAN,1,True,1768 +C,heldout/edit1,edit,2,qwen-vx,,1668,,3453.4202,,,22.6147,,,,,,,0,logs/C.edit1.r2.vx.txt,2026-11-21T01:55:51,2026-11-21T01:57:54,0,airportd,0,, +C,heldout/edit1,edit,2,qwen-vx --draft,7,1668,,3470.2876,,,15.9014,,53,333,298,,,0,logs/C.edit1.r2.vxdraft7.txt,2026-11-21T01:53:10,2026-11-21T01:55:11,0,com.apple.AppleUserHIDDrivers,0,True,1768 +C,heldout/edit1,edit,3,llama.cpp ngram-cache,,1668,1668,4207.0000,,,18.2490,514,,385,385,on,4,0,logs/C.edit1.r3.cache.txt,2026-11-21T03:45:52,2026-11-21T03:46:06,0,WindowServer,1,True,1768 +C,heldout/edit1,edit,3,llama-completion,,1668,1668,4216.3600,,,26.6800,511,,,,on,4,0,logs/C.edit1.r3.completion.txt,2026-11-21T03:44:44,2026-11-21T03:45:12,0,WindowServer,1,, +C,heldout/edit1,edit,3,llama.cpp draft-mtp,3,1668,1668,4409.0000,,,15.6609,516,,405,381,on,4,0,logs/C.edit1.r3.mtp3.txt,2026-11-21T03:47:43,2026-11-21T03:47:57,0,WindowServer,1,True,1768 +C,heldout/edit1,edit,3,llama.cpp ngram-mod,,1668,1668,4179.0000,,,20.3314,513,,233,233,on,4,0,logs/C.edit1.r3.ngram.txt,2026-11-21T03:46:47,2026-11-21T03:47:02,0,WindowServer,1,True,1768 +C,heldout/edit1,edit,3,qwen-vx,,1668,,3490.7608,,,22.6113,,,,,,,0,logs/C.edit1.r3.vx.txt,2026-11-21T03:39:26,2026-11-21T03:41:21,0,WindowServer,6,, +C,heldout/edit1,edit,3,qwen-vx --draft,7,1668,,3464.2582,,,15.9053,,53,333,298,,,0,logs/C.edit1.r3.vxdraft7.txt,2026-11-21T03:42:01,2026-11-21T03:43:53,0,WindowServer,8,True,1768 +C,heldout/edit2,edit,1,llama.cpp ngram-cache,,1286,1286,3202.0000,,,12.7102,521,,447,447,on,4,0,logs/C.edit2.r1.cache.txt,2026-11-21T00:42:28,2026-11-21T00:42:39,0,WindowServer,3,True,2049 +C,heldout/edit2,edit,1,llama-completion,,1286,1286,3216.5600,,,26.2900,511,,,,on,4,0,logs/C.edit2.r1.completion.txt,2026-11-21T00:41:22,2026-11-21T00:41:48,0,WindowServer,2,, +C,heldout/edit2,edit,1,llama.cpp draft-mtp,3,1286,1286,3347.0000,,,15.8835,515,,390,385,on,4,0,logs/C.edit2.r1.mtp3.txt,2026-11-21T00:44:08,2026-11-21T00:44:22,0,WindowServer,0,True,2049 +C,heldout/edit2,edit,1,llama.cpp ngram-mod,,1286,1286,3179.0000,,,6.8804,577,,544,544,on,4,0,logs/C.edit2.r1.ngram.txt,2026-11-21T00:43:20,2026-11-21T00:43:28,0,WindowServer,0,True,2049 +C,heldout/edit2,edit,1,qwen-vx,,1286,,2705.6172,,,22.5249,,,,,,,0,logs/C.edit2.r1.vx.txt,2026-11-21T00:36:21,2026-11-21T00:38:13,0,WindowServer,0,, +C,heldout/edit2,edit,1,qwen-vx --draft,7,1286,,2709.7208,,,11.4550,,64,439,439,,,0,logs/C.edit2.r1.vxdraft7.txt,2026-11-21T00:38:53,2026-11-21T00:40:42,0,WindowServer,0,True,2049 +C,heldout/edit2,edit,2,llama.cpp ngram-cache,,1286,1286,3186.0000,,,11.9789,521,,447,447,on,4,0,logs/C.edit2.r2.cache.txt,2026-11-21T02:27:46,2026-11-21T02:27:57,0,Brave,1,True,2049 +C,heldout/edit2,edit,2,llama-completion,,1286,1286,3190.7200,,,26.1600,511,,,,on,4,0,logs/C.edit2.r2.completion.txt,2026-11-21T02:28:37,2026-11-21T02:28:55,0,ZoomUpdater,0,, +C,heldout/edit2,edit,2,llama.cpp draft-mtp,3,1286,1286,3353.0000,,,15.4854,515,,390,385,on,4,0,logs/C.edit2.r2.mtp3.txt,2026-11-21T02:25:46,2026-11-21T02:26:07,0,com.apple.AppleUserHIDDrivers,0,True,2049 +C,heldout/edit2,edit,2,llama.cpp ngram-mod,,1286,1286,3170.0000,,,7.0537,577,,544,544,on,4,0,logs/C.edit2.r2.ngram.txt,2026-11-21T02:26:58,2026-11-21T02:27:06,0,WindowServer,0,True,2049 +C,heldout/edit2,edit,2,qwen-vx,,1286,,2692.2803,,,22.4906,,,,,,,0,logs/C.edit2.r2.vx.txt,2026-11-21T02:32:03,2026-11-21T02:33:56,0,Brave,0,, +C,heldout/edit2,edit,2,qwen-vx --draft,7,1286,,2700.5296,,,11.4601,,64,439,439,,,0,logs/C.edit2.r2.vxdraft7.txt,2026-11-21T02:29:35,2026-11-21T02:31:22,0,identityservicesd,0,True,2049 +C,heldout/edit2,edit,3,llama.cpp ngram-cache,,1286,1286,3201.0000,,,12.6161,521,,447,447,on,4,0,logs/C.edit2.r3.cache.txt,2026-11-21T04:24:08,2026-11-21T04:24:19,0,WindowServer,8,True,2049 +C,heldout/edit2,edit,3,llama-completion,,1286,1286,3212.3600,,,26.1100,511,,,,on,4,0,logs/C.edit2.r3.completion.txt,2026-11-21T04:23:01,2026-11-21T04:23:27,0,WindowServer,6,, +C,heldout/edit2,edit,3,llama.cpp draft-mtp,3,1286,1286,3344.0000,,,15.1515,515,,390,385,on,4,0,logs/C.edit2.r3.mtp3.txt,2026-11-21T04:25:47,2026-11-21T04:26:00,0,WindowServer,2,True,2049 +C,heldout/edit2,edit,3,llama.cpp ngram-mod,,1286,1286,3191.0000,,,6.8943,577,,544,544,on,4,0,logs/C.edit2.r3.ngram.txt,2026-11-21T04:24:59,2026-11-21T04:25:07,0,WindowServer,1,True,2049 +C,heldout/edit2,edit,3,qwen-vx,,1286,,2708.8540,,,22.5119,,,,,,,0,logs/C.edit2.r3.vx.txt,2026-11-21T04:17:50,2026-11-21T04:19:42,0,WindowServer,1,, +C,heldout/edit2,edit,3,qwen-vx --draft,7,1286,,2710.6094,,,11.4599,,64,439,439,,,0,logs/C.edit2.r3.vxdraft7.txt,2026-11-21T04:20:22,2026-11-21T04:22:21,0,WindowServer,12,True,2049 +C,heldout/edit3,edit,1,llama.cpp ngram-cache,,1605,1605,4051.0000,,,12.9981,521,,429,429,on,4,0,logs/C.edit3.r1.cache.txt,2026-11-21T01:19:13,2026-11-21T01:19:25,0,WindowServer,2,True,1909 +C,heldout/edit3,edit,1,llama-completion,,1605,1605,4070.2600,,,26.2500,511,,,,on,4,0,logs/C.edit3.r1.completion.txt,2026-11-21T01:18:05,2026-11-21T01:18:32,0,WindowServer,1,, +C,heldout/edit3,edit,1,llama.cpp draft-mtp,3,1605,1605,4247.0000,,,15.7539,516,,398,383,on,4,0,logs/C.edit3.r1.mtp3.txt,2026-11-21T01:20:56,2026-11-21T01:21:10,0,WindowServer,1,True,1909 +C,heldout/edit3,edit,1,llama.cpp ngram-mod,,1605,1605,4020.0000,,,10.9084,513,,422,422,on,4,0,logs/C.edit3.r1.ngram.txt,2026-11-21T01:20:05,2026-11-21T01:20:16,0,WindowServer,0,True,1909 +C,heldout/edit3,edit,1,qwen-vx,,1605,,3330.4064,,,22.6265,,,,,,,0,logs/C.edit3.r1.vx.txt,2026-11-21T01:13:01,2026-11-21T01:14:54,0,WindowServer,0,, +C,heldout/edit3,edit,1,qwen-vx --draft,7,1605,,3354.5887,,,12.6061,,58,400,399,,,0,logs/C.edit3.r1.vxdraft7.txt,2026-11-21T01:15:34,2026-11-21T01:17:25,0,WindowServer,0,True,1870 +C,heldout/edit3,edit,2,llama.cpp ngram-cache,,1605,1605,4045.0000,,,12.0499,521,,429,429,on,4,0,logs/C.edit3.r2.cache.txt,2026-11-21T03:04:42,2026-11-21T03:04:54,0,WindowServer,1,True,1909 +C,heldout/edit3,edit,2,llama-completion,,1605,1605,4043.5500,,,26.3800,511,,,,on,4,0,logs/C.edit3.r2.completion.txt,2026-11-21T03:05:44,2026-11-21T03:06:03,0,WindowServer,2,, +C,heldout/edit3,edit,2,llama.cpp draft-mtp,3,1605,1605,4273.0000,,,15.2364,516,,398,383,on,4,0,logs/C.edit3.r2.mtp3.txt,2026-11-21T03:02:49,2026-11-21T03:03:11,0,WindowServer,1,True,1909 +C,heldout/edit3,edit,2,llama.cpp ngram-mod,,1605,1605,4022.0000,,,10.7446,513,,422,422,on,4,0,logs/C.edit3.r2.ngram.txt,2026-11-21T03:03:51,2026-11-21T03:04:02,0,WindowServer,1,True,1909 +C,heldout/edit3,edit,2,qwen-vx,,1605,,3337.7790,,,22.6756,,,,,,,0,logs/C.edit3.r2.vx.txt,2026-11-21T03:09:13,2026-11-21T03:11:08,0,WindowServer,7,, +C,heldout/edit3,edit,2,qwen-vx --draft,7,1605,,3341.3913,,,12.6017,,58,400,399,,,0,logs/C.edit3.r2.vxdraft7.txt,2026-11-21T03:06:43,2026-11-21T03:08:33,0,WindowServer,2,True,1870 +C,heldout/edit3,edit,3,llama.cpp ngram-cache,,1605,1605,4065.0000,,,12.1996,521,,429,429,on,4,0,logs/C.edit3.r3.cache.txt,2026-11-21T05:01:56,2026-11-21T05:02:08,0,WindowServer,1,True,1909 +C,heldout/edit3,edit,3,llama-completion,,1605,1605,4074.9000,,,26.1900,511,,,,on,4,0,logs/C.edit3.r3.completion.txt,2026-11-21T05:00:49,2026-11-21T05:01:16,0,launchd,1,, +C,heldout/edit3,edit,3,llama.cpp draft-mtp,3,1605,1605,4241.0000,,,15.5853,516,,398,383,on,4,0,logs/C.edit3.r3.mtp3.txt,2026-11-21T05:03:49,2026-11-21T05:04:03,0,WindowServer,1,True,1909 +C,heldout/edit3,edit,3,llama.cpp ngram-mod,,1605,1605,4027.0000,,,10.6550,513,,422,422,on,4,0,logs/C.edit3.r3.ngram.txt,2026-11-21T05:02:58,2026-11-21T05:03:09,0,WindowServer,1,True,1909 +C,heldout/edit3,edit,3,qwen-vx,,1605,,3339.5896,,,22.6152,,,,,,,0,logs/C.edit3.r3.vx.txt,2026-11-21T04:55:45,2026-11-21T04:57:29,0,WindowServer,1,, +C,heldout/edit3,edit,3,qwen-vx --draft,7,1605,,3386.0958,,,12.6134,,58,400,399,,,0,logs/C.edit3.r3.vxdraft7.txt,2026-11-21T04:58:09,2026-11-21T05:00:08,0,WindowServer,6,True,1870 +C,heldout/explain1,explain,1,llama.cpp ngram-cache,,1503,1503,3634.0000,,,32.5117,514,,147,147,on,4,0,logs/C.explain1.r1.cache.txt,2026-11-21T00:33:24,2026-11-21T00:33:46,0,WindowServer,1,True,1943 +C,heldout/explain1,explain,1,llama-completion,,1503,1503,3644.8100,,,26.2600,511,,,,on,4,0,logs/C.explain1.r1.completion.txt,2026-11-21T00:32:17,2026-11-21T00:32:44,0,WindowServer,1,, +C,heldout/explain1,explain,1,llama.cpp draft-mtp,3,1503,1503,3789.0000,,,20.5523,516,,529,339,on,4,0,logs/C.explain1.r1.mtp3.txt,2026-11-21T00:35:25,2026-11-21T00:35:41,0,WindowServer,1,True,1943 +C,heldout/explain1,explain,1,llama.cpp ngram-mod,,1503,1503,3609.0000,,,26.4873,513,,0,0,on,4,0,logs/C.explain1.r1.ngram.txt,2026-11-21T00:34:26,2026-11-21T00:34:44,0,WindowServer,1,True,1943 +C,heldout/explain1,explain,1,qwen-vx,,1503,,3107.1677,,,22.6435,,,,,,,0,logs/C.explain1.r1.vx.txt,2026-11-21T00:27:09,2026-11-21T00:29:03,0,WindowServer,1,, +C,heldout/explain1,explain,1,qwen-vx --draft,7,1503,,3107.4643,,,22.7101,,7,25,12,,,0,logs/C.explain1.r1.vxdraft7.txt,2026-11-21T00:29:43,2026-11-21T00:31:37,0,WindowServer,1,True,1879 +C,heldout/explain1,explain,2,llama.cpp ngram-cache,,1503,1503,3621.0000,,,32.4922,514,,147,147,on,4,0,logs/C.explain1.r2.cache.txt,2026-11-21T02:18:38,2026-11-21T02:19:00,0,UserEventAgent,0,True,1943 +C,heldout/explain1,explain,2,llama-completion,,1503,1503,3626.7400,,,26.2900,511,,,,on,4,0,logs/C.explain1.r2.completion.txt,2026-11-21T02:19:40,2026-11-21T02:19:58,0,dasd,0,, +C,heldout/explain1,explain,2,llama.cpp draft-mtp,3,1503,1503,3775.0000,,,20.6802,516,,529,339,on,4,0,logs/C.explain1.r2.mtp3.txt,2026-11-21T02:16:34,2026-11-21T02:16:59,0,com.apple.AppleUserHIDDrivers,0,True,1943 +C,heldout/explain1,explain,2,llama.cpp ngram-mod,,1503,1503,3599.0000,,,26.4561,513,,0,0,on,4,0,logs/C.explain1.r2.ngram.txt,2026-11-21T02:17:40,2026-11-21T02:17:58,0,com.apple.AppleUserHIDDrivers,0,True,1943 +C,heldout/explain1,explain,2,qwen-vx,,1503,,3099.8023,,,22.5733,,,,,,,0,logs/C.explain1.r2.vx.txt,2026-11-21T02:23:11,2026-11-21T02:25:05,0,airportd,0,, +C,heldout/explain1,explain,2,qwen-vx --draft,7,1503,,3095.9432,,,22.6980,,7,25,12,,,0,logs/C.explain1.r2.vxdraft7.txt,2026-11-21T02:20:38,2026-11-21T02:22:31,0,Google,0,True,1879 +C,heldout/explain1,explain,3,llama.cpp ngram-cache,,1503,1503,3626.0000,,,32.5253,514,,147,147,on,4,0,logs/C.explain1.r3.cache.txt,2026-11-21T04:14:43,2026-11-21T04:15:04,0,WindowServer,1,True,1943 +C,heldout/explain1,explain,3,llama-completion,,1503,1503,3643.4700,,,26.2300,511,,,,on,4,0,logs/C.explain1.r3.completion.txt,2026-11-21T04:13:26,2026-11-21T04:13:52,0,WindowServer,7,, +C,heldout/explain1,explain,3,llama.cpp draft-mtp,3,1503,1503,3785.0000,,,20.1434,516,,529,339,on,4,0,logs/C.explain1.r3.mtp3.txt,2026-11-21T04:16:43,2026-11-21T04:16:59,0,WindowServer,1,True,1943 +C,heldout/explain1,explain,3,llama.cpp ngram-mod,,1503,1503,3607.0000,,,26.8538,513,,0,0,on,4,0,logs/C.explain1.r3.ngram.txt,2026-11-21T04:15:44,2026-11-21T04:16:03,0,WindowServer,1,True,1943 +C,heldout/explain1,explain,3,qwen-vx,,1503,,3108.5722,,,22.6926,,,,,,,0,logs/C.explain1.r3.vx.txt,2026-11-21T04:07:47,2026-11-21T04:09:51,0,WindowServer,1,, +C,heldout/explain1,explain,3,qwen-vx --draft,7,1503,,3126.0266,,,22.7059,,7,25,12,,,0,logs/C.explain1.r3.vxdraft7.txt,2026-11-21T04:10:51,2026-11-21T04:12:45,0,WindowServer,1,True,1879 +C,heldout/explain2,explain,1,llama.cpp ngram-cache,,1330,1330,3288.0000,,,28.2073,521,,242,242,on,4,0,logs/C.explain2.r1.cache.txt,2026-11-21T01:10:08,2026-11-21T01:10:27,0,mdworker_shared,1,True,2000 +C,heldout/explain2,explain,1,llama-completion,,1330,1330,3298.6900,,,26.1600,511,,,,on,4,0,logs/C.explain2.r1.completion.txt,2026-11-21T01:09:01,2026-11-21T01:09:28,0,WindowServer,1,, +C,heldout/explain2,explain,1,llama.cpp draft-mtp,3,1330,1330,3434.0000,,,18.8624,516,,483,355,on,4,0,logs/C.explain2.r1.mtp3.txt,2026-11-21T01:12:06,2026-11-21T01:12:21,0,cfprefsd,0,True,2000 +C,heldout/explain2,explain,1,llama.cpp ngram-mod,,1330,1330,3270.0000,,,27.3996,513,,19,19,on,4,0,logs/C.explain2.r1.ngram.txt,2026-11-21T01:11:07,2026-11-21T01:11:26,0,WindowServer,0,True,2000 +C,heldout/explain2,explain,1,qwen-vx,,1330,,2761.4377,,,22.5397,,,,,,,0,logs/C.explain2.r1.vx.txt,2026-11-21T01:03:44,2026-11-21T01:05:38,0,WindowServer,1,, +C,heldout/explain2,explain,1,qwen-vx --draft,7,1330,,2758.7025,,,21.5236,,28,112,76,,,0,logs/C.explain2.r1.vxdraft7.txt,2026-11-21T01:06:28,2026-11-21T01:08:21,0,com.apple.AppleUserHIDDrivers,1,True,2034 +C,heldout/explain2,explain,2,llama.cpp ngram-cache,,1330,1330,3292.0000,,,27.9655,521,,242,242,on,4,0,logs/C.explain2.r2.cache.txt,2026-11-21T02:55:11,2026-11-21T02:55:30,0,WindowServer,1,True,2000 +C,heldout/explain2,explain,2,llama-completion,,1330,1330,3292.7600,,,26.2500,511,,,,on,4,0,logs/C.explain2.r2.completion.txt,2026-11-21T02:56:11,2026-11-21T02:56:29,0,WindowServer,0,, +C,heldout/explain2,explain,2,llama.cpp draft-mtp,3,1330,1330,3440.0000,,,18.2771,516,,483,355,on,4,0,logs/C.explain2.r2.mtp3.txt,2026-11-21T02:53:09,2026-11-21T02:53:33,0,WindowServer,1,True,2000 +C,heldout/explain2,explain,2,llama.cpp ngram-mod,,1330,1330,3273.0000,,,27.3158,513,,19,19,on,4,0,logs/C.explain2.r2.ngram.txt,2026-11-21T02:54:13,2026-11-21T02:54:31,0,WindowServer,1,True,2000 +C,heldout/explain2,explain,2,qwen-vx,,1330,,2761.4815,,,22.5465,,,,,,,0,logs/C.explain2.r2.vx.txt,2026-11-21T03:00:05,2026-11-21T03:01:58,0,WindowServer,15,, +C,heldout/explain2,explain,2,qwen-vx --draft,7,1330,,2771.2173,,,21.5677,,28,112,76,,,0,logs/C.explain2.r2.vxdraft7.txt,2026-11-21T02:57:09,2026-11-21T02:59:04,0,WindowServer,1,True,2034 +C,heldout/explain2,explain,3,llama.cpp ngram-cache,,1330,1330,3281.0000,,,28.3858,521,,242,242,on,4,0,logs/C.explain2.r3.cache.txt,2026-11-21T04:52:42,2026-11-21T04:53:01,0,WindowServer,1,True,2000 +C,heldout/explain2,explain,3,llama-completion,,1330,1330,3298.8900,,,26.2700,511,,,,on,4,0,logs/C.explain2.r3.completion.txt,2026-11-21T04:51:15,2026-11-21T04:51:42,0,WindowServer,8,, +C,heldout/explain2,explain,3,llama.cpp draft-mtp,3,1330,1330,3426.0000,,,18.1357,516,,483,355,on,4,0,logs/C.explain2.r3.mtp3.txt,2026-11-21T04:54:41,2026-11-21T04:54:55,0,WindowServer,1,True,2000 +C,heldout/explain2,explain,3,llama.cpp ngram-mod,,1330,1330,3265.0000,,,27.7271,513,,19,19,on,4,0,logs/C.explain2.r3.ngram.txt,2026-11-21T04:53:42,2026-11-21T04:54:00,0,WindowServer,1,True,2000 +C,heldout/explain2,explain,3,qwen-vx,,1330,,2754.8339,,,22.5325,,,,,,,0,logs/C.explain2.r3.vx.txt,2026-11-21T04:45:58,2026-11-21T04:47:52,0,WindowServer,1,, +C,heldout/explain2,explain,3,qwen-vx --draft,7,1330,,2751.4257,,,21.4809,,28,112,76,,,0,logs/C.explain2.r3.vxdraft7.txt,2026-11-21T04:48:42,2026-11-21T04:50:35,0,WindowServer,1,True,2034 +C,heldout/explain3,explain,1,llama.cpp ngram-cache,,1257,1257,3132.0000,,,31.7461,516,,113,113,on,4,0,logs/C.explain3.r1.cache.txt,2026-11-21T01:46:32,2026-11-21T01:46:52,0,com.apple.AppleUserHIDDrivers,0,False,983 +C,heldout/explain3,explain,1,llama-completion,,1257,1257,3143.6200,,,26.1500,511,,,,on,4,0,logs/C.explain3.r1.completion.txt,2026-11-21T01:45:25,2026-11-21T01:45:51,0,airportd,0,, +C,heldout/explain3,explain,1,llama.cpp draft-mtp,3,1257,1257,3272.0000,,,19.8012,513,,526,337,on,4,0,logs/C.explain3.r1.mtp3.txt,2026-11-21T01:48:31,2026-11-21T01:48:46,0,airportd,1,False,457 +C,heldout/explain3,explain,1,llama.cpp ngram-mod,,1257,1257,3115.0000,,,26.6238,513,,0,0,on,4,0,logs/C.explain3.r1.ngram.txt,2026-11-21T01:47:32,2026-11-21T01:47:50,0,Brave,1,False,457 +C,heldout/explain3,explain,1,qwen-vx,,1257,,2603.5409,,,22.5180,,,,,,,0,logs/C.explain3.r1.vx.txt,2026-11-21T01:40:17,2026-11-21T01:42:10,0,com.apple.AppleUserHIDDrivers,0,, +C,heldout/explain3,explain,1,qwen-vx --draft,7,1257,,2604.6684,,,22.6552,,0,0,0,,,0,logs/C.explain3.r1.vxdraft7.txt,2026-11-21T01:42:50,2026-11-21T01:44:45,0,1.6 ps,0,True,2144 +C,heldout/explain3,explain,2,llama.cpp ngram-cache,,1257,1257,3135.0000,,,31.7500,516,,113,113,on,4,0,logs/C.explain3.r2.cache.txt,2026-11-21T03:32:08,2026-11-21T03:32:29,0,WindowServer,8,False,983 +C,heldout/explain3,explain,2,llama-completion,,1257,1257,3146.1000,,,26.2500,511,,,,on,4,0,logs/C.explain3.r2.completion.txt,2026-11-21T03:33:09,2026-11-21T03:33:27,0,WindowServer,7,, +C,heldout/explain3,explain,2,llama.cpp draft-mtp,3,1257,1257,3295.0000,,,20.7680,513,,526,337,on,4,0,logs/C.explain3.r2.mtp3.txt,2026-11-21T03:29:55,2026-11-21T03:30:20,0,WindowServer,1,False,457 +C,heldout/explain3,explain,2,llama.cpp ngram-mod,,1257,1257,3126.0000,,,26.4386,513,,0,0,on,4,0,logs/C.explain3.r2.ngram.txt,2026-11-21T03:31:00,2026-11-21T03:31:18,0,WindowServer,2,False,457 +C,heldout/explain3,explain,2,qwen-vx,,1257,,2624.0096,,,22.5074,,,,,,,0,logs/C.explain3.r2.vx.txt,2026-11-21T03:36:43,2026-11-21T03:38:46,0,WindowServer,1,, +C,heldout/explain3,explain,2,qwen-vx --draft,7,1257,,2634.2647,,,22.6478,,0,0,0,,,0,logs/C.explain3.r2.vxdraft7.txt,2026-11-21T03:34:07,2026-11-21T03:36:03,0,WindowServer,6,True,2144 +C,heldout/explain3,explain,3,llama.cpp ngram-cache,,1257,1257,3136.0000,,,31.8702,516,,113,113,on,4,0,logs/C.explain3.r3.cache.txt,2026-11-21T05:29:25,2026-11-21T05:29:46,0,WindowServer,6,False,983 +C,heldout/explain3,explain,3,llama-completion,,1257,1257,3147.4100,,,26.1500,511,,,,on,4,0,logs/C.explain3.r3.completion.txt,2026-11-21T05:28:19,2026-11-21T05:28:45,0,launchd,6,, +C,heldout/explain3,explain,3,llama.cpp draft-mtp,3,1257,1257,3269.0000,,,20.6413,513,,526,337,on,4,0,logs/C.explain3.r3.mtp3.txt,2026-11-21T05:31:24,2026-11-21T05:31:40,0,WindowServer,7,False,457 +C,heldout/explain3,explain,3,llama.cpp ngram-mod,,1257,1257,3120.0000,,,26.6530,513,,0,0,on,4,0,logs/C.explain3.r3.ngram.txt,2026-11-21T05:30:26,2026-11-21T05:30:44,0,WindowServer,11,False,457 +C,heldout/explain3,explain,3,qwen-vx,,1257,,2636.3289,,,22.5208,,,,,,,0,logs/C.explain3.r3.vx.txt,2026-11-21T05:22:59,2026-11-21T05:24:53,0,WindowServer,1,, +C,heldout/explain3,explain,3,qwen-vx --draft,7,1257,,2607.2359,,,22.8557,,0,0,0,,,0,logs/C.explain3.r3.vxdraft7.txt,2026-11-21T05:25:44,2026-11-21T05:27:38,0,mdworker_shared,1,True,2144 +C,heldout/write1,write,1,llama.cpp ngram-cache,,44,44,233.0000,,,28.3216,513,,218,218,on,4,0,logs/C.write1.r1.cache.txt,2026-11-21T00:24:27,2026-11-21T00:24:43,0,WindowServer,0,False,773 +C,heldout/write1,write,1,llama-completion,,44,44,239.7800,,,25.7000,511,,,,on,4,0,logs/C.write1.r1.completion.txt,2026-11-21T00:23:24,2026-11-21T00:23:47,0,networkserviceproxy,0,, +C,heldout/write1,write,1,llama.cpp draft-mtp,3,44,44,268.0000,,,16.1012,514,,434,369,on,4,0,logs/C.write1.r1.mtp3.txt,2026-11-21T00:26:18,2026-11-21T00:26:29,0,launchd,0,False,773 +C,heldout/write1,write,1,llama.cpp ngram-mod,,44,44,234.0000,,,25.9805,513,,0,0,on,4,0,logs/C.write1.r1.ngram.txt,2026-11-21T00:25:23,2026-11-21T00:25:38,0,WindowServer,0,False,773 +C,heldout/write1,write,1,qwen-vx,,44,,321.4834,,,22.2826,,,,,,,0,logs/C.write1.r1.vx.txt,2026-11-21T00:18:10,2026-11-21T00:20:11,0,WindowServer,1,, +C,heldout/write1,write,1,qwen-vx --draft,7,44,,343.6083,,,22.3432,,16,58,28,,,0,logs/C.write1.r1.vxdraft7.txt,2026-11-21T00:20:51,2026-11-21T00:22:43,0,WindowServer,0,True,1764 +C,heldout/write1,write,2,llama.cpp ngram-cache,,44,44,234.0000,,,28.0780,513,,218,218,on,4,0,logs/C.write1.r2.cache.txt,2026-11-21T02:09:33,2026-11-21T02:09:49,0,Google,0,False,773 +C,heldout/write1,write,2,llama-completion,,44,44,238.7800,,,25.9200,511,,,,on,4,0,logs/C.write1.r2.completion.txt,2026-11-21T02:10:29,2026-11-21T02:10:44,0,airportd,0,, +C,heldout/write1,write,2,llama.cpp draft-mtp,3,44,44,268.0000,,,16.2062,514,,434,369,on,4,0,logs/C.write1.r2.mtp3.txt,2026-11-21T02:07:39,2026-11-21T02:07:58,0,com.apple.AppleUserHIDDrivers,0,False,773 +C,heldout/write1,write,2,llama.cpp ngram-mod,,44,44,234.0000,,,26.1287,513,,0,0,on,4,0,logs/C.write1.r2.ngram.txt,2026-11-21T02:08:38,2026-11-21T02:08:53,0,com.apple.AppleUserHIDDrivers,1,False,773 +C,heldout/write1,write,2,qwen-vx,,44,,323.2389,,,22.2157,,,,,,,0,logs/C.write1.r2.vx.txt,2026-11-21T02:13:56,2026-11-21T02:15:54,0,com.apple.DriverKit-AppleBCMWLAN,0,, +C,heldout/write1,write,2,qwen-vx --draft,7,44,,324.5988,,,22.2673,,16,58,28,,,0,logs/C.write1.r2.vxdraft7.txt,2026-11-21T02:11:24,2026-11-21T02:13:16,0,WindowServer,1,True,1764 +C,heldout/write1,write,3,llama.cpp ngram-cache,,44,44,234.0000,,,28.1150,513,,218,218,on,4,0,logs/C.write1.r3.cache.txt,2026-11-21T04:04:45,2026-11-21T04:05:01,0,WindowServer,1,False,773 +C,heldout/write1,write,3,llama-completion,,44,44,239.9000,,,25.8800,511,,,,on,4,0,logs/C.write1.r3.completion.txt,2026-11-21T04:03:42,2026-11-21T04:04:05,0,WindowServer,1,, +C,heldout/write1,write,3,llama.cpp draft-mtp,3,44,44,257.0000,,,16.4805,514,,434,369,on,4,0,logs/C.write1.r3.mtp3.txt,2026-11-21T04:06:46,2026-11-21T04:06:57,0,WindowServer,1,False,773 +C,heldout/write1,write,3,llama.cpp ngram-mod,,44,44,235.0000,,,26.1442,513,,0,0,on,4,0,logs/C.write1.r3.ngram.txt,2026-11-21T04:05:41,2026-11-21T04:05:56,0,WindowServer,1,False,773 +C,heldout/write1,write,3,qwen-vx,,44,,337.4423,,,22.3543,,,,,,,0,logs/C.write1.r3.vx.txt,2026-11-21T03:57:51,2026-11-21T04:00:10,0,WindowServer,1,, +C,heldout/write1,write,3,qwen-vx --draft,7,44,,350.4577,,,22.2249,,16,58,28,,,0,logs/C.write1.r3.vxdraft7.txt,2026-11-21T04:00:50,2026-11-21T04:02:52,0,WindowServer,1,True,1764 +C,heldout/write2,write,1,llama.cpp ngram-cache,,52,52,243.0000,,,32.4288,513,,191,191,on,4,0,logs/C.write2.r1.cache.txt,2026-11-21T01:01:01,2026-11-21T01:01:19,0,WindowServer,0,True,1732 +C,heldout/write2,write,1,llama-completion,,52,52,250.7800,,,25.6800,511,,,,on,4,0,logs/C.write2.r1.completion.txt,2026-11-21T00:59:57,2026-11-21T01:00:20,0,WindowServer,0,, +C,heldout/write2,write,1,llama.cpp draft-mtp,3,52,52,275.0000,,,16.3275,516,,443,368,on,4,0,logs/C.write2.r1.mtp3.txt,2026-11-21T01:02:54,2026-11-21T01:03:04,0,talagentd,1,False,1581 +C,heldout/write2,write,1,llama.cpp ngram-mod,,52,52,244.0000,,,26.0195,513,,0,0,on,4,0,logs/C.write2.r1.ngram.txt,2026-11-21T01:01:59,2026-11-21T01:02:14,0,WindowServer,0,False,1600 +C,heldout/write2,write,1,qwen-vx,,52,,334.8590,,,22.2643,,,,,,,0,logs/C.write2.r1.vx.txt,2026-11-21T00:54:34,2026-11-21T00:56:35,0,WindowServer,1,, +C,heldout/write2,write,1,qwen-vx --draft,7,52,,330.5700,,,22.4220,,1,1,0,,,0,logs/C.write2.r1.vxdraft7.txt,2026-11-21T00:57:15,2026-11-21T00:59:17,0,WindowServer,0,True,1661 +C,heldout/write2,write,2,llama.cpp ngram-cache,,52,52,244.0000,,,32.5302,513,,191,191,on,4,0,logs/C.write2.r2.cache.txt,2026-11-21T02:45:44,2026-11-21T02:46:02,0,com.apple.AppleUserHIDDrivers,0,True,1732 +C,heldout/write2,write,2,llama-completion,,52,52,248.6000,,,25.7700,511,,,,on,4,0,logs/C.write2.r2.completion.txt,2026-11-21T02:47:02,2026-11-21T02:47:17,0,com.apple.AppleUserHIDDrivers,1,, +C,heldout/write2,write,2,llama.cpp draft-mtp,3,52,52,270.0000,,,16.2965,516,,443,368,on,4,0,logs/C.write2.r2.mtp3.txt,2026-11-21T02:43:49,2026-11-21T02:44:08,0,com.apple.DriverKit-AppleBCMWLAN,0,False,1581 +C,heldout/write2,write,2,llama.cpp ngram-mod,,52,52,244.0000,,,25.9844,513,,0,0,on,4,0,logs/C.write2.r2.ngram.txt,2026-11-21T02:44:49,2026-11-21T02:45:03,0,launchd,0,False,1600 +C,heldout/write2,write,2,qwen-vx,,52,,332.7585,,,22.2178,,,,,,,0,logs/C.write2.r2.vx.txt,2026-11-21T02:50:29,2026-11-21T02:52:29,0,UserEventAgent,2,, +C,heldout/write2,write,2,qwen-vx --draft,7,52,,329.9384,,,22.4435,,1,1,0,,,0,logs/C.write2.r2.vxdraft7.txt,2026-11-21T02:47:57,2026-11-21T02:49:49,0,com.apple.AppleUserHIDDrivers,0,True,1661 +C,heldout/write2,write,3,llama.cpp ngram-cache,,52,52,245.0000,,,32.5302,513,,191,191,on,4,0,logs/C.write2.r3.cache.txt,2026-11-21T04:43:04,2026-11-21T04:43:22,0,WindowServer,8,True,1732 +C,heldout/write2,write,3,llama-completion,,52,52,250.3700,,,25.7900,511,,,,on,4,0,logs/C.write2.r3.completion.txt,2026-11-21T04:42:01,2026-11-21T04:42:24,0,WindowServer,7,, +C,heldout/write2,write,3,llama.cpp draft-mtp,3,52,52,271.0000,,,16.3876,516,,443,368,on,4,0,logs/C.write2.r3.mtp3.txt,2026-11-21T04:44:57,2026-11-21T04:45:08,0,WindowServer,1,False,1581 +C,heldout/write2,write,3,llama.cpp ngram-mod,,52,52,244.0000,,,26.0507,513,,0,0,on,4,0,logs/C.write2.r3.ngram.txt,2026-11-21T04:44:02,2026-11-21T04:44:17,0,WindowServer,6,False,1600 +C,heldout/write2,write,3,qwen-vx,,52,,332.5330,,,22.2633,,,,,,,0,logs/C.write2.r3.vx.txt,2026-11-21T04:36:49,2026-11-21T04:38:40,0,WindowServer,1,, +C,heldout/write2,write,3,qwen-vx --draft,7,52,,333.0611,,,22.3130,,1,1,0,,,0,logs/C.write2.r3.vxdraft7.txt,2026-11-21T04:39:20,2026-11-21T04:41:20,0,WindowServer,6,True,1661 +C,heldout/write3,write,1,llama.cpp ngram-cache,,35,35,208.0000,,,26.3942,515,,245,245,on,4,0,logs/C.write3.r1.cache.txt,2026-11-21T01:37:36,2026-11-21T01:37:51,0,Brave,0,True,1924 +C,heldout/write3,write,1,llama-completion,,35,35,214.7100,,,25.6600,511,,,,on,4,0,logs/C.write3.r1.completion.txt,2026-11-21T01:36:33,2026-11-21T01:36:56,0,airportd,0,, +C,heldout/write3,write,1,llama.cpp draft-mtp,3,35,35,230.0000,,,15.3333,516,,404,381,on,4,0,logs/C.write3.r1.mtp3.txt,2026-11-21T01:39:26,2026-11-21T01:39:36,0,com.apple.AppleUserHIDDrivers,0,True,1924 +C,heldout/write3,write,1,llama.cpp ngram-mod,,35,35,209.0000,,,26.8343,513,,15,15,on,4,0,logs/C.write3.r1.ngram.txt,2026-11-21T01:38:31,2026-11-21T01:38:46,0,com.apple.AppleUserHIDDrivers,1,True,1924 +C,heldout/write3,write,1,qwen-vx,,35,,295.8100,,,22.3148,,,,,,,0,logs/C.write3.r1.vx.txt,2026-11-21T01:31:22,2026-11-21T01:33:13,0,WindowServer,1,, +C,heldout/write3,write,1,qwen-vx --draft,7,35,,302.2209,,,20.7403,,30,125,91,,,0,logs/C.write3.r1.vxdraft7.txt,2026-11-21T01:33:54,2026-11-21T01:35:52,0,com.apple.AppleUserHIDDrivers,0,True,1942 +C,heldout/write3,write,2,llama.cpp ngram-cache,,35,35,208.0000,,,26.4097,515,,245,245,on,4,0,logs/C.write3.r2.cache.txt,2026-11-21T03:22:53,2026-11-21T03:23:07,0,WindowServer,1,True,1924 +C,heldout/write3,write,2,llama-completion,,35,35,212.8800,,,25.8000,511,,,,on,4,0,logs/C.write3.r2.completion.txt,2026-11-21T03:23:58,2026-11-21T03:24:12,0,WindowServer,1,, +C,heldout/write3,write,2,llama.cpp draft-mtp,3,35,35,230.0000,,,14.8992,516,,404,381,on,4,0,logs/C.write3.r2.mtp3.txt,2026-11-21T03:20:59,2026-11-21T03:21:17,0,WindowServer,1,True,1924 +C,heldout/write3,write,2,llama.cpp ngram-mod,,35,35,209.0000,,,26.6569,513,,15,15,on,4,0,logs/C.write3.r2.ngram.txt,2026-11-21T03:21:57,2026-11-21T03:22:12,0,WindowServer,1,True,1924 +C,heldout/write3,write,2,qwen-vx,,35,,307.1400,,,22.2127,,,,,,,0,logs/C.write3.r2.vx.txt,2026-11-21T03:27:22,2026-11-21T03:29:15,0,WindowServer,8,, +C,heldout/write3,write,2,qwen-vx --draft,7,35,,300.8695,,,20.7624,,30,125,91,,,0,logs/C.write3.r2.vxdraft7.txt,2026-11-21T03:24:53,2026-11-21T03:26:42,0,WindowServer,1,True,1942 +C,heldout/write3,write,3,llama.cpp ngram-cache,,35,35,208.0000,,,26.3748,515,,245,245,on,4,0,logs/C.write3.r3.cache.txt,2026-11-21T05:20:18,2026-11-21T05:20:33,0,launchd,11,True,1924 +C,heldout/write3,write,3,llama-completion,,35,35,214.6800,,,25.9400,511,,,,on,4,0,logs/C.write3.r3.completion.txt,2026-11-21T05:19:15,2026-11-21T05:19:38,0,WindowServer,6,, +C,heldout/write3,write,3,llama.cpp draft-mtp,3,35,35,232.0000,,,15.3140,516,,404,381,on,4,0,logs/C.write3.r3.mtp3.txt,2026-11-21T05:22:09,2026-11-21T05:22:19,0,WindowServer,8,True,1924 +C,heldout/write3,write,3,llama.cpp ngram-mod,,35,35,209.0000,,,27.3626,513,,15,15,on,4,0,logs/C.write3.r3.ngram.txt,2026-11-21T05:21:13,2026-11-21T05:21:29,0,WindowServer,8,True,1924 +C,heldout/write3,write,3,qwen-vx,,35,,305.9733,,,22.2383,,,,,,,0,logs/C.write3.r3.vx.txt,2026-11-21T05:13:54,2026-11-21T05:15:55,0,WindowServer,1,, +C,heldout/write3,write,3,qwen-vx --draft,7,35,,305.0898,,,20.7515,,30,125,91,,,0,logs/C.write3.r3.vxdraft7.txt,2026-11-21T05:16:46,2026-11-21T05:18:35,0,WindowServer,1,True,1942 +P,context/ctx2048,ctx,1,llama-completion,,2048,2048,5067.7000,,,0.0000,1,,,,on,4,0,logs/P.llama.ctx2048.r1.txt,2026-11-20T17:57:00,2026-11-20T17:57:14,0,airportd,0,, +P,context/ctx2048,ctx,2,llama-completion,,2048,2048,5045.8900,,,0.0000,1,,,,on,4,0,logs/P.llama.ctx2048.r2.txt,2026-11-20T18:05:49,2026-11-20T18:06:04,0,com.apple.DriverKit-AppleBCMWLAN,0,, +P,context/ctx2048,ctx,3,llama-completion,,2048,2048,5173.5200,,,0.0000,1,,,,on,4,0,logs/P.llama.ctx2048.r3.txt,2026-11-20T18:19:51,2026-11-20T18:20:08,0,99.0 clang++,1,, +P,context/ctx512,ctx,1,llama-completion,,512,512,1220.3200,,,0.0000,1,,,,on,4,0,logs/P.llama.ctx512.r1.txt,2026-11-20T17:53:35,2026-11-20T17:53:46,0,com.apple.AppleUserHIDDrivers,0,, +P,context/ctx512,ctx,2,llama-completion,,512,512,1223.0800,,,0.0000,1,,,,on,4,0,logs/P.llama.ctx512.r2.txt,2026-11-20T18:02:26,2026-11-20T18:02:28,0,com.apple.DriverKit-AppleBCMWLAN,1,, +P,context/ctx512,ctx,3,llama-completion,,512,512,1217.2600,,,0.0000,1,,,,on,4,0,logs/P.llama.ctx512.r3.txt,2026-11-20T18:16:20,2026-11-20T18:16:31,0,clocksyncd,1,, +P,context/ctx8192,ctx,1,llama-completion,,8192,8192,22887.7400,,,0.0000,1,,,,on,4,0,logs/P.llama.ctx8192.r1.txt,2026-11-20T18:01:13,2026-11-20T18:01:46,0,airportd,0,, +P,context/ctx8192,ctx,2,llama-completion,,8192,8192,22710.5900,,,0.0000,1,,,,on,4,0,logs/P.llama.ctx8192.r2.txt,2026-11-20T18:09:16,2026-11-20T18:09:48,0,mediaanalysisd,0,, +P,context/ctx8192,ctx,3,llama-completion,,8192,8192,23065.7700,,,0.0000,1,,,,on,4,0,logs/P.llama.ctx8192.r3.txt,2026-11-20T18:33:10,2026-11-20T18:33:43,0,com.apple.DriverKit-AppleBCMWLAN,1,, +P,context/ctx2048,ctx,1,qwen-vx,,2048,,4178.9961,4162.7092,4154.1 4179.0,,,,,,,,0,logs/P.vx.ctx2048.r1.txt,2026-11-20T17:54:26,2026-11-20T17:56:19,0,airportd,1,, +P,context/ctx2048,ctx,2,qwen-vx,,2048,,4167.0837,4153.2874,4142.5 4167.1,,,,,,,,0,logs/P.vx.ctx2048.r2.txt,2026-11-20T18:06:44,2026-11-20T18:08:36,0,airportd,0,, +P,context/ctx2048,ctx,3,qwen-vx,,2048,,4178.8201,4170.0788,4157.1 4178.8,,,,,,,,0,logs/P.vx.ctx2048.r3.txt,2026-11-20T18:17:11,2026-11-20T18:19:11,0,com.apple.DriverKit-AppleBCMWLAN,1,, +P,context/ctx512,ctx,1,qwen-vx,,512,,1137.7344,1181.0926,1131.9 1137.7,,,,,,,,0,logs/P.vx.ctx512.r1.txt,2026-11-20T17:51:12,2026-11-20T17:52:55,0,com.apple.AppleUserHIDDrivers,0,, +P,context/ctx512,ctx,2,qwen-vx,,512,,1130.7464,1175.1494,1127.2 1130.7,,,,,,,,0,logs/P.vx.ctx512.r2.txt,2026-11-20T18:03:19,2026-11-20T18:05:09,0,launchd,0,, +P,context/ctx512,ctx,3,qwen-vx,,512,,1135.1813,1181.5621,1130.2 1135.2,,,,,,,,0,logs/P.vx.ctx512.r3.txt,2026-11-20T18:13:56,2026-11-20T18:15:39,0,com.apple.AppleUserHIDDrivers,1,, +P,context/ctx8192,ctx,1,qwen-vx,,8192,,20613.5025,18905.0179,19957.7 20613.5,,,,,,,,0,logs/P.vx.ctx8192.r1.txt,2026-11-20T17:57:55,2026-11-20T18:00:33,0,com.apple.AppleUserHIDDrivers,0,, +P,context/ctx8192,ctx,2,qwen-vx,,8192,,20603.7979,18921.4382,19930.8 20603.8,,,,,,,,0,logs/P.vx.ctx8192.r2.txt,2026-11-20T18:10:29,2026-11-20T18:13:16,0,mediaanalysisd,1,, +P,context/ctx8192,ctx,3,qwen-vx,,8192,,20768.3735,19080.6770,20402.3 20768.4,,,,,,,,0,logs/P.vx.ctx8192.r3.txt,2026-11-20T18:29:41,2026-11-20T18:32:30,0,parentalcontrolsd,1,, +T,twelve/complete1,complete,1,llama.cpp ngram-cache,,1726,1726,4274.0000,,,28.3833,514,,169,169,on,4,0,logs/T.complete1.r1.cache.txt,2026-11-20T19:20:54,2026-11-20T19:21:23,0,com.apple.AppleUserHIDDrivers,0,False,231 +T,twelve/complete1,complete,1,llama-completion,,1726,1726,4272.8700,,,26.2800,511,,,,on,4,0,logs/T.complete1.r1.completion.txt,2026-11-20T19:23:02,2026-11-20T19:23:21,0,loginwindow,1,, +T,twelve/complete1,complete,1,llama.cpp draft-mtp,1,1726,1726,4459.0000,,,22.1615,514,,270,244,on,4,0,logs/T.complete1.r1.mtp1.txt,2026-11-20T19:03:50,2026-11-20T19:04:08,0,com.apple.AppleUserHIDDrivers,0,False,231 +T,twelve/complete1,complete,1,llama.cpp draft-mtp,2,1726,1726,4474.0000,,,20.2335,514,,396,316,on,4,0,logs/T.complete1.r1.mtp2.txt,2026-11-20T19:02:54,2026-11-20T19:03:10,0,com.apple.AppleUserHIDDrivers,0,False,231 +T,twelve/complete1,complete,1,llama.cpp draft-mtp,3,1726,1726,4475.0000,,,19.5349,516,,503,348,on,4,0,logs/T.complete1.r1.mtp3.txt,2026-11-20T19:01:58,2026-11-20T19:02:14,0,com.apple.AppleUserHIDDrivers,0,False,231 +T,twelve/complete1,complete,1,llama.cpp draft-mtp,4,1726,1726,4478.0000,,,20.2229,516,,588,369,on,4,0,logs/T.complete1.r1.mtp4.txt,2026-11-20T19:01:01,2026-11-20T19:01:18,0,loginwindow,0,False,231 +T,twelve/complete1,complete,1,llama.cpp draft-mtp,6,1726,1726,4478.0000,,,22.4990,519,,814,383,on,4,0,logs/T.complete1.r1.mtp6.txt,2026-11-20T19:00:04,2026-11-20T19:00:21,0,com.apple.AppleUserHIDDrivers,0,False,231 +T,twelve/complete1,complete,1,llama.cpp ngram-mod,,1726,1726,4241.0000,,,26.4386,513,,0,0,on,4,0,logs/T.complete1.r1.ngram.txt,2026-11-20T19:22:03,2026-11-20T19:22:22,0,com.apple.AppleUserHIDDrivers,0,False,231 +T,twelve/complete1,complete,1,qwen-vx,,1726,,3502.2852,,,22.6715,,,,,,,0,logs/T.complete1.r1.vx.txt,2026-11-20T19:24:01,2026-11-20T19:25:46,0,loginwindow,1,, +T,twelve/complete1,complete,1,qwen-vx --draft,11,1726,,3508.3358,,,21.2599,,19,94,75,,,0,logs/T.complete1.r1.vxdraft11.txt,2026-11-20T19:07:30,2026-11-20T19:09:32,0,com.apple.AppleUserHIDDrivers,0,True,2315 +T,twelve/complete1,complete,1,qwen-vx --draft,15,1726,,3502.9876,,,21.3723,,19,94,75,,,0,logs/T.complete1.r1.vxdraft15.txt,2026-11-20T19:04:58,2026-11-20T19:06:50,0,com.apple.AppleUserHIDDrivers,0,True,2315 +T,twelve/complete1,complete,1,qwen-vx --draft,3,1726,,3509.1140,,,21.4751,,31,84,66,,,0,logs/T.complete1.r1.vxdraft3.txt,2026-11-20T19:18:11,2026-11-20T19:20:14,0,com.apple.AppleUserHIDDrivers,0,True,2315 +T,twelve/complete1,complete,1,qwen-vx --draft,5,1726,,3507.0016,,,21.3001,,23,89,74,,,0,logs/T.complete1.r1.vxdraft5.txt,2026-11-20T19:15:28,2026-11-20T19:17:31,0,airportd,0,True,2315 +T,twelve/complete1,complete,1,qwen-vx --draft,7,1726,,3501.8582,,,21.3487,,19,94,75,,,0,logs/T.complete1.r1.vxdraft7.txt,2026-11-20T19:12:46,2026-11-20T19:14:38,0,com.apple.AppleUserHIDDrivers,0,True,2315 +T,twelve/complete1,complete,1,qwen-vx --draft,9,1726,,3495.6191,,,21.3636,,19,94,75,,,0,logs/T.complete1.r1.vxdraft9.txt,2026-11-20T19:10:13,2026-11-20T19:12:06,0,Brave,0,True,2315 +T,twelve/complete2,complete,1,llama.cpp ngram-cache,,1608,1608,4013.0000,,,31.4016,513,,159,159,on,4,0,logs/T.complete2.r1.cache.txt,2026-11-20T21:09:01,2026-11-20T21:09:31,0,airportd,1,True,2178 +T,twelve/complete2,complete,1,llama-completion,,1608,1608,4005.0600,,,26.2900,511,,,,on,4,0,logs/T.complete2.r1.completion.txt,2026-11-20T21:11:11,2026-11-20T21:11:30,0,mdworker_shared,0,, +T,twelve/complete2,complete,1,llama.cpp draft-mtp,1,1608,1608,4190.0000,,,22.2198,514,,273,241,on,4,0,logs/T.complete2.r1.mtp1.txt,2026-11-20T20:48:01,2026-11-20T20:48:18,0,WindowServer,0,False,1213 +T,twelve/complete2,complete,1,llama.cpp draft-mtp,2,1608,1608,4194.0000,,,21.4397,514,,430,299,on,4,0,logs/T.complete2.r1.mtp2.txt,2026-11-20T20:47:05,2026-11-20T20:47:21,0,WindowServer,0,True,2178 +T,twelve/complete2,complete,1,llama.cpp draft-mtp,3,1608,1608,4194.0000,,,20.9942,516,,543,335,on,4,0,logs/T.complete2.r1.mtp3.txt,2026-11-20T20:46:08,2026-11-20T20:46:24,0,WindowServer,0,True,2178 +T,twelve/complete2,complete,1,llama.cpp draft-mtp,4,1608,1608,4189.0000,,,21.4554,516,,655,352,on,4,0,logs/T.complete2.r1.mtp4.txt,2026-11-20T20:45:11,2026-11-20T20:45:28,0,WindowServer,1,True,2178 +T,twelve/complete2,complete,1,llama.cpp draft-mtp,6,1608,1608,4199.0000,,,25.5543,516,,920,362,on,4,0,logs/T.complete2.r1.mtp6.txt,2026-11-20T20:44:12,2026-11-20T20:44:31,0,WindowServer,1,True,2178 +T,twelve/complete2,complete,1,llama.cpp ngram-mod,,1608,1608,3977.0000,,,28.2222,513,,4,4,on,4,0,logs/T.complete2.r1.ngram.txt,2026-11-20T21:10:12,2026-11-20T21:10:31,0,com.apple.AppleUserHIDDrivers,1,True,2178 +T,twelve/complete2,complete,1,qwen-vx,,1608,,3331.9206,,,22.8644,,,,,,,0,logs/T.complete2.r1.vx.txt,2026-11-20T21:12:10,2026-11-20T21:14:05,0,mDNSResponder,0,, +T,twelve/complete2,complete,1,qwen-vx --draft,11,1608,,3312.3028,,,23.0434,,4,10,1,,,0,logs/T.complete2.r1.vxdraft11.txt,2026-11-20T20:55:55,2026-11-20T20:57:49,0,WindowServer,0,True,2112 +T,twelve/complete2,complete,1,qwen-vx --draft,15,1608,,3347.1775,,,23.4376,,4,10,1,,,0,logs/T.complete2.r1.vxdraft15.txt,2026-11-20T20:48:59,2026-11-20T20:50:53,0,WindowServer,0,True,2112 +T,twelve/complete2,complete,1,qwen-vx --draft,3,1608,,3325.6428,,,22.9332,,4,8,1,,,0,logs/T.complete2.r1.vxdraft3.txt,2026-11-20T21:06:25,2026-11-20T21:08:21,0,WindowServer,1,True,2112 +T,twelve/complete2,complete,1,qwen-vx --draft,5,1608,,3349.7982,,,22.9517,,4,10,1,,,0,logs/T.complete2.r1.vxdraft5.txt,2026-11-20T21:03:50,2026-11-20T21:05:45,0,WindowServer,0,True,2112 +T,twelve/complete2,complete,1,qwen-vx --draft,7,1608,,3356.9698,,,23.0060,,4,10,1,,,0,logs/T.complete2.r1.vxdraft7.txt,2026-11-20T21:01:05,2026-11-20T21:03:10,0,WindowServer,0,True,2112 +T,twelve/complete2,complete,1,qwen-vx --draft,9,1608,,3325.0985,,,23.0035,,4,10,1,,,0,logs/T.complete2.r1.vxdraft9.txt,2026-11-20T20:58:29,2026-11-20T21:00:25,0,WindowServer,0,True,2112 +T,twelve/complete3,complete,1,llama.cpp ngram-cache,,1508,1508,3680.0000,,,29.8635,513,,209,209,on,4,0,logs/T.complete3.r1.cache.txt,2026-11-20T23:00:16,2026-11-20T23:00:45,0,WindowServer,1,True,2170 +T,twelve/complete3,complete,1,llama-completion,,1508,1508,3674.4600,,,26.3300,511,,,,on,4,0,logs/T.complete3.r1.completion.txt,2026-11-20T23:02:24,2026-11-20T23:02:42,0,WindowServer,1,, +T,twelve/complete3,complete,1,llama.cpp draft-mtp,1,1508,1508,3813.0000,,,22.2047,513,,275,238,on,4,0,logs/T.complete3.r1.mtp1.txt,2026-11-20T22:43:34,2026-11-20T22:43:50,0,com.apple.AppleUserHIDDrivers,1,True,2170 +T,twelve/complete3,complete,1,llama.cpp draft-mtp,2,1508,1508,3802.0000,,,19.9282,515,,405,312,on,4,0,logs/T.complete3.r1.mtp2.txt,2026-11-20T22:42:38,2026-11-20T22:42:54,0,PerfPowerServices,0,True,2170 +T,twelve/complete3,complete,1,llama.cpp draft-mtp,3,1508,1508,3807.0000,,,19.8585,516,,516,344,on,4,0,logs/T.complete3.r1.mtp3.txt,2026-11-20T22:41:42,2026-11-20T22:41:58,0,WindowServer,1,True,2170 +T,twelve/complete3,complete,1,llama.cpp draft-mtp,4,1508,1508,3813.0000,,,20.4275,517,,624,361,on,4,0,logs/T.complete3.r1.mtp4.txt,2026-11-20T22:40:46,2026-11-20T22:41:02,0,WindowServer,1,True,2170 +T,twelve/complete3,complete,1,llama.cpp draft-mtp,6,1508,1508,3810.0000,,,22.5607,519,,817,382,on,4,0,logs/T.complete3.r1.mtp6.txt,2026-11-20T22:39:49,2026-11-20T22:40:06,0,WindowServer,0,True,2170 +T,twelve/complete3,complete,1,llama.cpp ngram-mod,,1508,1508,3642.0000,,,26.5341,513,,0,0,on,4,0,logs/T.complete3.r1.ngram.txt,2026-11-20T23:01:25,2026-11-20T23:01:44,0,airportd,1,True,2170 +T,twelve/complete3,complete,1,qwen-vx,,1508,,3124.1751,,,22.5591,,,,,,,0,logs/T.complete3.r1.vx.txt,2026-11-20T23:03:23,2026-11-20T23:05:19,0,WindowServer,1,, +T,twelve/complete3,complete,1,qwen-vx --draft,11,1508,,3117.9786,,,20.5015,,25,117,102,,,0,logs/T.complete3.r1.vxdraft11.txt,2026-11-20T22:47:06,2026-11-20T22:49:01,0,WindowServer,1,True,2380 +T,twelve/complete3,complete,1,qwen-vx --draft,15,1508,,3123.4977,,,20.5236,,25,117,102,,,0,logs/T.complete3.r1.vxdraft15.txt,2026-11-20T22:44:30,2026-11-20T22:46:26,0,WindowServer,1,True,2380 +T,twelve/complete3,complete,1,qwen-vx --draft,3,1508,,3113.2581,,,20.6898,,39,102,88,,,0,logs/T.complete3.r1.vxdraft3.txt,2026-11-20T22:57:33,2026-11-20T22:59:36,0,WindowServer,0,True,2380 +T,twelve/complete3,complete,1,qwen-vx --draft,5,1508,,3114.1319,,,20.6182,,29,112,97,,,0,logs/T.complete3.r1.vxdraft5.txt,2026-11-20T22:54:59,2026-11-20T22:56:53,0,WindowServer,0,True,2380 +T,twelve/complete3,complete,1,qwen-vx --draft,7,1508,,3114.0170,,,20.4988,,25,117,102,,,0,logs/T.complete3.r1.vxdraft7.txt,2026-11-20T22:52:26,2026-11-20T22:54:18,0,WindowServer,0,True,2380 +T,twelve/complete3,complete,1,qwen-vx --draft,9,1508,,3121.7477,,,20.4994,,25,117,102,,,0,logs/T.complete3.r1.vxdraft9.txt,2026-11-20T22:49:41,2026-11-20T22:51:46,0,WindowServer,0,True,2380 +T,twelve/edit1,edit,1,llama.cpp ngram-cache,,1799,1799,4480.0000,,,12.1306,513,,427,427,on,4,0,logs/T.edit1.r1.cache.txt,2026-11-20T18:39:08,2026-11-20T18:39:20,0,mediaanalysisd,0,False,877 +T,twelve/edit1,edit,1,llama-completion,,1799,1799,4501.4300,,,26.4200,511,,,,on,4,0,logs/T.edit1.r1.completion.txt,2026-11-20T18:37:08,2026-11-20T18:37:36,0,bash,0,, +T,twelve/edit1,edit,1,llama.cpp draft-mtp,1,1799,1799,4690.0000,,,20.5634,513,,258,255,on,4,0,logs/T.edit1.r1.mtp1.txt,2026-11-20T18:55:21,2026-11-20T18:55:47,0,com.apple.AppleUserHIDDrivers,0,False,877 +T,twelve/edit1,edit,1,llama.cpp draft-mtp,2,1799,1799,4677.0000,,,17.0893,515,,347,341,on,4,0,logs/T.edit1.r1.mtp2.txt,2026-11-20T18:56:27,2026-11-20T18:56:42,0,com.apple.AppleUserHIDDrivers,0,False,877 +T,twelve/edit1,edit,1,llama.cpp draft-mtp,3,1799,1799,4672.0000,,,15.4516,516,,393,385,on,4,0,logs/T.edit1.r1.mtp3.txt,2026-11-20T18:57:22,2026-11-20T18:57:36,0,com.apple.AppleUserHIDDrivers,1,False,877 +T,twelve/edit1,edit,1,llama.cpp draft-mtp,4,1799,1799,4673.0000,,,14.3810,517,,430,409,on,4,0,logs/T.edit1.r1.mtp4.txt,2026-11-20T18:58:17,2026-11-20T18:58:30,0,mdworker_shared,1,False,877 +T,twelve/edit1,edit,1,llama.cpp draft-mtp,6,1799,1799,4675.0000,,,13.7669,519,,488,437,on,4,0,logs/T.edit1.r1.mtp6.txt,2026-11-20T18:59:10,2026-11-20T18:59:23,0,secd,0,False,877 +T,twelve/edit1,edit,1,llama.cpp ngram-mod,,1799,1799,4457.0000,,,10.5893,577,,486,486,on,4,0,logs/T.edit1.r1.ngram.txt,2026-11-20T18:38:16,2026-11-20T18:38:28,0,com.apple.DriverKit-AppleBCMWLAN,1,False,877 +T,twelve/edit1,edit,1,qwen-vx,,1799,,3726.3532,,,22.6464,,,,,,,0,logs/T.edit1.r1.vx.txt,2026-11-20T18:34:23,2026-11-20T18:36:18,0,com.apple.DriverKit-AppleBCMWLAN,1,, +T,twelve/edit1,edit,1,qwen-vx --draft,11,1799,,3701.5364,,,12.5069,,61,411,408,,,0,logs/T.edit1.r1.vxdraft11.txt,2026-11-20T18:50:21,2026-11-20T18:52:10,0,com.apple.AppleUserHIDDrivers,0,True,2159 +T,twelve/edit1,edit,1,qwen-vx --draft,15,1799,,3705.8387,,,12.5055,,61,411,408,,,0,logs/T.edit1.r1.vxdraft15.txt,2026-11-20T18:52:51,2026-11-20T18:54:41,0,com.apple.AppleUserHIDDrivers,0,True,2159 +T,twelve/edit1,edit,1,qwen-vx --draft,3,1799,,3705.0333,,,13.7953,,119,355,349,,,0,logs/T.edit1.r1.vxdraft3.txt,2026-11-20T18:40:00,2026-11-20T18:41:51,0,loginwindow,0,True,2159 +T,twelve/edit1,edit,1,qwen-vx --draft,5,1799,,3700.7782,,,12.8974,,80,392,389,,,0,logs/T.edit1.r1.vxdraft5.txt,2026-11-20T18:42:31,2026-11-20T18:44:21,0,Brave,1,True,2159 +T,twelve/edit1,edit,1,qwen-vx --draft,7,1799,,3707.7966,,,12.5021,,61,411,408,,,0,logs/T.edit1.r1.vxdraft7.txt,2026-11-20T18:45:02,2026-11-20T18:47:01,0,loginwindow,0,True,2159 +T,twelve/edit1,edit,1,qwen-vx --draft,9,1799,,3723.7091,,,12.4881,,61,411,408,,,0,logs/T.edit1.r1.vxdraft9.txt,2026-11-20T18:47:41,2026-11-20T18:49:41,0,com.apple.AppleUserHIDDrivers,0,True,2159 +T,twelve/edit2,edit,1,llama.cpp ngram-cache,,1577,1577,3927.0000,,,12.4545,517,,447,447,on,4,0,logs/T.edit2.r1.cache.txt,2026-11-20T20:23:02,2026-11-20T20:23:14,0,WindowServer,3,True,1966 +T,twelve/edit2,edit,1,llama-completion,,1577,1577,3925.7700,,,26.2400,511,,,,on,4,0,logs/T.edit2.r1.completion.txt,2026-11-20T20:21:06,2026-11-20T20:21:33,0,com.apple.AppleUserHIDDrivers,0,, +T,twelve/edit2,edit,1,llama.cpp draft-mtp,1,1577,1577,4135.0000,,,21.0682,513,,257,256,on,4,0,logs/T.edit2.r1.mtp1.txt,2026-11-20T20:39:33,2026-11-20T20:39:58,0,WindowServer,1,True,1966 +T,twelve/edit2,edit,1,llama.cpp draft-mtp,2,1577,1577,4103.0000,,,17.0738,515,,345,342,on,4,0,logs/T.edit2.r1.mtp2.txt,2026-11-20T20:40:38,2026-11-20T20:40:53,0,WindowServer,1,True,1966 +T,twelve/edit2,edit,1,llama.cpp draft-mtp,3,1577,1577,4111.0000,,,14.9709,516,,390,386,on,4,0,logs/T.edit2.r1.mtp3.txt,2026-11-20T20:41:33,2026-11-20T20:41:46,0,WindowServer,1,True,1966 +T,twelve/edit2,edit,1,llama.cpp draft-mtp,4,1577,1577,4103.0000,,,14.8917,517,,424,411,on,4,0,logs/T.edit2.r1.mtp4.txt,2026-11-20T20:42:26,2026-11-20T20:42:39,0,WindowServer,1,True,1966 +T,twelve/edit2,edit,1,llama.cpp draft-mtp,6,1577,1577,4107.0000,,,13.2158,519,,470,440,on,4,0,logs/T.edit2.r1.mtp6.txt,2026-11-20T20:43:20,2026-11-20T20:43:32,0,WindowServer,1,True,1966 +T,twelve/edit2,edit,1,llama.cpp ngram-mod,,1577,1577,3891.0000,,,6.8873,577,,544,544,on,4,0,logs/T.edit2.r1.ngram.txt,2026-11-20T20:22:13,2026-11-20T20:22:22,0,com.apple.AppleUserHIDDrivers,0,True,1966 +T,twelve/edit2,edit,1,qwen-vx,,1577,,3225.6608,,,22.6426,,,,,,,0,logs/T.edit2.r1.vx.txt,2026-11-20T20:18:32,2026-11-20T20:20:26,0,Brave,1,, +T,twelve/edit2,edit,1,qwen-vx --draft,11,1577,,3236.9256,,,11.5162,,64,439,439,,,0,logs/T.edit2.r1.vxdraft11.txt,2026-11-20T20:34:28,2026-11-20T20:36:24,0,airportd,1,True,1966 +T,twelve/edit2,edit,1,qwen-vx --draft,15,1577,,3231.2016,,,11.5259,,64,439,439,,,0,logs/T.edit2.r1.vxdraft15.txt,2026-11-20T20:37:05,2026-11-20T20:38:53,0,com.apple.AppleUserHIDDrivers,0,True,1966 +T,twelve/edit2,edit,1,qwen-vx --draft,3,1577,,3219.5323,,,12.8492,,126,377,377,,,0,logs/T.edit2.r1.vxdraft3.txt,2026-11-20T20:23:54,2026-11-20T20:25:42,0,com.apple.AppleUserHIDDrivers,4,True,1966 +T,twelve/edit2,edit,1,qwen-vx --draft,5,1577,,3228.2798,,,11.9315,,84,419,419,,,0,logs/T.edit2.r1.vxdraft5.txt,2026-11-20T20:26:22,2026-11-20T20:28:12,0,com.apple.DriverKit-AppleBCMWLAN,1,True,1966 +T,twelve/edit2,edit,1,qwen-vx --draft,7,1577,,3233.8855,,,11.5247,,64,439,439,,,0,logs/T.edit2.r1.vxdraft7.txt,2026-11-20T20:28:52,2026-11-20T20:30:58,0,WindowServer,1,True,1966 +T,twelve/edit2,edit,1,qwen-vx --draft,9,1577,,3255.2557,,,11.5430,,64,439,439,,,0,logs/T.edit2.r1.vxdraft9.txt,2026-11-20T20:31:38,2026-11-20T20:33:38,0,PerfPowerServices,1,True,1966 +T,twelve/edit3,edit,1,llama.cpp ngram-cache,,2251,2251,5660.0000,,,12.8983,521,,446,446,on,4,0,logs/T.edit3.r1.cache.txt,2026-11-20T22:18:45,2026-11-20T22:18:58,0,WindowServer,1,True,2046 +T,twelve/edit3,edit,1,llama-completion,,2251,2251,5671.2500,,,26.4000,511,,,,on,4,0,logs/T.edit3.r1.completion.txt,2026-11-20T22:16:44,2026-11-20T22:17:13,0,WindowServer,1,, +T,twelve/edit3,edit,1,llama.cpp draft-mtp,1,2251,2251,5941.0000,,,21.0506,514,,258,256,on,4,0,logs/T.edit3.r1.mtp1.txt,2026-11-20T22:35:00,2026-11-20T22:35:27,0,WindowServer,1,True,2046 +T,twelve/edit3,edit,1,llama.cpp draft-mtp,2,2251,2251,5921.0000,,,17.3922,515,,345,342,on,4,0,logs/T.edit3.r1.mtp2.txt,2026-11-20T22:36:07,2026-11-20T22:36:24,0,WindowServer,1,True,2046 +T,twelve/edit3,edit,1,llama.cpp draft-mtp,3,2251,2251,5937.0000,,,15.7417,515,,393,384,on,4,0,logs/T.edit3.r1.mtp3.txt,2026-11-20T22:37:04,2026-11-20T22:37:19,0,WindowServer,0,True,2046 +T,twelve/edit3,edit,1,llama.cpp draft-mtp,4,2251,2251,5918.0000,,,15.1663,517,,425,410,on,4,0,logs/T.edit3.r1.mtp4.txt,2026-11-20T22:37:59,2026-11-20T22:38:15,0,WindowServer,1,True,2046 +T,twelve/edit3,edit,1,llama.cpp draft-mtp,6,2251,2251,5934.0000,,,13.3892,519,,472,440,on,4,0,logs/T.edit3.r1.mtp6.txt,2026-11-20T22:38:55,2026-11-20T22:39:09,0,WindowServer,1,True,2046 +T,twelve/edit3,edit,1,llama.cpp ngram-mod,,2251,2251,5610.0000,,,7.9636,550,,517,517,on,4,0,logs/T.edit3.r1.ngram.txt,2026-11-20T22:17:53,2026-11-20T22:18:04,0,WindowServer,2,True,2046 +T,twelve/edit3,edit,1,qwen-vx,,2251,,4914.4177,,,22.9128,,,,,,,0,logs/T.edit3.r1.vx.txt,2026-11-20T22:14:07,2026-11-20T22:16:04,0,corespotlightd,3,, +T,twelve/edit3,edit,1,qwen-vx --draft,11,2251,,4931.2692,,,11.7946,,64,439,439,,,0,logs/T.edit3.r1.vxdraft11.txt,2026-11-20T22:30:01,2026-11-20T22:31:52,0,WindowServer,1,True,2046 +T,twelve/edit3,edit,1,qwen-vx --draft,15,2251,,4932.0188,,,11.7915,,64,439,439,,,0,logs/T.edit3.r1.vxdraft15.txt,2026-11-20T22:32:32,2026-11-20T22:34:20,0,WindowServer,1,True,2046 +T,twelve/edit3,edit,1,qwen-vx --draft,3,2251,,4927.7363,,,13.0889,,126,378,377,,,0,logs/T.edit3.r1.vxdraft3.txt,2026-11-20T22:19:38,2026-11-20T22:21:28,0,WindowServer,2,True,2046 +T,twelve/edit3,edit,1,qwen-vx --draft,5,2251,,4916.1406,,,12.1637,,84,419,419,,,0,logs/T.edit3.r1.vxdraft5.txt,2026-11-20T22:22:09,2026-11-20T22:23:59,0,networkserviceproxy,1,True,2046 +T,twelve/edit3,edit,1,qwen-vx --draft,7,2251,,4919.3130,,,11.7635,,64,439,439,,,0,logs/T.edit3.r1.vxdraft7.txt,2026-11-20T22:24:39,2026-11-20T22:26:31,0,com.apple.AppleUserHIDDrivers,1,True,2046 +T,twelve/edit3,edit,1,qwen-vx --draft,9,2251,,4913.9018,,,11.7724,,64,439,439,,,0,logs/T.edit3.r1.vxdraft9.txt,2026-11-20T22:27:11,2026-11-20T22:29:21,0,WindowServer,1,True,2046 +T,twelve/explain1,explain,1,llama.cpp ngram-cache,,1384,1384,3415.0000,,,32.2827,513,,146,146,on,4,0,logs/T.explain1.r1.cache.txt,2026-11-20T20:12:52,2026-11-20T20:13:22,0,com.apple.AppleUserHIDDrivers,0,True,1870 +T,twelve/explain1,explain,1,llama-completion,,1384,1384,3410.0700,,,26.3400,511,,,,on,4,0,logs/T.explain1.r1.completion.txt,2026-11-20T20:15:00,2026-11-20T20:15:18,0,WindowServer,0,, +T,twelve/explain1,explain,1,llama.cpp draft-mtp,1,1384,1384,3547.0000,,,22.0934,514,,275,239,on,4,0,logs/T.explain1.r1.mtp1.txt,2026-11-20T19:56:03,2026-11-20T19:56:19,0,Brave,0,True,1870 +T,twelve/explain1,explain,1,llama.cpp draft-mtp,2,1384,1384,3558.0000,,,19.9515,515,,397,316,on,4,0,logs/T.explain1.r1.mtp2.txt,2026-11-20T19:55:07,2026-11-20T19:55:23,0,WindowServer,0,True,1870 +T,twelve/explain1,explain,1,llama.cpp draft-mtp,3,1384,1384,3559.0000,,,19.3391,516,,496,350,on,4,0,logs/T.explain1.r1.mtp3.txt,2026-11-20T19:54:12,2026-11-20T19:54:27,0,com.apple.AppleUserHIDDrivers,0,True,1870 +T,twelve/explain1,explain,1,llama.cpp draft-mtp,4,1384,1384,3546.0000,,,20.0542,517,,613,363,on,4,0,logs/T.explain1.r1.mtp4.txt,2026-11-20T19:53:17,2026-11-20T19:53:32,0,secd,0,True,1870 +T,twelve/explain1,explain,1,llama.cpp draft-mtp,6,1384,1384,3551.0000,,,22.8343,519,,809,383,on,4,0,logs/T.explain1.r1.mtp6.txt,2026-11-20T19:52:20,2026-11-20T19:52:37,0,bash,0,True,1870 +T,twelve/explain1,explain,1,llama.cpp ngram-mod,,1384,1384,3389.0000,,,26.4191,513,,0,0,on,4,0,logs/T.explain1.r1.ngram.txt,2026-11-20T20:14:02,2026-11-20T20:14:20,0,com.apple.AppleUserHIDDrivers,0,True,1870 +T,twelve/explain1,explain,1,qwen-vx,,1384,,2883.6536,,,22.5856,,,,,,,0,logs/T.explain1.r1.vx.txt,2026-11-20T20:15:58,2026-11-20T20:17:52,0,com.apple.AppleUserHIDDrivers,0,, +T,twelve/explain1,explain,1,qwen-vx --draft,11,1384,,2847.9662,,,22.8211,,4,16,5,,,0,logs/T.explain1.r1.vxdraft11.txt,2026-11-20T19:59:43,2026-11-20T20:01:37,0,com.apple.AppleUserHIDDrivers,0,True,1973 +T,twelve/explain1,explain,1,qwen-vx --draft,15,1384,,2850.5559,,,22.8737,,4,16,5,,,0,logs/T.explain1.r1.vxdraft15.txt,2026-11-20T19:56:59,2026-11-20T19:59:03,0,com.apple.AppleUserHIDDrivers,0,True,1973 +T,twelve/explain1,explain,1,qwen-vx --draft,3,1384,,2853.3530,,,22.7203,,5,11,5,,,0,logs/T.explain1.r1.vxdraft3.txt,2026-11-20T20:10:10,2026-11-20T20:12:12,0,com.apple.AppleUserHIDDrivers,0,True,1973 +T,twelve/explain1,explain,1,qwen-vx --draft,5,1384,,2844.2090,,,22.8050,,4,14,5,,,0,logs/T.explain1.r1.vxdraft5.txt,2026-11-20T20:07:27,2026-11-20T20:09:29,0,apsd,0,True,1973 +T,twelve/explain1,explain,1,qwen-vx --draft,7,1384,,2848.0587,,,22.8510,,4,16,5,,,0,logs/T.explain1.r1.vxdraft7.txt,2026-11-20T20:04:52,2026-11-20T20:06:47,0,airportd,0,True,1973 +T,twelve/explain1,explain,1,qwen-vx --draft,9,1384,,2850.9722,,,22.8795,,4,16,5,,,0,logs/T.explain1.r1.vxdraft9.txt,2026-11-20T20:02:17,2026-11-20T20:04:12,0,secd,1,True,1973 +T,twelve/explain2,explain,1,llama.cpp ngram-cache,,1549,1549,3790.0000,,,30.5603,514,,138,138,on,4,0,logs/T.explain2.r1.cache.txt,2026-11-20T22:01:42,2026-11-20T22:02:11,0,com.apple.DriverKit-AppleBCMWLAN,0,True,2290 +T,twelve/explain2,explain,1,llama-completion,,1549,1549,3788.6100,,,26.4000,511,,,,on,4,0,logs/T.explain2.r1.completion.txt,2026-11-20T22:03:50,2026-11-20T22:04:09,0,WindowServer,0,, +T,twelve/explain2,explain,1,llama.cpp draft-mtp,1,1549,1549,3960.0000,,,22.9767,514,,282,232,on,4,0,logs/T.explain2.r1.mtp1.txt,2026-11-20T21:44:20,2026-11-20T21:44:37,0,clocksyncd,1,True,2290 +T,twelve/explain2,explain,1,llama.cpp draft-mtp,2,1549,1549,3972.0000,,,21.2951,515,,424,303,on,4,0,logs/T.explain2.r1.mtp2.txt,2026-11-20T21:43:23,2026-11-20T21:43:40,0,airportd,0,True,2290 +T,twelve/explain2,explain,1,llama.cpp draft-mtp,3,1549,1549,3957.0000,,,21.9205,516,,559,329,on,4,0,logs/T.explain2.r1.mtp3.txt,2026-11-20T21:42:26,2026-11-20T21:42:43,0,1.3 ps,0,True,2290 +T,twelve/explain2,explain,1,llama.cpp draft-mtp,4,1549,1549,3973.0000,,,22.3366,517,,661,351,on,4,0,logs/T.explain2.r1.mtp4.txt,2026-11-20T21:41:29,2026-11-20T21:41:46,0,com.apple.AppleUserHIDDrivers,1,True,2290 +T,twelve/explain2,explain,1,llama.cpp draft-mtp,6,1549,1549,3975.0000,,,26.0928,517,,942,359,on,4,0,logs/T.explain2.r1.mtp6.txt,2026-11-20T21:40:30,2026-11-20T21:40:49,0,bash,1,True,2290 +T,twelve/explain2,explain,1,llama.cpp ngram-mod,,1549,1549,3763.0000,,,26.5302,513,,0,0,on,4,0,logs/T.explain2.r1.ngram.txt,2026-11-20T22:02:51,2026-11-20T22:03:10,0,WindowServer,1,True,2290 +T,twelve/explain2,explain,1,qwen-vx,,1549,,3212.2445,,,22.6781,,,,,,,0,logs/T.explain2.r1.vx.txt,2026-11-20T22:04:49,2026-11-20T22:06:44,0,WindowServer,1,, +T,twelve/explain2,explain,1,qwen-vx --draft,11,1549,,3214.3540,,,22.6786,,4,13,8,,,0,logs/T.explain2.r1.vxdraft11.txt,2026-11-20T21:48:00,2026-11-20T21:50:05,0,com.apple.AppleUserHIDDrivers,0,True,2229 +T,twelve/explain2,explain,1,qwen-vx --draft,15,1549,,3197.4442,,,22.6129,,4,13,8,,,0,logs/T.explain2.r1.vxdraft15.txt,2026-11-20T21:45:17,2026-11-20T21:47:20,0,com.apple.AppleUserHIDDrivers,1,True,2229 +T,twelve/explain2,explain,1,qwen-vx --draft,3,1549,,3204.4532,,,22.4611,,4,8,8,,,0,logs/T.explain2.r1.vxdraft3.txt,2026-11-20T21:58:58,2026-11-20T22:01:02,0,com.apple.AppleUserHIDDrivers,0,True,2229 +T,twelve/explain2,explain,1,qwen-vx --draft,5,1549,,3205.0700,,,22.5532,,4,11,8,,,0,logs/T.explain2.r1.vxdraft5.txt,2026-11-20T21:56:13,2026-11-20T21:58:08,0,com.apple.AppleUserHIDDrivers,0,True,2229 +T,twelve/explain2,explain,1,qwen-vx --draft,7,1549,,3203.4469,,,22.6682,,4,13,8,,,0,logs/T.explain2.r1.vxdraft7.txt,2026-11-20T21:53:29,2026-11-20T21:55:32,0,com.apple.AppleUserHIDDrivers,1,True,2229 +T,twelve/explain2,explain,1,qwen-vx --draft,9,1549,,3199.4934,,,22.6638,,4,13,8,,,0,logs/T.explain2.r1.vxdraft9.txt,2026-11-20T21:50:45,2026-11-20T21:52:49,0,com.apple.AppleUserHIDDrivers,0,True,2229 +T,twelve/explain3,explain,1,llama.cpp ngram-cache,,1915,1915,4766.0000,,,29.0604,513,,197,197,on,4,0,logs/T.explain3.r1.cache.txt,2026-11-20T23:52:08,2026-11-20T23:52:38,0,com.apple.DriverKit-AppleBCMWLAN,1,False,1492 +T,twelve/explain3,explain,1,llama-completion,,1915,1915,4756.9200,,,26.3000,511,,,,on,4,0,logs/T.explain3.r1.completion.txt,2026-11-20T23:54:27,2026-11-20T23:54:46,0,WindowServer,1,, +T,twelve/explain3,explain,1,llama.cpp draft-mtp,1,1915,1915,4944.0000,,,21.5389,514,,269,245,on,4,0,logs/T.explain3.r1.mtp1.txt,2026-11-20T23:35:26,2026-11-20T23:35:44,0,airportd,0,True,2001 +T,twelve/explain3,explain,1,llama.cpp draft-mtp,2,1915,1915,4946.0000,,,19.9204,515,,389,320,on,4,0,logs/T.explain3.r1.mtp2.txt,2026-11-20T23:34:29,2026-11-20T23:34:46,0,com.apple.AppleUserHIDDrivers,1,False,1492 +T,twelve/explain3,explain,1,llama.cpp draft-mtp,3,1915,1915,4944.0000,,,18.8117,515,,479,355,on,4,0,logs/T.explain3.r1.mtp3.txt,2026-11-20T23:33:33,2026-11-20T23:33:49,0,WindowServer,1,False,1492 +T,twelve/explain3,explain,1,llama.cpp draft-mtp,4,1915,1915,4942.0000,,,18.8755,514,,556,374,on,4,0,logs/T.explain3.r1.mtp4.txt,2026-11-20T23:32:37,2026-11-20T23:32:53,0,WindowServer,1,True,2001 +T,twelve/explain3,explain,1,llama.cpp draft-mtp,6,1915,1915,4964.0000,,,20.6381,514,,705,395,on,4,0,logs/T.explain3.r1.mtp6.txt,2026-11-20T23:31:40,2026-11-20T23:31:57,0,WindowServer,1,True,2001 +T,twelve/explain3,explain,1,llama.cpp ngram-mod,,1915,1915,4715.0000,,,24.9864,513,,75,75,on,4,0,logs/T.explain3.r1.ngram.txt,2026-11-20T23:53:28,2026-11-20T23:53:47,0,talagentd,0,False,1492 +T,twelve/explain3,explain,1,qwen-vx,,1915,,3895.7405,,,22.7454,,,,,,,0,logs/T.explain3.r1.vx.txt,2026-11-20T23:55:26,2026-11-20T23:57:30,0,WindowServer,1,, +T,twelve/explain3,explain,1,qwen-vx --draft,11,1915,,3898.5271,,,21.3268,,19,100,79,,,0,logs/T.explain3.r1.vxdraft11.txt,2026-11-20T23:38:59,2026-11-20T23:40:54,0,com.apple.AppleUserHIDDrivers,0,True,1914 +T,twelve/explain3,explain,1,qwen-vx --draft,15,1915,,3891.1295,,,21.3747,,19,100,79,,,0,logs/T.explain3.r1.vxdraft15.txt,2026-11-20T23:36:24,2026-11-20T23:38:19,0,bash,1,True,1914 +T,twelve/explain3,explain,1,qwen-vx --draft,3,1915,,3899.8704,,,21.4289,,30,84,68,,,0,logs/T.explain3.r1.vxdraft3.txt,2026-11-20T23:49:33,2026-11-20T23:51:28,0,com.apple.AppleUserHIDDrivers,0,True,1914 +T,twelve/explain3,explain,1,qwen-vx --draft,5,1915,,3894.5093,,,21.3579,,23,98,75,,,0,logs/T.explain3.r1.vxdraft5.txt,2026-11-20T23:46:59,2026-11-20T23:48:53,0,bash,0,True,1914 +T,twelve/explain3,explain,1,qwen-vx --draft,7,1915,,3892.7813,,,21.3237,,19,100,79,,,0,logs/T.explain3.r1.vxdraft7.txt,2026-11-20T23:44:15,2026-11-20T23:46:19,0,com.apple.DriverKit-AppleBCMWLAN,3,True,1914 +T,twelve/explain3,explain,1,qwen-vx --draft,9,1915,,3919.9021,,,21.4903,,19,100,79,,,0,logs/T.explain3.r1.vxdraft9.txt,2026-11-20T23:41:34,2026-11-20T23:43:35,0,com.apple.DriverKit-AppleBCMWLAN,0,True,1914 +T,twelve/write1,write,1,llama.cpp ngram-cache,,41,41,223.0000,,,30.7709,515,,166,166,on,4,0,logs/T.write1.r1.cache.txt,2026-11-20T19:31:13,2026-11-20T19:31:31,0,com.apple.DriverKit-AppleBCMWLAN,1,False,803 +T,twelve/write1,write,1,llama-completion,,41,41,229.2300,,,25.6000,511,,,,on,4,0,logs/T.write1.r1.completion.txt,2026-11-20T19:29:05,2026-11-20T19:29:28,0,secd,0,, +T,twelve/write1,write,1,llama.cpp draft-mtp,1,41,41,249.0000,,,20.6296,513,,263,250,on,4,0,logs/T.write1.r1.mtp1.txt,2026-11-20T19:47:36,2026-11-20T19:47:58,0,com.apple.AppleUserHIDDrivers,0,False,803 +T,twelve/write1,write,1,llama.cpp draft-mtp,2,41,41,243.0000,,,17.8913,515,,363,333,on,4,0,logs/T.write1.r1.mtp2.txt,2026-11-20T19:48:38,2026-11-20T19:48:49,0,WindowServer,0,False,803 +T,twelve/write1,write,1,llama.cpp draft-mtp,3,41,41,239.0000,,,16.2287,516,,420,376,on,4,0,logs/T.write1.r1.mtp3.txt,2026-11-20T19:49:49,2026-11-20T19:49:59,0,WindowServer,2,False,803 +T,twelve/write1,write,1,llama.cpp draft-mtp,4,41,41,249.0000,,,15.8588,517,,490,394,on,4,0,logs/T.write1.r1.mtp4.txt,2026-11-20T19:50:39,2026-11-20T19:50:49,0,airportd,1,False,803 +T,twelve/write1,write,1,llama.cpp draft-mtp,6,41,41,246.0000,,,16.4778,519,,617,416,on,4,0,logs/T.write1.r1.mtp6.txt,2026-11-20T19:51:29,2026-11-20T19:51:40,0,com.apple.AppleUserHIDDrivers,0,False,803 +T,twelve/write1,write,1,llama.cpp ngram-mod,,41,41,223.0000,,,25.9123,513,,0,0,on,4,0,logs/T.write1.r1.ngram.txt,2026-11-20T19:30:18,2026-11-20T19:30:33,0,launchd,1,False,803 +T,twelve/write1,write,1,qwen-vx,,41,,344.2475,,,22.2164,,,,,,,0,logs/T.write1.r1.vx.txt,2026-11-20T19:26:26,2026-11-20T19:28:15,0,com.apple.AppleUserHIDDrivers,0,, +T,twelve/write1,write,1,qwen-vx --draft,11,41,,316.9647,,,22.2861,,3,12,8,,,0,logs/T.write1.r1.vxdraft11.txt,2026-11-20T19:42:26,2026-11-20T19:44:25,0,airportd,0,True,2201 +T,twelve/write1,write,1,qwen-vx --draft,15,41,,314.4045,,,22.2780,,3,12,8,,,0,logs/T.write1.r1.vxdraft15.txt,2026-11-20T19:45:05,2026-11-20T19:46:56,0,secd,0,True,2201 +T,twelve/write1,write,1,qwen-vx --draft,3,41,,316.0685,,,22.2751,,4,12,7,,,0,logs/T.write1.r1.vxdraft3.txt,2026-11-20T19:32:11,2026-11-20T19:34:00,0,com.apple.AppleUserHIDDrivers,1,True,2201 +T,twelve/write1,write,1,qwen-vx --draft,5,41,,338.1301,,,22.1723,,3,12,8,,,0,logs/T.write1.r1.vxdraft5.txt,2026-11-20T19:34:41,2026-11-20T19:36:33,0,com.apple.AppleUserHIDDrivers,0,True,2201 +T,twelve/write1,write,1,qwen-vx --draft,7,41,,326.6698,,,22.2241,,3,12,8,,,0,logs/T.write1.r1.vxdraft7.txt,2026-11-20T19:37:13,2026-11-20T19:39:14,0,com.apple.AppleUserHIDDrivers,0,True,2201 +T,twelve/write1,write,1,qwen-vx --draft,9,41,,323.0011,,,22.2602,,3,12,8,,,0,logs/T.write1.r1.vxdraft9.txt,2026-11-20T19:39:54,2026-11-20T19:41:46,0,dasd,0,True,2201 +T,twelve/write2,write,1,llama.cpp ngram-cache,,52,52,244.0000,,,30.7446,513,,126,126,on,4,0,logs/T.write2.r1.cache.txt,2026-11-20T21:19:26,2026-11-20T21:19:43,0,WindowServer,1,True,2039 +T,twelve/write2,write,1,llama-completion,,52,52,250.7000,,,25.6800,511,,,,on,4,0,logs/T.write2.r1.completion.txt,2026-11-20T21:17:28,2026-11-20T21:17:51,0,com.apple.AppleUserHIDDrivers,1,, +T,twelve/write2,write,1,llama.cpp draft-mtp,1,52,52,278.0000,,,22.2412,514,,280,234,on,4,0,logs/T.write2.r1.mtp1.txt,2026-11-20T21:35:58,2026-11-20T21:36:20,0,com.apple.AppleUserHIDDrivers,1,True,2039 +T,twelve/write2,write,1,llama.cpp draft-mtp,2,52,52,272.0000,,,20.1479,514,,414,307,on,4,0,logs/T.write2.r1.mtp2.txt,2026-11-20T21:37:00,2026-11-20T21:37:12,0,WindowServer,0,True,2039 +T,twelve/write2,write,1,llama.cpp draft-mtp,3,52,52,266.0000,,,19.9089,516,,528,340,on,4,0,logs/T.write2.r1.mtp3.txt,2026-11-20T21:37:53,2026-11-20T21:38:05,0,com.apple.AppleUserHIDDrivers,0,True,2039 +T,twelve/write2,write,1,llama.cpp draft-mtp,4,52,52,267.0000,,,20.3926,517,,635,358,on,4,0,logs/T.write2.r1.mtp4.txt,2026-11-20T21:38:45,2026-11-20T21:38:57,0,com.apple.DriverKit-AppleBCMWLAN,0,True,2039 +T,twelve/write2,write,1,llama.cpp draft-mtp,6,52,52,269.0000,,,21.6390,518,,813,382,on,4,0,logs/T.write2.r1.mtp6.txt,2026-11-20T21:39:37,2026-11-20T21:39:50,0,com.apple.AppleUserHIDDrivers,1,True,2039 +T,twelve/write2,write,1,llama.cpp ngram-mod,,52,52,245.0000,,,26.1969,513,,0,0,on,4,0,logs/T.write2.r1.ngram.txt,2026-11-20T21:18:31,2026-11-20T21:18:46,0,com.apple.DriverKit-AppleBCMWLAN,1,True,2039 +T,twelve/write2,write,1,qwen-vx,,52,,337.3272,,,22.2465,,,,,,,0,logs/T.write2.r1.vx.txt,2026-11-20T21:14:45,2026-11-20T21:16:38,0,airportd,1,, +T,twelve/write2,write,1,qwen-vx --draft,11,52,,333.2320,,,22.1663,,6,29,19,,,0,logs/T.write2.r1.vxdraft11.txt,2026-11-20T21:30:44,2026-11-20T21:32:35,0,com.apple.AppleUserHIDDrivers,0,True,2108 +T,twelve/write2,write,1,qwen-vx --draft,15,52,,331.7808,,,22.3505,,6,29,19,,,0,logs/T.write2.r1.vxdraft15.txt,2026-11-20T21:33:16,2026-11-20T21:35:18,0,WindowServer,2,True,2108 +T,twelve/write2,write,1,qwen-vx --draft,3,52,,331.9344,,,22.0685,,8,22,17,,,0,logs/T.write2.r1.vxdraft3.txt,2026-11-20T21:20:24,2026-11-20T21:22:23,0,com.apple.AppleUserHIDDrivers,1,True,2108 +T,twelve/write2,write,1,qwen-vx --draft,5,52,,342.2175,,,22.0305,,6,24,18,,,0,logs/T.write2.r1.vxdraft5.txt,2026-11-20T21:23:04,2026-11-20T21:24:53,0,com.apple.AppleUserHIDDrivers,0,True,2108 +T,twelve/write2,write,1,qwen-vx --draft,7,52,,334.8740,,,22.1262,,6,29,19,,,0,logs/T.write2.r1.vxdraft7.txt,2026-11-20T21:25:33,2026-11-20T21:27:24,0,Google,0,True,2108 +T,twelve/write2,write,1,qwen-vx --draft,9,52,,339.4217,,,22.1244,,6,29,19,,,0,logs/T.write2.r1.vxdraft9.txt,2026-11-20T21:28:04,2026-11-20T21:30:04,0,com.apple.AppleUserHIDDrivers,0,True,2108 +T,twelve/write3,write,1,llama.cpp ngram-cache,,39,39,214.0000,,,31.3346,514,,164,164,on,4,0,logs/T.write3.r1.cache.txt,2026-11-20T23:10:29,2026-11-20T23:10:47,0,com.apple.AppleUserHIDDrivers,0,True,1881 +T,twelve/write3,write,1,llama-completion,,39,39,220.6700,,,25.7100,511,,,,on,4,0,logs/T.write3.r1.completion.txt,2026-11-20T23:08:31,2026-11-20T23:08:54,0,networkserviceproxy,0,, +T,twelve/write3,write,1,llama.cpp draft-mtp,1,39,39,242.0000,,,20.8129,513,,266,247,on,4,0,logs/T.write3.r1.mtp1.txt,2026-11-20T23:27:15,2026-11-20T23:27:36,0,WindowServer,1,True,1881 +T,twelve/write3,write,1,llama.cpp draft-mtp,2,39,39,235.0000,,,17.7437,515,,378,326,on,4,0,logs/T.write3.r1.mtp2.txt,2026-11-20T23:28:16,2026-11-20T23:28:27,0,WindowServer,1,True,1881 +T,twelve/write3,write,1,llama.cpp draft-mtp,3,39,39,229.0000,,,16.7728,515,,444,367,on,4,0,logs/T.write3.r1.mtp3.txt,2026-11-20T23:29:07,2026-11-20T23:29:18,0,WindowServer,1,True,1881 +T,twelve/write3,write,1,llama.cpp draft-mtp,4,39,39,230.0000,,,16.9204,515,,531,382,on,4,0,logs/T.write3.r1.mtp4.txt,2026-11-20T23:29:58,2026-11-20T23:30:08,0,WindowServer,0,True,1881 +T,twelve/write3,write,1,llama.cpp draft-mtp,6,39,39,237.0000,,,18.2913,515,,682,401,on,4,0,logs/T.write3.r1.mtp6.txt,2026-11-20T23:30:48,2026-11-20T23:31:00,0,WindowServer,1,True,1881 +T,twelve/write3,write,1,llama.cpp ngram-mod,,39,39,215.0000,,,25.9844,513,,0,0,on,4,0,logs/T.write3.r1.ngram.txt,2026-11-20T23:09:34,2026-11-20T23:09:49,0,com.apple.AppleUserHIDDrivers,1,True,1881 +T,twelve/write3,write,1,qwen-vx,,39,,327.0063,,,22.2750,,,,,,,0,logs/T.write3.r1.vx.txt,2026-11-20T23:06:00,2026-11-20T23:07:51,0,WindowServer,1,, +T,twelve/write3,write,1,qwen-vx --draft,11,39,,308.2013,,,22.4314,,5,20,9,,,0,logs/T.write3.r1.vxdraft11.txt,2026-11-20T23:22:04,2026-11-20T23:23:55,0,airportd,0,True,1904 +T,twelve/write3,write,1,qwen-vx --draft,15,39,,308.6520,,,22.5029,,5,20,9,,,0,logs/T.write3.r1.vxdraft15.txt,2026-11-20T23:24:36,2026-11-20T23:26:35,0,com.apple.AppleUserHIDDrivers,1,True,1904 +T,twelve/write3,write,1,qwen-vx --draft,3,39,,304.0625,,,22.2487,,5,13,9,,,0,logs/T.write3.r1.vxdraft3.txt,2026-11-20T23:11:27,2026-11-20T23:13:27,0,airportd,0,True,1904 +T,twelve/write3,write,1,qwen-vx --draft,5,39,,310.6667,,,22.3717,,5,18,9,,,0,logs/T.write3.r1.vxdraft5.txt,2026-11-20T23:14:07,2026-11-20T23:16:11,0,WiFiAgent,0,True,1904 +T,twelve/write3,write,1,qwen-vx --draft,7,39,,337.5919,,,22.4037,,5,20,9,,,0,logs/T.write3.r1.vxdraft7.txt,2026-11-20T23:16:52,2026-11-20T23:18:51,0,WindowServer,1,True,1904 +T,twelve/write3,write,1,qwen-vx --draft,9,39,,307.3860,,,22.4124,,5,20,9,,,0,logs/T.write3.r1.vxdraft9.txt,2026-11-20T23:19:31,2026-11-20T23:21:24,0,com.apple.DriverKit-AppleBCMWLAN,0,True,1904 +fa,context/ctx2048,ctx,1,llama-completion,,2048,2048,5030.4300,,,27.6700,255,,,,off,4,0,logs/fa-off.ctx2048.r1.txt,2026-11-20T16:13:37,2026-11-20T16:13:51,0,mediaanalysisd,1,, +fa,context/ctx2048,ctx,2,llama-completion,,2048,2048,5036.3100,,,27.5100,255,,,,off,4,0,logs/fa-off.ctx2048.r2.txt,2026-11-20T16:14:31,2026-11-20T16:14:44,0,com.apple.AppleUserHIDDrivers,1,, +fa,context/ctx2048,ctx,3,llama-completion,,2048,2048,5040.9100,,,27.6700,255,,,,off,4,0,logs/fa-off.ctx2048.r3.txt,2026-11-20T16:17:10,2026-11-20T16:17:24,0,com.apple.AppleUserHIDDrivers,1,, +fa,context/ctx2048,ctx,1,llama-completion,,2048,2048,5006.3300,,,26.3300,255,,,,on,4,0,logs/fa-on.ctx2048.r1.txt,2026-11-20T16:12:36,2026-11-20T16:12:57,0,airportd,1,, +fa,context/ctx2048,ctx,2,llama-completion,,2048,2048,5006.8400,,,26.3700,255,,,,on,4,0,logs/fa-on.ctx2048.r2.txt,2026-11-20T16:15:24,2026-11-20T16:15:37,0,com.apple.AppleUserHIDDrivers,1,, +fa,context/ctx2048,ctx,3,llama-completion,,2048,2048,5003.0200,,,26.3700,255,,,,on,4,0,logs/fa-on.ctx2048.r3.txt,2026-11-20T16:16:17,2026-11-20T16:16:30,0,com.apple.AppleUserHIDDrivers,1,, diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/summary.md b/docs/benchmarks/2026-11-20-qwen36-m4/summary.md new file mode 100644 index 0000000..a60bdf4 --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/summary.md @@ -0,0 +1,129 @@ +draft lengths tried: app 3 5 7 9 11 15, MTP 1 2 3 4 6 +flash attention: on 26.37 ms, off 27.67 ms (medians at 2,048 tokens); chosen: on +flash attention: given by FA; chosen: on +draft lengths given: DRAFT=7 MTP_N=3 + +## Table A: generated tokens after a prompt + +ms for each generated token: the median of the runs, and the fastest and slowest run. The prompt time is that of the first prompt of a process. + +| Prompt tokens | qwen-vx ms | llama.cpp ms | qwen-vx tok/s | llama.cpp tok/s | llama.cpp ms / qwen-vx ms | qwen-vx prompt ms | llama.cpp prompt ms | +| ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| 64 | 22.17 (22.14-22.17) | 25.81 (25.63-26.19) | 45.1 | 38.7 | 1.164 | 351 (338-366) | 251 (251-252) | +| 512 | 22.33 (22.29-22.36) | 25.83 (25.81-25.85) | 44.8 | 38.7 | 1.157 | 1180 (1174-1203) | 1217 (1216-1217) | +| 2,048 | 22.82 (22.79-22.84) | 26.40 (26.36-26.53) | 43.8 | 37.9 | 1.157 | 4160 (4157-4168) | 5050 (5044-5056) | +| 8,192 | 24.32 (24.30-24.33) | 27.94 (27.86-27.98) | 41.1 | 35.8 | 1.149 | 18850 (18830-18928) | 22577 (22550-22622) | +| 16,384 | 26.55 (26.54-26.65) | 32.05 (32.02-32.16) | 37.7 | 31.2 | 1.207 | 45572 (45432-45955) | 53550 (53046-53562) | +| 32,768 | 43.55 (43.39-47.50) | 48.97 (48.38-55.01) | 23.0 | 20.4 | 1.124 | 129143 (128628-134961) | 138361 (138249-149488) | + +## Table P: the prompt + +Tokens of the prompt each second: the median of the runs, and the slowest and fastest run. qwen-vx ran the prompt several times in one process. The first run includes the first launch of each kernel. llama-completion ran the prompt once, after its warm-up. + +| Prompt tokens | qwen-vx first run | qwen-vx later runs | llama-completion | +| ---: | ---: | ---: | ---: | +| 512 | 433 (433-436) | 453 (450-454) | 420 (419-421) | +| 2,048 | 492 (491-493) | 492 (490-494) | 404 (396-406) | +| 8,192 | 433 (429-433) | 400 (394-411) | 358 (355-361) | + +## Table T: draft lengths, on the 12 tuning prompts + +ms for each generated token: the geometric mean over the 12 prompts, one run each. + +| Program | Draft length | ms | accepted / drafted | +| --- | ---: | ---: | ---: | +| llama-completion | | 26.16 | | +| llama.cpp draft-mtp | 1 | 21.62 | 2937 / 3226 (91%) | +| llama.cpp draft-mtp | 2 | 19.11 | 3857 / 4633 (83%) | +| llama.cpp draft-mtp | 3 | 18.15 | 4299 / 5664 (76%) | +| llama.cpp draft-mtp | 4 | 18.21 | 4534 / 6632 (68%) | +| llama.cpp draft-mtp | 6 | 19.22 | 4780 / 8549 (56%) | +| llama.cpp ngram-cache | | 24.38 | 2794 / 2794 (100%) | +| llama.cpp ngram-mod | | 19.76 | 1626 / 1626 (100%) | +| qwen-vx | | 22.59 | | +| qwen-vx --draft | 3 | 19.39 | 1372 / 1454 (94%) | +| qwen-vx --draft | 5 | 19.04 | 1522 / 1618 (94%) | +| qwen-vx --draft | 7 | 18.90 | 1592 / 1700 (94%) | +| qwen-vx --draft | 9 | 18.92 | 1592 / 1700 (94%) | +| qwen-vx --draft | 11 | 18.91 | 1592 / 1700 (94%) | +| qwen-vx --draft | 15 | 18.96 | 1592 / 1700 (94%) | + +- qwen-vx --draft: the text of qwen-vx in 72 of 72 runs +- llama.cpp ngram-cache: the text of llama-completion in 8 of 12 runs. Other text, in the summary (the number of equal characters at the start): logs/T.complete1.r1.cache.txt (231), logs/T.edit1.r1.cache.txt (877), logs/T.explain3.r1.cache.txt (1492), logs/T.write1.r1.cache.txt (803) +- llama.cpp ngram-mod: the text of llama-completion in 8 of 12 runs. Other text, in the summary (the number of equal characters at the start): logs/T.complete1.r1.ngram.txt (231), logs/T.edit1.r1.ngram.txt (877), logs/T.explain3.r1.ngram.txt (1492), logs/T.write1.r1.ngram.txt (803) +- llama.cpp draft-mtp: the text of llama-completion in 42 of 60 runs. Other text, in the summary (the number of equal characters at the start): logs/T.complete1.r1.mtp1.txt (231), logs/T.complete1.r1.mtp2.txt (231), logs/T.complete1.r1.mtp3.txt (231), logs/T.complete1.r1.mtp4.txt (231), logs/T.complete1.r1.mtp6.txt (231), logs/T.complete2.r1.mtp1.txt (1213), logs/T.edit1.r1.mtp1.txt (877), logs/T.edit1.r1.mtp2.txt (877), logs/T.edit1.r1.mtp3.txt (877), logs/T.edit1.r1.mtp4.txt (877), logs/T.edit1.r1.mtp6.txt (877), logs/T.explain3.r1.mtp2.txt (1492), logs/T.explain3.r1.mtp3.txt (1492), logs/T.write1.r1.mtp1.txt (803), logs/T.write1.r1.mtp2.txt (803), logs/T.write1.r1.mtp3.txt (803), logs/T.write1.r1.mtp4.txt (803), logs/T.write1.r1.mtp6.txt (803) + +## Table C: the 12 held-out prompts + +ms for each generated token: the geometric mean over the prompts of each kind, and the fastest and slowest run. + +| Kind | Prompt tokens | qwen-vx | qwen-vx --draft | llama-completion | llama.cpp ngram-cache | llama.cpp ngram-mod | llama.cpp draft-mtp | +| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | +| edit | 1286, 1605, 1668 | 22.60 (22.49-22.71) | 13.19 (11.45-15.91) | 26.30 (26.11-26.68) | 14.13 (11.98-18.33) | 11.50 (6.88-20.41) | 15.64 (15.15-16.15) | +| complete | 1044, 1086, 1288 | 22.49 (22.41-22.60) | 21.89 (20.27-22.81) | 26.22 (26.10-26.50) | 27.31 (20.96-31.67) | 27.63 (26.33-30.30) | 17.30 (16.22-18.15) | +| write | 35, 44, 52 | 22.26 (22.21-22.35) | 21.79 (20.74-22.44) | 25.79 (25.66-25.94) | 28.91 (26.37-32.53) | 26.35 (25.98-27.36) | 15.92 (14.90-16.48) | +| explain | 1257, 1330, 1503 | 22.56 (22.51-22.69) | 22.31 (21.48-22.86) | 26.22 (26.15-26.29) | 30.77 (27.97-32.53) | 26.88 (26.44-27.73) | 19.74 (18.14-20.77) | +| all 12 | | 22.48 (22.21-22.71) | 19.36 (11.45-22.86) | 26.13 (25.66-26.68) | 24.20 (11.98-32.53) | 21.78 (6.88-30.30) | 17.08 (14.90-20.77) | + +- qwen-vx against llama-completion: 1.162, faster on 12 of 12 prompts (1.16 to 1.17) +- qwen-vx --draft against qwen-vx: 1.161, faster on 7 of 12 prompts (0.99 to 1.96) +- qwen-vx --draft against llama-completion: 1.350, faster on 12 of 12 prompts (1.15 to 2.29) +- qwen-vx --draft against llama.cpp ngram-cache: 1.250, faster on 11 of 12 prompts (0.98 to 1.45) +- qwen-vx --draft against llama.cpp ngram-mod: 1.125, faster on 10 of 12 prompts (0.61 to 1.49) +- qwen-vx --draft against llama.cpp draft-mtp: 0.882, faster on 3 of 12 prompts (0.73 to 1.35) +- llama.cpp ngram-cache against llama-completion: 1.080, faster on 4 of 12 prompts (0.79 to 2.12) +- llama.cpp ngram-mod against llama-completion: 1.200, faster on 3 of 12 prompts (0.87 to 3.77) +- llama.cpp draft-mtp against llama-completion: 1.530, faster on 12 of 12 prompts (1.28 to 1.70) + +### Drafts, table C, round 1 + +| Kind | qwen-vx --draft accepted / drafted | llama.cpp ngram-cache accepted / drafted | llama.cpp ngram-mod accepted / drafted | llama.cpp draft-mtp accepted / drafted | +| --- | ---: | ---: | ---: | ---: | +| edit | 1136 / 1172 (97%), 6.49 per check | 1261 / 1261 (100%) | 1199 / 1199 (100%) | 1149 / 1193 (96%) | +| complete | 177 / 292 (61%), 2.95 per check | 737 / 737 (100%) | 41 / 41 (100%) | 1096 / 1348 (81%) | +| write | 119 / 184 (65%), 2.53 per check | 654 / 654 (100%) | 15 / 15 (100%) | 1118 / 1281 (87%) | +| explain | 88 / 137 (64%), 2.51 per check | 502 / 502 (100%) | 19 / 19 (100%) | 1031 / 1538 (67%) | +| all 12 | 1520 / 1785 (85%), 4.79 per check | 3154 / 3154 (100%) | 1274 / 1274 (100%) | 4394 / 5360 (82%) | + +- qwen-vx --draft: the text of qwen-vx in 36 of 36 runs +- llama.cpp ngram-cache: the text of llama-completion in 27 of 36 runs. Other text, in the summary (the number of equal characters at the start): logs/C.complete3.r1.cache.txt (1395), logs/C.complete3.r2.cache.txt (1395), logs/C.complete3.r3.cache.txt (1395), logs/C.explain3.r1.cache.txt (983), logs/C.explain3.r2.cache.txt (983), logs/C.explain3.r3.cache.txt (983), logs/C.write1.r1.cache.txt (773), logs/C.write1.r2.cache.txt (773), logs/C.write1.r3.cache.txt (773) +- llama.cpp ngram-mod: the text of llama-completion in 24 of 36 runs. Other text, in the summary (the number of equal characters at the start): logs/C.complete3.r1.ngram.txt (1395), logs/C.complete3.r2.ngram.txt (1395), logs/C.complete3.r3.ngram.txt (1395), logs/C.explain3.r1.ngram.txt (457), logs/C.explain3.r2.ngram.txt (457), logs/C.explain3.r3.ngram.txt (457), logs/C.write1.r1.ngram.txt (773), logs/C.write1.r2.ngram.txt (773), logs/C.write1.r3.ngram.txt (773), logs/C.write2.r1.ngram.txt (1600), logs/C.write2.r2.ngram.txt (1600), logs/C.write2.r3.ngram.txt (1600) +- llama.cpp draft-mtp: the text of llama-completion in 21 of 36 runs. Other text, in the summary (the number of equal characters at the start): logs/C.complete1.r1.mtp3.txt (1055), logs/C.complete1.r2.mtp3.txt (1055), logs/C.complete1.r3.mtp3.txt (1055), logs/C.complete3.r1.mtp3.txt (1395), logs/C.complete3.r2.mtp3.txt (1395), logs/C.complete3.r3.mtp3.txt (1395), logs/C.explain3.r1.mtp3.txt (457), logs/C.explain3.r2.mtp3.txt (457), logs/C.explain3.r3.mtp3.txt (457), logs/C.write1.r1.mtp3.txt (773), logs/C.write1.r2.mtp3.txt (773), logs/C.write1.r3.mtp3.txt (773), logs/C.write2.r1.mtp3.txt (1581), logs/C.write2.r2.mtp3.txt (1581), logs/C.write2.r3.mtp3.txt (1581) + +### qwen-vx and llama-completion: where the text starts to differ + +The characters at the start of the generated text that are the same, round 1. The weight files differ in the token embedding and the output matrix, so the greedy text of the two programs can differ. + +| Prompt | Same characters | Characters of llama-completion | +| --- | ---: | ---: | +| complete1 | 104 | 2085 | +| complete2 | 0 | 1938 | +| complete3 | 12 | 1427 | +| edit1 | 1768 | 1768 | +| edit2 | 2049 | 2049 | +| edit3 | 1807 | 1909 | +| explain1 | 87 | 1943 | +| explain2 | 5 | 2000 | +| explain3 | 281 | 2121 | +| write1 | 1764 | 1764 | +| write2 | 1077 | 1732 | +| write3 | 419 | 1924 | + +## llama-bench-pp + +| model | size | params | backend | threads | fa | test | t/s | +| ------------------------------ | ---------: | ---------: | ---------- | ------: | --: | --------------: | -------------------: | +| qwen35moe 35B.A3B Q4_0 | 18.35 GiB | 34.66 B | MTL,BLAS | 4 | 1 | pp512 | 426.29 ± 3.15 | +| qwen35moe 35B.A3B Q4_0 | 18.35 GiB | 34.66 B | MTL,BLAS | 4 | 1 | pp2048 | 404.80 ± 3.25 | +| qwen35moe 35B.A3B Q4_0 | 18.35 GiB | 34.66 B | MTL,BLAS | 4 | 1 | pp8192 | 343.12 ± 5.44 | + +## llama-bench-tg + +| model | size | params | backend | threads | fa | test | t/s | +| ------------------------------ | ---------: | ---------: | ---------- | ------: | --: | --------------: | -------------------: | +| qwen35moe 35B.A3B Q4_0 | 18.35 GiB | 34.66 B | MTL,BLAS | 4 | 1 | tg128 | 39.09 ± 0.17 | +| qwen35moe 35B.A3B Q4_0 | 18.35 GiB | 34.66 B | MTL,BLAS | 4 | 1 | tg128 @ d2048 | 38.25 ± 0.09 | +| qwen35moe 35B.A3B Q4_0 | 18.35 GiB | 34.66 B | MTL,BLAS | 4 | 1 | tg128 @ d8192 | 35.77 ± 0.38 | +| qwen35moe 35B.A3B Q4_0 | 18.35 GiB | 34.66 B | MTL,BLAS | 4 | 1 | tg128 @ d16384 | 27.83 ± 0.59 | +| qwen35moe 35B.A3B Q4_0 | 18.35 GiB | 34.66 B | MTL,BLAS | 4 | 1 | tg128 @ d32768 | 19.68 ± 0.05 | + diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/weights.txt b/docs/benchmarks/2026-11-20-qwen36-m4/weights.txt new file mode 100644 index 0000000..b42555c --- /dev/null +++ b/docs/benchmarks/2026-11-20-qwen36-m4/weights.txt @@ -0,0 +1,58 @@ +Checks of the two weight files, on the CPU, on 2026-11-21. Each section gives the command and its output. +VXW=~/models/Qwen3.6-35B-A3B-q4-q6.vxw GGUF=~/models/gguf/qwen36/Qwen3.6-35B-A3B-Q4_0.gguf, scripts/ of qwen-vx 3d56b14, gguf-py of llama.cpp b1b770d. + +== python3 bytes_per_token.py $VXW $GGUF scripts llama.cpp/gguf-py +config: {'arch': 1, 'conv_width': 4, 'eos_token_id': 248044, 'experts_per_token': 8, 'full_attention_interval': 4, 'head_dim': 256, 'hidden_size': 2048, 'intermediate_size': 0, 'linear_k_dim': 128, 'linear_k_heads': 16, 'linear_v_dim': 128, 'linear_v_heads': 32, 'max_positions': 262144, 'moe_intermediate_size': 512, 'num_experts': 256, 'num_kv_heads': 2, 'num_layers': 40, 'num_q_heads': 16, 'qk_norm': 1, 'qkv_bias': 0, 'rms_norm_eps': 1e-06, 'rope_theta': 10000000.0, 'rotary_dim': 64, 'shared_expert_intermediate_size': 512, 'tied_embeddings': 0, 'vocab_size': 248320, 'weight_format': 3} +app: 1.819 GB per token, file 20.389 GB + linear_in: 379.5 MB + experts_gate_up: 335.5 MB + lm_head: 254.3 MB + experts_down: 167.8 MB + lm_head.high: 127.1 MB + linear_out: 125.8 MB + qkv: 94.4 MB + linear_in.scale: 47.4 MB + router: 42.1 MB + experts_gate_up.scale: 41.9 MB + shared_gate_up: 41.9 MB + attn_out: 41.9 MB + lm_head.scale: 31.8 MB + experts_down.scale: 21.0 MB +gguf: 1.865 GB per token, file 19.704 GB + output.weight: 417.2 MB + attn_qkv.weight: 283.1 MB + ffn_down_exps.weight: 188.7 MB + ffn_gate_exps.weight: 188.7 MB + ffn_up_exps.weight: 188.7 MB + attn_gate.weight: 141.6 MB + ssm_out.weight: 141.6 MB + attn_q.weight: 94.4 MB + ffn_gate_inp.weight: 83.9 MB + attn_output.weight: 47.2 MB + ffn_down_shexp.weight: 23.6 MB + ffn_gate_shexp.weight: 23.6 MB + ffn_up_shexp.weight: 23.6 MB + attn_k.weight: 5.9 MB + +== python3 compare_bits.py $VXW $GGUF scripts llama.cpp/gguf-py +320 matrices checked in 40 layers, 0 differ: [] + +== The same check on layers 0 and 3, with one code or scale changed in memory in 8 matrices: +== experts_down, experts_gate_up (gate part), linear_in and linear_out of layer 0; qkv, attn_out, +== shared_gate_up (up part) and shared_down of layer 3. Expected: exactly these 8 differ. +16 matrices checked in 40 layers, 8 differ: ['layer 0 experts gate', 'layer 0 experts down', 'layer 0 linear in', 'layer 0 linear out', 'layer 3 shared up', 'layer 3 shared down', 'layer 3 qkv', 'layer 3 attn out'] +(The count line prints num_layers of the file, 40, though the loop ran 2 layers.) + +== python3 perplexity.py $VXW $GGUF scripts llama.cpp/gguf-py ~/models/Qwen3.6-35B-A3B policy.md speculate.vx qwen_weights.py --max-tokens 512 +== policy.md is docs/benchmarking_policy.md of Vx at 643f63b5b. speculate.vx and qwen_weights.py are src/ and scripts/ of qwen-vx at 3d56b14. +embed: Q4_0 from the GGUF, (248320, 2048) +lm_head: Q6_K from the GGUF, (248320, 2048) +quality-texts/policy.md: app forward of 512 tokens in 59 s +quality-texts/policy.md: llama.cpp forward of 512 tokens in 57 s +quality-texts/policy.md: tokens=512 perplexity app=11.9348 llama.cpp=12.1307 kl=0.012269 same_top1=94.72% +quality-texts/speculate.vx: app forward of 512 tokens in 62 s +quality-texts/speculate.vx: llama.cpp forward of 512 tokens in 72 s +quality-texts/speculate.vx: tokens=512 perplexity app=7.3574 llama.cpp=7.3558 kl=0.005107 same_top1=96.09% +quality-texts/qwen_weights.py: app forward of 512 tokens in 57 s +quality-texts/qwen_weights.py: llama.cpp forward of 512 tokens in 53 s +quality-texts/qwen_weights.py: tokens=512 perplexity app=7.1244 llama.cpp=7.1567 kl=0.007000 same_top1=96.48% diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/README.md b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/README.md new file mode 100644 index 0000000..51fa364 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/README.md @@ -0,0 +1,264 @@ +# Qwen3.6-35B-A3B on an M4: qwen-vx with MTP drafts against llama.cpp + +Run on 2026-11-25, as `docs/benchmarking_policy.md` of the Vx repository asks. The app is qwen-vx +at commit 730f1b7 (PR #113 on main, with #109 to #112), compiled by vxc 0.0.5 with `-O2`. The +baseline is llama.cpp at commit b1b770d (2026-11-13), Release build, Metal, the same commit as the +run of 2026-11-20 ([`../2026-11-20-qwen36-m4/`](../2026-11-20-qwen36-m4/README.md)). + +This run adds the drafts from the MTP layer of the model to the app (`--mtp`, entries 16 to 19 of +`docs/optimizations.md`). It measures the app with and without drafts against llama.cpp with and +without drafts. + +## Claims + +All numbers are for batch 1, greedy decoding (temperature 0), on an M4 MacBook Air with 32 GB. The +model is Qwen3.6-35B-A3B. Both files have the same Q4_0 matrices and a 6-bit output matrix (6.5 +against 6.5625 bits a weight). The "held-out prompts" are the 12 chat prompts of the 2026-11-20 run +(35 to 1,668 tokens). No setting of this run was tuned on them. Each program ran each prompt 3 +times, 512 generated tokens. A speed on the held-out prompts is the geometric mean over the 36 runs. +A ratio is the geometric mean over the 12 prompts of the ratios of the medians of each prompt. + +- **Decode with drafts:** 71.2 against 58.5 generated tokens a second (1.22×), + `qwen-vx --mtp 3,5 --draft 11` against `llama-speculative-simple --spec-type draft-mtp` (3 + tokens), Qwen3.6-35B-A3B in Q4_0 with a 6-bit output matrix, on the 12 held-out prompts, on an M4 + with 32 GB, batch 1, against llama.cpp b1b770d. qwen-vx is faster on 12 of 12 prompts (1.06× to + 1.61×). +- **Decode with MTP drafts only:** 67.8 against 58.5 tokens a second (1.16×), `qwen-vx --mtp 3,5` + against the same llama.cpp program. Faster on 12 of 12 prompts (1.06× to 1.25×). +- **Decode without drafts:** 44.8 against 38.3 tokens a second (1.17×), `qwen-vx` against + `llama-completion`. Faster on 12 of 12 prompts (1.16× to 1.18×). +- **Decode after a long prompt:** 1.16× to 1.21× from 64 to 32,768 prompt tokens (table A), for + example 41.4 against 35.7 tokens a second after 8,192 tokens. +- **Prompt:** 490 against 404 prompt tokens a second (1.21×) for a prompt of 2,048 tokens, 451 + against 419 (1.08×) at 512, and 399 against 356 (1.12×) at 8,192 (table P, the app's runs after + its first run in a process). +- **Drafts from the context:** 56.3 against 46.0 tokens a second (1.22×), `qwen-vx --draft 11` + against `llama-speculative-simple --spec-type ngram-mod`. Faster on 11 of 12 prompts (0.77× to + 1.64×). + +Each program with drafts of the app gave the text of the app without drafts in 36 of 36 runs. + +Where qwen-vx is slower: + +- **edit2 against ngram-mod.** ngram-mod takes 6.93 ms a token, against 9.51 ms for + `qwen-vx --mtp 3,5 --draft 11` and 9.07 ms for `qwen-vx --draft 11`. ngram-mod drafts up to 64 + tokens. The app drafts up to 11. This is the one prompt of 12 where `--mtp 3,5 --draft 11` is + slower than ngram-mod (0.74×). +- **Drafts from the context only, against draft-mtp:** `qwen-vx --draft 11` is 0.96× of + llama.cpp's MTP drafts, and faster on 3 of 12 prompts (the 3 edits). +- **A short first prompt.** A 64-token prompt takes 262 ms against 252 ms (table A). This is the + first prompt of the app's process, which includes the first launch of each kernel. + `llama-completion` runs a warm-up first. + +## Setup + +The machine, the OS, the model, the formats, the prompts, the order of the runs and the settings +of llama.cpp are those of the 2026-11-20 run ([Setup](../2026-11-20-qwen36-m4/README.md#setup)). +Its checks of the weight files (the same bits in the 320 Q4_0 matrices, the perplexity of the two +token embeddings and output matrices) hold for this run, because the app's file has the same 745 +tensors. What is new: + +| | qwen-vx | llama.cpp | +| --- | --- | --- | +| Program | `vxc -O2 src/main.vx` at 730f1b7, vxc 0.0.5 (5b92da4f) | b1b770d with `llama-timing.patch`, built again from the same commit with the same settings (`llama.cpp-build.txt`) | +| Weight file | `Qwen3.6-35B-A3B-q4-q6-mtp.vxw`, 20,868,300,800 bytes: the 745 tensors of the 2026-11-20 file with the same bytes, and the 22 tensors of the MTP layer after them (475,987,968 bytes) | `Qwen3.6-35B-A3B-Q4_0.gguf`, 19,715,053,888 bytes, as on 2026-11-20 | +| MTP layer | in the weight file. `append_mtp.py` added it with the functions of `scripts/convert.py`, which writes the same tensors | `mtp-Qwen3.6-35B-A3B-Q4_0.gguf` of ggml-org, 1,060,038,720 bytes | +| MTP drafts | up to 3 tokens while the running mean of the kept drafts is at least 0.85, up to 5 from 0.95, else 1 (`--mtp 3,5`). A draft scores the 65,536 tokens of the lowest ids | 3 tokens (`--spec-draft-n-max 3`). A draft scores all 248,320 tokens | +| Drafts from the context | `--draft 11`: up to 11 tokens after a match of 16 tokens, 4 after 12 to 15, 1 after 2 to 11. With `--mtp`, a round drafts from the context only after a match of 16 tokens | ngram-mod: `n_match` 24, `n_min` 48, `n_max` 64 (the defaults) | +| Settings | no "auto" setting | flash attention on, which `run.sh` chose again: 26.31 against 27.88 ms a token with it off (medians at 2,048 tokens). CPU threads: 4 (the default) | + +The draft settings come from the 12 tuning prompts (`prompts/twelve/`), not from the held-out +prompts: `--mtp 3,5` and the match of 16 from entries 16 and 19 of `docs/optimizations.md`, +`--draft 11` from `draft_length35` of `src/speculate.vx`, and 3 MTP tokens for llama.cpp from table +T of the 2026-11-20 run, with the same build of llama.cpp. This run has no table T. + +The idle check of `run.sh` now checks the machine again after the 30 s of cooling, and waits again +when another process started in them. + +## Results + +The full tables are in `summary.md`, and each run is a row of `runs.csv`. ms for each generated +token; tokens a second are 1,000 divided by the ms. + +### Table C: the 12 held-out prompts + +The geometric mean over the runs of each kind (3 prompts, 3 runs each), and the fastest and +slowest run: + +| Kind | qwen-vx | qwen-vx `--draft 11` | qwen-vx `--mtp 3,5` | qwen-vx `--mtp 3,5 --draft 11` | llama-completion | ngram-mod | draft-mtp | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| edit | 22.40 (22.31-22.48) | 11.00 (9.05-13.91) | 12.94 (12.24-13.54) | **10.62** (9.47-12.03) | 26.36 (26.15-26.53) | 11.48 (6.91-20.37) | 15.62 (15.08-16.21) | +| complete | 22.33 (22.23-22.40) | 20.28 (18.36-21.42) | 15.46 (13.97-16.78) | **15.37** (13.78-16.83) | 26.14 (26.03-26.35) | 27.66 (26.29-30.30) | 17.35 (16.42-18.10) | +| write | 22.12 (22.03-22.28) | 20.69 (19.50-21.82) | **14.11** (13.54-15.21) | 14.15 (13.58-15.21) | 25.69 (25.64-25.84) | 26.23 (25.81-26.79) | 16.05 (14.88-17.01) | +| explain | 22.38 (22.29-22.58) | 21.55 (20.40-22.57) | **16.72** (15.71-17.21) | 16.83 (16.02-17.58) | 26.24 (26.10-26.55) | 26.80 (26.35-27.68) | 19.68 (18.11-20.39) | +| all 12 | 22.31 | 17.76 | 14.74 | **14.04** | 26.10 | 21.74 | 17.10 | +| tokens a second | 44.8 | 56.3 | 67.8 | **71.2** | 38.3 | 46.0 | 58.5 | + +The median of the 3 runs of each prompt: + +| Prompt | qwen-vx | `--draft 11` | `--mtp 3,5` | `--mtp 3,5 --draft 11` | llama-completion | ngram-mod | draft-mtp | draft-mtp / best qwen-vx | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| edit1 | 22.45 | 13.89 | 13.54 | 12.02 | 26.29 | 20.35 | 15.96 | 1.33 | +| edit2 | 22.32 | 9.07 | 12.24 | 9.51 | 26.42 | 6.93 | 15.32 | 1.61 | +| edit3 | 22.40 | 10.55 | 13.06 | 10.49 | 26.32 | 10.61 | 15.70 | 1.50 | +| complete1 | 22.27 | 21.18 | 16.77 | 16.78 | 26.11 | 26.33 | 17.89 | 1.07 | +| complete2 | 22.37 | 21.42 | 15.68 | 15.66 | 26.09 | 26.39 | 17.81 | 1.14 | +| complete3 | 22.38 | 18.43 | 14.03 | 13.81 | 26.11 | 30.27 | 16.59 | 1.20 | +| write1 | 22.17 | 20.84 | 15.16 | 15.15 | 25.68 | 26.01 | 16.15 | 1.07 | +| write2 | 22.08 | 21.78 | 13.64 | 13.77 | 25.66 | 25.98 | 16.77 | 1.22 | +| write3 | 22.16 | 19.53 | 13.54 | 13.59 | 25.65 | 26.76 | 14.97 | 1.10 | +| explain1 | 22.37 | 21.80 | 17.19 | 17.20 | 26.24 | 26.53 | 20.26 | 1.18 | +| explain2 | 22.36 | 20.41 | 15.73 | 16.04 | 26.20 | 27.58 | 18.84 | 1.17 | +| explain3 | 22.32 | 22.54 | 17.13 | 17.15 | 26.14 | 26.37 | 20.15 | 1.17 | + +The last column compares draft-mtp with `--mtp 3,5 --draft 11`. The 3 runs of a case differ by at +most 5.2% (complete1, draft-mtp). + +Speed-ups, the geometric mean of the ratios of the 12 prompts (`summary.md` has all pairs): + +| | Ratio | Faster on | Range | +| --- | ---: | ---: | ---: | +| `--mtp 3,5 --draft 11` against draft-mtp | 1.218 | 12 of 12 | 1.06-1.61 | +| `--mtp 3,5` against draft-mtp | 1.161 | 12 of 12 | 1.06-1.25 | +| qwen-vx against llama-completion | 1.170 | 12 of 12 | 1.16-1.18 | +| `--mtp 3,5 --draft 11` against llama-completion | 1.859 | 12 of 12 | 1.51-2.78 | +| `--draft 11` against ngram-mod | 1.224 | 11 of 12 | 0.77-1.64 | +| `--mtp 3,5 --draft 11` against ngram-mod | 1.548 | 11 of 12 | 0.74-2.19 | +| `--mtp 3,5` against qwen-vx (own speed-up) | 1.514 | 12 of 12 | 1.30-1.82 | +| `--mtp 3,5 --draft 11` against qwen-vx (own speed-up) | 1.589 | 12 of 12 | 1.29-2.35 | +| `--mtp 3,5 --draft 11` against `--mtp 3,5` | 1.050 | 6 of 12 | 0.99-1.29 | +| draft-mtp against llama-completion (own speed-up) | 1.526 | 12 of 12 | 1.29-1.73 | +| ngram-mod against llama-completion (own speed-up) | 1.201 | 3 of 12 | 0.87-3.78 | + +The drafts from the context in the MTP rounds help the edits (10.62 against 12.94 ms, 1.22×), and +change the other kinds by 1% or less (0.99× to 1.01×). + +### Table A: generated tokens after a prompt + +256 generated tokens. The median of 3 runs, and the fastest and slowest run: + +| Prompt tokens | qwen-vx ms | llama.cpp ms | qwen-vx tok/s | llama.cpp tok/s | Ratio | +| ---: | ---: | ---: | ---: | ---: | ---: | +| 64 | 22.05 (22.03-22.08) | 25.82 (25.67-25.90) | 45.4 | 38.7 | 1.171 | +| 512 | 22.20 (22.16-22.20) | 26.03 (25.82-26.49) | 45.1 | 38.4 | 1.173 | +| 2,048 | 22.62 (22.62-22.63) | 26.26 (26.26-26.28) | 44.2 | 38.1 | 1.161 | +| 8,192 | 24.16 (24.11-24.16) | 28.02 (27.88-28.11) | 41.4 | 35.7 | 1.160 | +| 16,384 | 26.60 (26.59-26.76) | 32.27 (32.26-32.31) | 37.6 | 31.0 | 1.213 | +| 32,768 | 50.49 (48.66-51.41) | 58.90 (58.00-65.10) | 19.8 | 17.0 | 1.167 | + +`llama-bench` gave 39.05 tokens a second for tg128 and 18.86 at a depth of 32,768 (`summary.md`). + +### Table P: the prompt + +Tokens of the prompt each second, the median of 3 runs, and the slowest and fastest run. qwen-vx +ran the prompt 3 times in one process. The first run includes the first launch of each kernel. +`llama-completion` ran the prompt once, after its warm-up. + +| Prompt tokens | qwen-vx first run | qwen-vx later runs | llama-completion | Ratio, later runs | +| ---: | ---: | ---: | ---: | ---: | +| 512 | 456 (452-456) | 451 (448-453) | 419 (418-420) | 1.08 | +| 2,048 | 498 (497-499) | 490 (487-493) | 404 (403-404) | 1.21 | +| 8,192 | 431 (431-433) | 399 (394-406) | 356 (355-361) | 1.12 | + +## Speculative decoding + +Accepted and drafted tokens, table C round 1: + +| | `--draft 11` | `--mtp 3,5` | `--mtp 3,5 --draft 11` | ngram-mod | draft-mtp | +| --- | --- | --- | --- | --- | --- | +| Accepted / drafted | 2004 / 2631 (76%) | 3963 / 4744 (84%) | 4146 / 4986 (83%) | 1274 / 1274 as printed (below) | 4394 / 5360 (82%) | +| Accepted tokens for each check | 1.73 | 1.84 | 2.10 | not printed | not printed | +| Same text as without drafts | 36 of 36 runs | 36 of 36 runs | 36 of 36 runs | 24 of 36 runs | 21 of 36 runs | + +The app checks a draft with the bits of a plain step, so its text with drafts is the text of the +app without drafts in every run. + +llama.cpp with drafts writes other text in some runs, as on 2026-11-20: the same 12 runs of +ngram-mod and the same 15 runs of draft-mtp leave the text of `llama-completion`, at the same +characters (`summary.md` lists them). The summary keeps these runs. The acceptance of ngram-mod +shows 100% because `llama-speculative-simple` checks the kept tokens of a partial accept again +from a checkpoint, and its counts leave out the first check. draft-mtp uses no checkpoints, and +its counts are comparable. The draft programs of llama.cpp stop after the check that passes `-n +512`, and their speed is the decode time divided by the decoded tokens. The 2026-11-20 report +explains these points ([Speculative decoding](../2026-11-20-qwen36-m4/README.md#speculative-decoding)). + +## Limits + +- One machine, a fanless MacBook Air. The programs run interleaved, in a reversed order in round 2. +- Batch 1 and greedy decoding only. No serving numbers (section 6 of the policy). +- Decode to 32,768 prompt tokens. Prompt speed to 8,192 tokens. +- The run does not split the gain of the app into its changes. +- The two weight files differ in the token embedding and the output matrix. The 2026-11-20 run + measured both with one program. +- The MTP drafts of the app score only the 65,536 tokens of the lowest ids. This changes only the + drafts, not the text. +- The MTP layers are in other files: the app's is in its weight file, and llama.cpp reads a + GGUF of ggml-org. This run did not compare their bits. +- At 32,768 prompt tokens, both programs were slower than on 2026-11-20 (qwen-vx 43.55 to 50.49 ms, + llama.cpp 48.97 to 58.90 ms), and their runs spread more (up to 12%). The ratio was 1.12 then and + 1.17 now. The other prompt lengths of table A are within 1% of 2026-11-20. +- The prompts are code tasks in 4 kinds. Other text can give other draft gains. + +## How the run went + +1. 06:55, all stages. A browser was open from about 07:48, and some runs started with it using the + GPU. At 09:14 I stopped the run. Its output is not in this folder. +2. 09:53, all stages again, with the idle check that checks again after the cooling. It ended at + 22:34. While it ran, another job built the Vx compiler and ran its tests on the CPU, three + times: 17:14 to 17:34, 17:58 to 18:27 and 21:32 to 22:18. The idle check made most runs wait. + 8 runs of table C started in these periods: edit3 round 2 (completion, ngram-mod, draft-mtp), + complete3 round 2 (`--draft 11`), and write3 round 3 (completion, `--draft 11`, `--mtp 3,5`, + `--mtp 3,5 --draft 11`). +3. 22:41, these 8 runs again, with `RERUN` and the same `OUT`. They ended at 22:55. Their first + logs are in `logs-overlapped/` of `logs.tar.xz`. `log.txt` keeps the lines of both runs, and + `parse.py` uses the last line of each run. + +No run started with more than 5% GPU use, and every run exited with code 0. + +## Commands + +llama.cpp, as on 2026-11-20: + + git clone https://github.com/ggml-org/llama.cpp && cd llama.cpp && git checkout b1b770d + git apply /path/to/qwen-vx/docs/benchmarks/2026-11-25-qwen36-m4-mtp/llama-timing.patch + cmake -B build -DCMAKE_BUILD_TYPE=Release -DGGML_METAL=ON -DGGML_METAL_EMBED_LIBRARY=ON \ + -DGGML_NATIVE=ON -DLLAMA_CURL=OFF -DLLAMA_BUILD_MTMD=OFF -DLLAMA_BUILD_UI=OFF -DLLAMA_BUILD_TESTS=OFF + cmake --build build -j 8 --target llama-completion llama-speculative-simple llama-bench + +The model files: those of the 2026-11-20 run, and the app's weight file with the MTP layer, which +`scripts/convert.py` now writes: + + python3 scripts/convert.py --q4 --q6-lm-head ~/models/Qwen3.6-35B-A3B Qwen3.6-35B-A3B-q4-q6-mtp.vxw + +This run's file came from the 2026-11-20 file and `append_mtp.py`, which writes the same MTP +tensors with the functions of `convert.py`: + + cp -c Qwen3.6-35B-A3B-q4-q6.vxw Qwen3.6-35B-A3B-q4-q6-mtp.vxw + python3 $OUT/append_mtp.py scripts ~/models/Qwen3.6-35B-A3B Qwen3.6-35B-A3B-q4-q6-mtp.vxw + +The run, under `caffeinate -dims`, on an idle Mac, from the root of this repository: + + export OUT=docs/benchmarks/2026-11-25-qwen36-m4-mtp VXC=~/.vx/current/bin/vxc FLEET=~/.vx/current/fleet \ + VXW=Qwen3.6-35B-A3B-q4-q6-mtp.vxw VXT=Qwen3.6-35B-A3B.vxt GGUF=Qwen3.6-35B-A3B-Q4_0.gguf \ + MTP=mtp-Qwen3.6-35B-A3B-Q4_0.gguf LB=llama.cpp/build/bin + caffeinate -dims $OUT/run.sh + RERUN="C.edit3.r2.mtp3 C.edit3.r2.ngram C.edit3.r2.completion C.complete3.r2.vxdraft11 \ + C.write3.r3.vxdraft11 C.write3.r3.vxmtp C.write3.r3.vxmtpdraft11 C.write3.r3.completion" \ + STAGES=C FA=on caffeinate -dims $OUT/run.sh + python3 $OUT/parse.py $OUT + +`run.sh` prints each command line in the log of its run. + +## Files + +- `run.sh`, `parse.py`, `make_prompts.py`, `prompts/`: the script, the parser and the inputs, from + the 2026-11-20 run with the programs of the app with `--mtp` added. +- `append_mtp.py`: added the MTP layer to the app's weight file. +- `env.txt`: the machine, OS, versions, files and settings, written at each start of `run.sh`. +- `log.txt`: one line for each run, with its start, end, exit code, the busiest other process and + the GPU use at the start. +- `logs.tar.xz`: the output of each run (`tar -xJf logs.tar.xz` gives `logs/` and + `logs-overlapped/`). `parse.py` gives the same `summary.md` and `runs.csv` from `logs/`. +- `runs.csv`, `summary.md`: written by `parse.py`. +- `llama-timing.patch`, `llama.cpp.diff`, `llama.cpp-build.txt`: the patch, the diff of the + llama.cpp source that ran, and its build settings. diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/append_mtp.py b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/append_mtp.py new file mode 100644 index 0000000..307b6c8 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/append_mtp.py @@ -0,0 +1,71 @@ +"""Append the MTP layer to a copy of a q4_0_q6 weight file of Qwen3.6-35B-A3B (scratch tool). + + append_mtp.py SCRIPTS_DIR MODEL_DIR FILE + +FILE must be a clone of the weight file without the MTP layer. The script checks that the data +start stays where it is, writes the MTP tensors after the last tensor, and then rewrites the +header and tensor table as write_weight_file would for the config with mtp_layers = 1. +""" +import struct +import sys + +sys.path.insert(0, sys.argv[1]) +import numpy as np # noqa: E402 + +import convert # noqa: E402 +import qwen_weights as q # noqa: E402 + +model_dir, path = sys.argv[2], sys.argv[3] +old_config, old = q.read_weight_file(path) +assert old_config["weight_format"] == q.WEIGHT_FORMATS["q4_0_q6"] and old_config.get("mtp_layers", 0) == 0 +hf_config, hf = q.config_from_hugging_face(model_dir), q.read_safetensors(model_dir) +assert hf_config["mtp_layers"] == 1 +config, tensors = convert.convert_tensors(hf_config, hf) +config, tensors = q.quantize(config, tensors, "q4_0_q6") +for field in q.CONFIG_INTS: + if field != "mtp_layers": + assert int(config[field]) == int(old_config[field]), field +names, shapes = q.tensor_names(config), q.tensor_shapes(config) +old_names = q.tensor_names(old_config) +assert names[: len(old_names)] == old_names == list(old) + +with open(path, "rb") as f: + head = bytearray(f.read(q.TABLE_OFFSET + q.ENTRY_BYTES * len(names))) +old_start = -(-(q.TABLE_OFFSET + q.ENTRY_BYTES * len(old_names)) // q.ALIGNMENT) * q.ALIGNMENT +data_start = -(-(q.TABLE_OFFSET + q.ENTRY_BYTES * len(names)) // q.ALIGNMENT) * q.ALIGNMENT +assert data_start == old_start, "the longer table would move the data" +last = q.TABLE_OFFSET + (len(old_names) - 1) * q.ENTRY_BYTES +offset, nbytes = struct.unpack_from("<2q", head, last + 64 + 48) +offset += -(-nbytes // q.ALIGNMENT) * q.ALIGNMENT + +entries = [] +with open(path, "r+b") as out: + out.seek(0, 2) + assert out.tell() == offset, (out.tell(), offset) + for name in names[len(old_names):]: + dtype, array = q.resolve(tensors[name]) + shape = shapes[name] + assert tuple(array.shape) == q.storage_shape(dtype, shape), name + assert array.dtype == q.STORAGE[dtype], name + size = int(np.prod(shape)) * q.DTYPE_BITS[dtype] // 8 + dims = list(shape) + [0] * (4 - len(shape)) + entry = name.encode("ascii").ljust(64, b"\0") + assert len(entry) == 64, name + entry += struct.pack("<8q", q.DTYPE_CODES[dtype], len(shape), *dims, offset, size) + entries.append(entry) + out.seek(offset) + out.write(np.ascontiguousarray(array).data) + offset += -(-size // q.ALIGNMENT) * q.ALIGNMENT + print(name, dtype, shape, flush=True) + out.truncate(offset) + # The header: the count of tensors and the config integers, as write_weight_file writes them. + version = q.file_version(config) + words = [version, len(names), q.ALIGNMENT, q.TABLE_OFFSET] + [int(config[f]) for f in q.CONFIG_INTS[: q.CONFIG_INT_SLOTS[version]]] + words += [0] * (q.CONFIG_INT_SLOTS[version] - len(q.CONFIG_INTS[: q.CONFIG_INT_SLOTS[version]])) + struct.pack_into(f"<{len(words)}q", head, 8, *words) + for i, entry in enumerate(entries): + at = q.TABLE_OFFSET + (len(old_names) + i) * q.ENTRY_BYTES + head[at : at + q.ENTRY_BYTES] = entry + out.seek(0) + out.write(head) +print("wrote", len(names), "tensors, end", offset) diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/env.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/env.txt new file mode 100644 index 0000000..a70f23f --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/env.txt @@ -0,0 +1,43 @@ +date: Wed Nov 25 09:53:04 PST 2026, stages: fa bench A P C +machine: Mac16,12, Apple M4, 32 GB + Chipset Model: Apple M4 + Total Number of Cores: 10 + Metal Support: Metal 4 +macOS: 27.0.1 (26A434) +power: Now drawing from 'AC Power' +vxc: vxc 0.0.5 (5b92da4f) +qwen-vx: 730f1b70d1f9665259c63e890ad63a4f401bb506 docs/optimizations.md: the PR number of entry 19, changed files: 0 +llama.cpp: version: 1.0.0-dev (build 12359, commit b1b770d90) built with AppleClang 21.0.0.21000334 for Darwin arm64 +llama.cpp source: b1b770d90d94cad9e9ea5b993bdbc383a522fb28, changes: 1 file changed, 3 insertions(+) +GGUF: /Users/adityak/models/gguf/qwen36/Qwen3.6-35B-A3B-Q4_0.gguf 19715053888 bytes +MTP GGUF: /Users/adityak/models/gguf/qwen36-draft/mtp-Qwen3.6-35B-A3B-Q4_0.gguf 1060038720 bytes +app weights: /Users/adityak/models/Qwen3.6-35B-A3B-q4-q6-mtp.vxw 20868300800 bytes +app tokenizer: /Users/adityak/models/Qwen3.6-35B-A3B.vxt 6853664 bytes +rounds: 3, cool: 30 s, prompt runs: 3 +contexts: 64 512 2048 8192 16384 32768, prompt contexts: 512 2048 8192, generated tokens: 256 and 512 +prompts: edit1 complete1 write1 explain1 edit2 complete2 write2 explain2 edit3 complete3 write3 explain3 +table C: vx vxdraft vxmtp vxmtpdraft completion ngram mtp; app --draft 11, app --mtp 3,5, llama.cpp draft-mtp 3 +flash attention: on 26.31 ms, off 27.88 ms (medians at 2,048 tokens); chosen: on +draft lengths given: DRAFT=11 MTP_N=3 +date: Wed Nov 25 22:40:49 PST 2026, stages: C +machine: Mac16,12, Apple M4, 32 GB + Chipset Model: Apple M4 + Total Number of Cores: 10 + Metal Support: Metal 4 +macOS: 27.0.1 (26A434) +power: Now drawing from 'AC Power' +vxc: vxc 0.0.5 (5b92da4f) +qwen-vx: 730f1b70d1f9665259c63e890ad63a4f401bb506 docs/optimizations.md: the PR number of entry 19, changed files: 0 +llama.cpp: version: 1.0.0-dev (build 12359, commit b1b770d90) built with AppleClang 21.0.0.21000334 for Darwin arm64 +llama.cpp source: b1b770d90d94cad9e9ea5b993bdbc383a522fb28, changes: 1 file changed, 3 insertions(+) +GGUF: /Users/adityak/models/gguf/qwen36/Qwen3.6-35B-A3B-Q4_0.gguf 19715053888 bytes +MTP GGUF: /Users/adityak/models/gguf/qwen36-draft/mtp-Qwen3.6-35B-A3B-Q4_0.gguf 1060038720 bytes +app weights: /Users/adityak/models/Qwen3.6-35B-A3B-q4-q6-mtp.vxw 20868300800 bytes +app tokenizer: /Users/adityak/models/Qwen3.6-35B-A3B.vxt 6853664 bytes +rounds: 3, cool: 30 s, prompt runs: 3 +contexts: 64 512 2048 8192 16384 32768, prompt contexts: 512 2048 8192, generated tokens: 256 and 512 +prompts: edit1 complete1 write1 explain1 edit2 complete2 write2 explain2 edit3 complete3 write3 explain3 +table C: vx vxdraft vxmtp vxmtpdraft completion ngram mtp; app --draft 11, app --mtp 3,5, llama.cpp draft-mtp 3 +rerun: C.edit3.r2.mtp3 C.edit3.r2.ngram C.edit3.r2.completion C.complete3.r2.vxdraft11 C.write3.r3.vxdraft11 C.write3.r3.vxmtp C.write3.r3.vxmtpdraft11 C.write3.r3.completion +flash attention: given by FA; chosen: on +draft lengths given: DRAFT=11 MTP_N=3 diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/llama-timing.patch b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/llama-timing.patch new file mode 100644 index 0000000..30232c6 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/llama-timing.patch @@ -0,0 +1,14 @@ +diff --git a/examples/speculative-simple/speculative-simple.cpp b/examples/speculative-simple/speculative-simple.cpp +index e4a878b..4ddd972 100644 +--- a/examples/speculative-simple/speculative-simple.cpp ++++ b/examples/speculative-simple/speculative-simple.cpp +@@ -155,6 +155,9 @@ int main(int argc, char ** argv) { + + common_prompt_checkpoint ckpt; + ++ // Wait for the GPU, so that the time of the prompt is not counted in the time of the first tokens. ++ llama_synchronize(ctx_tgt); ++ + const auto t_enc_end = ggml_time_us(); + + const auto t_dec_start = ggml_time_us(); diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/llama.cpp-build.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/llama.cpp-build.txt new file mode 100644 index 0000000..cc9dcf2 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/llama.cpp-build.txt @@ -0,0 +1,13 @@ +The build of llama.cpp that ran, from build/CMakeCache.txt (b1b770d with llama-timing.patch): +CMAKE_BUILD_TYPE:STRING=Release +CMAKE_CXX_COMPILER:FILEPATH=/usr/bin/c++ +CMAKE_C_COMPILER:FILEPATH=/usr/bin/cc +GGML_METAL:BOOL=ON +GGML_METAL_EMBED_LIBRARY:BOOL=ON +GGML_NATIVE:BOOL=ON +LLAMA_BUILD_MTMD:BOOL=OFF +LLAMA_BUILD_TESTS:BOOL=OFF +LLAMA_BUILD_UI:BOOL=OFF +LLAMA_CURL:UNINITIALIZED=OFF + +Build times of the binaries (2026-11-25): llama-bench 02:10, llama-completion 02:10, llama-speculative-simple 02:10. The patch was applied before the build. diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/llama.cpp.diff b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/llama.cpp.diff new file mode 100644 index 0000000..396c9d8 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/llama.cpp.diff @@ -0,0 +1,14 @@ +diff --git a/examples/speculative-simple/speculative-simple.cpp b/examples/speculative-simple/speculative-simple.cpp +index e4a878b82..4ddd9725b 100644 +--- a/examples/speculative-simple/speculative-simple.cpp ++++ b/examples/speculative-simple/speculative-simple.cpp +@@ -155,6 +155,9 @@ int main(int argc, char ** argv) { + + common_prompt_checkpoint ckpt; + ++ // Wait for the GPU, so that the time of the prompt is not counted in the time of the first tokens. ++ llama_synchronize(ctx_tgt); ++ + const auto t_enc_end = ggml_time_us(); + + const auto t_dec_start = ggml_time_us(); diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/log.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/log.txt new file mode 100644 index 0000000..92daf4b --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/log.txt @@ -0,0 +1,328 @@ +fa-on.ctx2048.r1 start=2026-11-25T09:53:45 end=2026-11-25T09:54:08 rc=0 busy=[mediaanalysisd] gpu=0% +fa-off.ctx2048.r1 start=2026-11-25T09:54:48 end=2026-11-25T09:55:01 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +fa-off.ctx2048.r2 start=2026-11-25T09:55:41 end=2026-11-25T09:55:55 rc=0 busy=[cfprefsd] gpu=0% +fa-on.ctx2048.r2 start=2026-11-25T09:56:35 end=2026-11-25T09:56:48 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +fa-on.ctx2048.r3 start=2026-11-25T09:57:28 end=2026-11-25T09:57:41 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +fa-off.ctx2048.r3 start=2026-11-25T09:58:21 end=2026-11-25T09:58:35 rc=0 busy=[launchd] gpu=0% +flash attention: on 26.31 ms, off 27.88 ms (medians at 2,048 tokens); chosen: on +llama-bench-pp start=2026-11-25T09:59:15 end=2026-11-25T10:02:19 rc=0 busy=[bash] gpu=0% +llama-bench-tg start=2026-11-25T10:02:59 end=2026-11-25T10:09:03 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +A.vx.ctx64.r1 start=2026-11-25T10:09:43 end=2026-11-25T10:11:52 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +A.llama.ctx64.r1 start=2026-11-25T10:12:32 end=2026-11-25T10:12:49 rc=0 busy=[AXVisualSupportAgent] gpu=0% +A.vx.ctx512.r1 start=2026-11-25T10:13:29 end=2026-11-25T10:15:30 rc=0 busy=[mediaanalysisd] gpu=0% +A.llama.ctx512.r1 start=2026-11-25T10:16:10 end=2026-11-25T10:16:27 rc=0 busy=[contextstored] gpu=0% +A.vx.ctx2048.r1 start=2026-11-25T10:17:08 end=2026-11-25T10:19:12 rc=0 busy=[ZoomUpdater] gpu=0% +A.llama.ctx2048.r1 start=2026-11-25T10:19:53 end=2026-11-25T10:20:14 rc=0 busy=[bash] gpu=0% +A.vx.ctx8192.r1 start=2026-11-25T10:20:54 end=2026-11-25T10:23:12 rc=0 busy=[trustd] gpu=0% +A.llama.ctx8192.r1 start=2026-11-25T10:23:52 end=2026-11-25T10:24:32 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +A.vx.ctx16384.r1 start=2026-11-25T10:25:12 end=2026-11-25T10:27:58 rc=0 busy=[bash] gpu=0% +A.llama.ctx16384.r1 start=2026-11-25T10:28:38 end=2026-11-25T10:29:51 rc=0 busy=[bash] gpu=0% +A.vx.ctx32768.r1 start=2026-11-25T10:30:41 end=2026-11-25T10:35:09 rc=0 busy=[cfprefsd] gpu=0% +A.llama.ctx32768.r1 start=2026-11-25T10:35:59 end=2026-11-25T10:39:05 rc=0 busy=[bash] gpu=0% +A.llama.ctx64.r2 start=2026-11-25T10:39:45 end=2026-11-25T10:39:53 rc=0 busy=[airportd] gpu=0% +A.vx.ctx64.r2 start=2026-11-25T10:40:33 end=2026-11-25T10:42:32 rc=0 busy=[bash] gpu=0% +A.llama.ctx512.r2 start=2026-11-25T10:43:12 end=2026-11-25T10:43:30 rc=0 busy=[airportd] gpu=0% +A.vx.ctx512.r2 start=2026-11-25T10:44:10 end=2026-11-25T10:46:10 rc=0 busy=[bash] gpu=0% +A.llama.ctx2048.r2 start=2026-11-25T10:46:50 end=2026-11-25T10:47:11 rc=0 busy=[3.7 agy] gpu=0% +A.vx.ctx2048.r2 start=2026-11-25T10:47:52 end=2026-11-25T10:50:04 rc=0 busy=[launchd] gpu=0% +A.llama.ctx8192.r2 start=2026-11-25T10:50:44 end=2026-11-25T10:51:24 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +A.vx.ctx8192.r2 start=2026-11-25T10:52:04 end=2026-11-25T10:54:31 rc=0 busy=[WindowServer] gpu=0% +A.llama.ctx16384.r2 start=2026-11-25T10:55:11 end=2026-11-25T10:56:23 rc=0 busy=[bash] gpu=0% +A.vx.ctx16384.r2 start=2026-11-25T10:57:03 end=2026-11-25T10:59:49 rc=0 busy=[bash] gpu=0% +A.llama.ctx32768.r2 start=2026-11-25T11:00:30 end=2026-11-25T11:03:38 rc=0 busy=[networkserviceproxy] gpu=0% +A.vx.ctx32768.r2 start=2026-11-25T11:04:19 end=2026-11-25T11:08:53 rc=0 busy=[bash] gpu=0% +A.vx.ctx64.r3 start=2026-11-25T11:09:33 end=2026-11-25T11:11:32 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +A.llama.ctx64.r3 start=2026-11-25T11:12:12 end=2026-11-25T11:12:29 rc=0 busy=[xprotectd] gpu=0% +A.vx.ctx512.r3 start=2026-11-25T11:13:09 end=2026-11-25T11:15:06 rc=0 busy=[UserEventAgent] gpu=0% +A.llama.ctx512.r3 start=2026-11-25T11:15:46 end=2026-11-25T11:16:04 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +A.vx.ctx2048.r3 start=2026-11-25T11:16:44 end=2026-11-25T11:18:37 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +A.llama.ctx2048.r3 start=2026-11-25T11:19:17 end=2026-11-25T11:19:38 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +A.vx.ctx8192.r3 start=2026-11-25T11:20:19 end=2026-11-25T11:22:47 rc=0 busy=[bash] gpu=0% +A.llama.ctx8192.r3 start=2026-11-25T11:23:27 end=2026-11-25T11:24:07 rc=0 busy=[distnoted] gpu=0% +A.vx.ctx16384.r3 start=2026-11-25T11:24:47 end=2026-11-25T11:27:41 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +A.llama.ctx16384.r3 start=2026-11-25T11:28:22 end=2026-11-25T11:29:34 rc=0 busy=[launchd] gpu=0% +A.vx.ctx32768.r3 start=2026-11-25T11:30:14 end=2026-11-25T11:34:52 rc=0 busy=[xprotectd] gpu=0% +A.llama.ctx32768.r3 start=2026-11-25T11:35:32 end=2026-11-25T11:38:29 rc=0 busy=[0.9 agy] gpu=0% +P.vx.ctx512.r1 start=2026-11-25T11:39:09 end=2026-11-25T11:41:09 rc=0 busy=[airportd] gpu=0% +P.llama.ctx512.r1 start=2026-11-25T11:41:49 end=2026-11-25T11:42:00 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +P.vx.ctx2048.r1 start=2026-11-25T11:42:40 end=2026-11-25T11:44:45 rc=0 busy=[AXVisualSupportAgent] gpu=0% +P.llama.ctx2048.r1 start=2026-11-25T11:45:25 end=2026-11-25T11:45:40 rc=0 busy=[WindowServer] gpu=0% +P.vx.ctx8192.r1 start=2026-11-25T11:46:31 end=2026-11-25T11:49:22 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +P.llama.ctx8192.r1 start=2026-11-25T11:50:02 end=2026-11-25T11:50:35 rc=0 busy=[bash] gpu=0% +P.llama.ctx512.r2 start=2026-11-25T11:51:25 end=2026-11-25T11:51:28 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +P.vx.ctx512.r2 start=2026-11-25T11:52:18 end=2026-11-25T11:54:14 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +P.llama.ctx2048.r2 start=2026-11-25T11:54:54 end=2026-11-25T11:55:09 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +P.vx.ctx2048.r2 start=2026-11-25T11:55:49 end=2026-11-25T11:58:05 rc=0 busy=[bash] gpu=0% +P.llama.ctx8192.r2 start=2026-11-25T11:58:45 end=2026-11-25T11:59:17 rc=0 busy=[PerfPowerServices] gpu=0% +P.vx.ctx8192.r2 start=2026-11-25T11:59:57 end=2026-11-25T12:03:00 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +P.vx.ctx512.r3 start=2026-11-25T12:03:40 end=2026-11-25T12:05:38 rc=0 busy=[bash] gpu=0% +P.llama.ctx512.r3 start=2026-11-25T12:06:18 end=2026-11-25T12:06:29 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +P.vx.ctx2048.r3 start=2026-11-25T12:07:39 end=2026-11-25T12:09:45 rc=0 busy=[airportd] gpu=0% +P.llama.ctx2048.r3 start=2026-11-25T12:10:25 end=2026-11-25T12:10:40 rc=0 busy=[bash] gpu=0% +P.vx.ctx8192.r3 start=2026-11-25T12:11:20 end=2026-11-25T12:14:12 rc=0 busy=[airportd] gpu=0% +P.llama.ctx8192.r3 start=2026-11-25T12:14:53 end=2026-11-25T12:15:25 rc=0 busy=[configd] gpu=0% +draft lengths given: DRAFT=11 MTP_N=3 +C.edit1.r1.vx start=2026-11-25T12:16:06 end=2026-11-25T12:18:14 rc=0 busy=[bash] gpu=0% +C.edit1.r1.vxdraft11 start=2026-11-25T12:18:54 end=2026-11-25T12:20:59 rc=0 busy=[xprotectd] gpu=0% +C.edit1.r1.vxmtp start=2026-11-25T12:21:39 end=2026-11-25T12:23:42 rc=0 busy=[bash] gpu=0% +C.edit1.r1.vxmtpdraft11 start=2026-11-25T12:24:22 end=2026-11-25T12:26:25 rc=0 busy=[launchd] gpu=0% +C.edit1.r1.completion start=2026-11-25T12:27:05 end=2026-11-25T12:27:33 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +C.edit1.r1.ngram start=2026-11-25T12:28:43 end=2026-11-25T12:28:59 rc=0 busy=[bash] gpu=0% +C.edit1.r1.mtp3 start=2026-11-25T12:29:39 end=2026-11-25T12:29:53 rc=0 busy=[airportd] gpu=0% +C.complete1.r1.vx start=2026-11-25T12:30:44 end=2026-11-25T12:32:51 rc=0 busy=[airportd] gpu=0% +C.complete1.r1.vxdraft11 start=2026-11-25T12:33:31 end=2026-11-25T12:35:39 rc=0 busy=[0.3 agy] gpu=0% +C.complete1.r1.vxmtp start=2026-11-25T12:36:19 end=2026-11-25T12:38:22 rc=0 busy=[0.4 agy] gpu=0% +C.complete1.r1.vxmtpdraft11 start=2026-11-25T12:39:02 end=2026-11-25T12:41:10 rc=0 busy=[loginwindow] gpu=0% +C.complete1.r1.completion start=2026-11-25T12:41:50 end=2026-11-25T12:42:16 rc=0 busy=[2.1 agy] gpu=0% +C.complete1.r1.ngram start=2026-11-25T12:42:56 end=2026-11-25T12:43:13 rc=0 busy=[xprotectd] gpu=0% +C.complete1.r1.mtp3 start=2026-11-25T12:43:54 end=2026-11-25T12:44:08 rc=0 busy=[bash] gpu=0% +C.write1.r1.vx start=2026-11-25T12:44:48 end=2026-11-25T12:46:53 rc=0 busy=[1.7 agy] gpu=0% +C.write1.r1.vxdraft11 start=2026-11-25T12:47:34 end=2026-11-25T12:49:38 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.write1.r1.vxmtp start=2026-11-25T12:50:18 end=2026-11-25T12:52:18 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.write1.r1.vxmtpdraft11 start=2026-11-25T12:52:58 end=2026-11-25T12:55:00 rc=0 busy=[bash] gpu=0% +C.write1.r1.completion start=2026-11-25T12:55:40 end=2026-11-25T12:56:04 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.write1.r1.ngram start=2026-11-25T12:56:44 end=2026-11-25T12:56:58 rc=0 busy=[bash] gpu=0% +C.write1.r1.mtp3 start=2026-11-25T12:57:39 end=2026-11-25T12:57:49 rc=0 busy=[airportd] gpu=0% +C.explain1.r1.vx start=2026-11-25T12:58:30 end=2026-11-25T13:00:37 rc=0 busy=[bash] gpu=0% +C.explain1.r1.vxdraft11 start=2026-11-25T13:01:17 end=2026-11-25T13:03:24 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.explain1.r1.vxmtp start=2026-11-25T13:04:04 end=2026-11-25T13:06:09 rc=0 busy=[secd] gpu=0% +C.explain1.r1.vxmtpdraft11 start=2026-11-25T13:06:50 end=2026-11-25T13:09:03 rc=0 busy=[airportd] gpu=0% +C.explain1.r1.completion start=2026-11-25T13:09:43 end=2026-11-25T13:10:10 rc=0 busy=[xprotectd] gpu=0% +C.explain1.r1.ngram start=2026-11-25T13:10:50 end=2026-11-25T13:11:09 rc=0 busy=[bash] gpu=0% +C.explain1.r1.mtp3 start=2026-11-25T13:11:49 end=2026-11-25T13:12:05 rc=0 busy=[cfprefsd] gpu=0% +C.edit2.r1.vx start=2026-11-25T13:12:45 end=2026-11-25T13:14:54 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.edit2.r1.vxdraft11 start=2026-11-25T13:15:34 end=2026-11-25T13:17:35 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.edit2.r1.vxmtp start=2026-11-25T13:18:15 end=2026-11-25T13:20:16 rc=0 busy=[bash] gpu=0% +C.edit2.r1.vxmtpdraft11 start=2026-11-25T13:20:56 end=2026-11-25T13:23:07 rc=0 busy=[bash] gpu=0% +C.edit2.r1.completion start=2026-11-25T13:23:47 end=2026-11-25T13:24:14 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.edit2.r1.ngram start=2026-11-25T13:24:54 end=2026-11-25T13:25:03 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +C.edit2.r1.mtp3 start=2026-11-25T13:25:43 end=2026-11-25T13:25:56 rc=0 busy=[dasd] gpu=0% +C.complete2.r1.vx start=2026-11-25T13:26:36 end=2026-11-25T13:28:54 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.complete2.r1.vxdraft11 start=2026-11-25T13:30:55 end=2026-11-25T13:32:59 rc=0 busy=[1.3 agy] gpu=0% +C.complete2.r1.vxmtp start=2026-11-25T13:33:39 end=2026-11-25T13:35:53 rc=0 busy=[bash] gpu=0% +C.complete2.r1.vxmtpdraft11 start=2026-11-25T13:36:33 end=2026-11-25T13:38:46 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.complete2.r1.completion start=2026-11-25T13:39:26 end=2026-11-25T13:39:52 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.complete2.r1.ngram start=2026-11-25T13:40:32 end=2026-11-25T13:40:50 rc=0 busy=[airportd] gpu=0% +C.complete2.r1.mtp3 start=2026-11-25T13:41:30 end=2026-11-25T13:41:44 rc=0 busy=[xprotectd] gpu=0% +C.write2.r1.vx start=2026-11-25T13:42:24 end=2026-11-25T13:44:30 rc=0 busy=[mdworker_shared] gpu=0% +C.write2.r1.vxdraft11 start=2026-11-25T13:45:10 end=2026-11-25T13:47:32 rc=0 busy=[bash] gpu=0% +C.write2.r1.vxmtp start=2026-11-25T13:48:12 end=2026-11-25T13:50:22 rc=0 busy=[WiFiAgent] gpu=0% +C.write2.r1.vxmtpdraft11 start=2026-11-25T13:51:02 end=2026-11-25T13:53:12 rc=0 busy=[loginwindow] gpu=0% +C.write2.r1.completion start=2026-11-25T13:53:53 end=2026-11-25T13:54:16 rc=0 busy=[clocksyncd] gpu=0% +C.write2.r1.ngram start=2026-11-25T13:54:56 end=2026-11-25T13:55:11 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.write2.r1.mtp3 start=2026-11-25T13:55:51 end=2026-11-25T13:56:02 rc=0 busy=[launchd] gpu=0% +C.explain2.r1.vx start=2026-11-25T13:56:42 end=2026-11-25T13:58:48 rc=0 busy=[bash] gpu=0% +C.explain2.r1.vxdraft11 start=2026-11-25T13:59:28 end=2026-11-25T14:01:35 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.explain2.r1.vxmtp start=2026-11-25T14:02:15 end=2026-11-25T14:04:28 rc=0 busy=[bash] gpu=0% +C.explain2.r1.vxmtpdraft11 start=2026-11-25T14:05:09 end=2026-11-25T14:07:21 rc=0 busy=[WindowServer] gpu=0% +C.explain2.r1.completion start=2026-11-25T14:08:01 end=2026-11-25T14:08:28 rc=0 busy=[loginwindow] gpu=0% +C.explain2.r1.ngram start=2026-11-25T14:09:08 end=2026-11-25T14:09:27 rc=0 busy=[identityservicesd] gpu=0% +C.explain2.r1.mtp3 start=2026-11-25T14:10:07 end=2026-11-25T14:10:22 rc=0 busy=[airportd] gpu=0% +C.edit3.r1.vx start=2026-11-25T14:11:02 end=2026-11-25T14:13:11 rc=0 busy=[loginwindow] gpu=0% +C.edit3.r1.vxdraft11 start=2026-11-25T14:13:51 end=2026-11-25T14:15:53 rc=0 busy=[launchd] gpu=0% +C.edit3.r1.vxmtp start=2026-11-25T14:16:33 end=2026-11-25T14:18:34 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.edit3.r1.vxmtpdraft11 start=2026-11-25T14:19:14 end=2026-11-25T14:21:18 rc=0 busy=[0.7 sleep] gpu=0% +C.edit3.r1.completion start=2026-11-25T14:21:58 end=2026-11-25T14:22:26 rc=0 busy=[secd] gpu=0% +C.edit3.r1.ngram start=2026-11-25T14:23:06 end=2026-11-25T14:23:16 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.edit3.r1.mtp3 start=2026-11-25T14:23:57 end=2026-11-25T14:24:11 rc=0 busy=[bash] gpu=0% +C.complete3.r1.vx start=2026-11-25T14:25:01 end=2026-11-25T14:27:10 rc=0 busy=[loginwindow] gpu=0% +C.complete3.r1.vxdraft11 start=2026-11-25T14:27:50 end=2026-11-25T14:29:55 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +C.complete3.r1.vxmtp start=2026-11-25T14:30:35 end=2026-11-25T14:32:38 rc=0 busy=[PerfPowerServices] gpu=0% +C.complete3.r1.vxmtpdraft11 start=2026-11-25T14:33:18 end=2026-11-25T14:35:30 rc=0 busy=[bash] gpu=0% +C.complete3.r1.completion start=2026-11-25T14:36:10 end=2026-11-25T14:36:36 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +C.complete3.r1.ngram start=2026-11-25T14:37:16 end=2026-11-25T14:37:36 rc=0 busy=[bash] gpu=0% +C.complete3.r1.mtp3 start=2026-11-25T14:38:17 end=2026-11-25T14:38:30 rc=0 busy=[secd] gpu=0% +C.write3.r1.vx start=2026-11-25T14:39:11 end=2026-11-25T14:41:25 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.write3.r1.vxdraft11 start=2026-11-25T14:42:05 end=2026-11-25T14:44:28 rc=0 busy=[bash] gpu=0% +C.write3.r1.vxmtp start=2026-11-25T14:45:09 end=2026-11-25T14:47:09 rc=0 busy=[UserEventAgent] gpu=0% +C.write3.r1.vxmtpdraft11 start=2026-11-25T14:47:49 end=2026-11-25T14:49:48 rc=0 busy=[xprotectd] gpu=0% +C.write3.r1.completion start=2026-11-25T14:50:29 end=2026-11-25T14:50:52 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.write3.r1.ngram start=2026-11-25T14:51:32 end=2026-11-25T14:51:47 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +C.write3.r1.mtp3 start=2026-11-25T14:52:27 end=2026-11-25T14:52:37 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +C.explain3.r1.vx start=2026-11-25T14:53:17 end=2026-11-25T14:55:33 rc=0 busy=[airportd] gpu=0% +C.explain3.r1.vxdraft11 start=2026-11-25T14:56:13 end=2026-11-25T14:58:20 rc=0 busy=[WindowServer] gpu=0% +C.explain3.r1.vxmtp start=2026-11-25T14:59:00 end=2026-11-25T15:01:04 rc=0 busy=[loginwindow] gpu=0% +C.explain3.r1.vxmtpdraft11 start=2026-11-25T15:01:44 end=2026-11-25T15:03:50 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.explain3.r1.completion start=2026-11-25T15:04:30 end=2026-11-25T15:04:57 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.explain3.r1.ngram start=2026-11-25T15:05:47 end=2026-11-25T15:06:05 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.explain3.r1.mtp3 start=2026-11-25T15:06:45 end=2026-11-25T15:07:01 rc=0 busy=[airportd] gpu=0% +C.edit1.r2.mtp3 start=2026-11-25T15:07:41 end=2026-11-25T15:07:55 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +C.edit1.r2.ngram start=2026-11-25T15:08:35 end=2026-11-25T15:08:51 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.edit1.r2.completion start=2026-11-25T15:09:31 end=2026-11-25T15:09:50 rc=0 busy=[bash] gpu=0% +C.edit1.r2.vxmtpdraft11 start=2026-11-25T15:10:30 end=2026-11-25T15:12:32 rc=0 busy=[bash] gpu=0% +C.edit1.r2.vxmtp start=2026-11-25T15:13:12 end=2026-11-25T15:15:26 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +C.edit1.r2.vxdraft11 start=2026-11-25T15:16:56 end=2026-11-25T15:19:00 rc=0 busy=[3.7 agy] gpu=0% +C.edit1.r2.vx start=2026-11-25T15:19:40 end=2026-11-25T15:21:48 rc=0 busy=[PerfPowerServices] gpu=0% +C.complete1.r2.mtp3 start=2026-11-25T15:22:28 end=2026-11-25T15:22:50 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.complete1.r2.ngram start=2026-11-25T15:23:30 end=2026-11-25T15:23:48 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.complete1.r2.completion start=2026-11-25T15:24:28 end=2026-11-25T15:24:45 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.complete1.r2.vxmtpdraft11 start=2026-11-25T15:25:25 end=2026-11-25T15:27:29 rc=0 busy=[xprotectd] gpu=0% +C.complete1.r2.vxmtp start=2026-11-25T15:28:09 end=2026-11-25T15:30:09 rc=0 busy=[UserEventAgent] gpu=0% +C.complete1.r2.vxdraft11 start=2026-11-25T15:30:49 end=2026-11-25T15:32:56 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.complete1.r2.vx start=2026-11-25T15:33:36 end=2026-11-25T15:35:30 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.write1.r2.mtp3 start=2026-11-25T15:36:11 end=2026-11-25T15:36:30 rc=0 busy=[PerfPowerServices] gpu=0% +C.write1.r2.ngram start=2026-11-25T15:37:10 end=2026-11-25T15:37:25 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.write1.r2.completion start=2026-11-25T15:38:05 end=2026-11-25T15:38:19 rc=0 busy=[bash] gpu=0% +C.write1.r2.vxmtpdraft11 start=2026-11-25T15:39:00 end=2026-11-25T15:41:11 rc=0 busy=[airportd] gpu=0% +C.write1.r2.vxmtp start=2026-11-25T15:41:51 end=2026-11-25T15:43:51 rc=0 busy=[launchd] gpu=0% +C.write1.r2.vxdraft11 start=2026-11-25T15:44:31 end=2026-11-25T15:46:47 rc=0 busy=[secd] gpu=0% +C.write1.r2.vx start=2026-11-25T15:47:28 end=2026-11-25T15:49:31 rc=0 busy=[secd] gpu=0% +C.explain1.r2.mtp3 start=2026-11-25T15:50:22 end=2026-11-25T15:50:47 rc=0 busy=[launchd] gpu=0% +C.explain1.r2.ngram start=2026-11-25T16:01:20 end=2026-11-25T16:01:38 rc=0 busy=[xprotectd] gpu=0% +C.explain1.r2.completion start=2026-11-25T16:02:19 end=2026-11-25T16:02:37 rc=0 busy=[bash] gpu=0% +C.explain1.r2.vxmtpdraft11 start=2026-11-25T16:03:17 end=2026-11-25T16:05:34 rc=0 busy=[WindowServer] gpu=0% +C.explain1.r2.vxmtp start=2026-11-25T16:06:14 end=2026-11-25T16:08:19 rc=0 busy=[bash] gpu=0% +C.explain1.r2.vxdraft11 start=2026-11-25T16:08:59 end=2026-11-25T16:11:18 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.explain1.r2.vx start=2026-11-25T16:11:58 end=2026-11-25T16:14:04 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.edit2.r2.mtp3 start=2026-11-25T16:14:44 end=2026-11-25T16:15:06 rc=0 busy=[xprotectd] gpu=0% +C.edit2.r2.ngram start=2026-11-25T16:15:46 end=2026-11-25T16:15:55 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.edit2.r2.completion start=2026-11-25T16:16:35 end=2026-11-25T16:16:53 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.edit2.r2.vxmtpdraft11 start=2026-11-25T16:17:33 end=2026-11-25T16:19:36 rc=0 busy=[xprotectd] gpu=0% +C.edit2.r2.vxmtp start=2026-11-25T16:20:16 end=2026-11-25T16:22:16 rc=0 busy=[ZoomUpdater] gpu=0% +C.edit2.r2.vxdraft11 start=2026-11-25T16:22:56 end=2026-11-25T16:24:57 rc=0 busy=[bash] gpu=0% +C.edit2.r2.vx start=2026-11-25T16:25:37 end=2026-11-25T16:27:42 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.complete2.r2.mtp3 start=2026-11-25T16:28:22 end=2026-11-25T16:28:45 rc=0 busy=[bash] gpu=0% +C.complete2.r2.ngram start=2026-11-25T16:29:25 end=2026-11-25T16:29:42 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.complete2.r2.completion start=2026-11-25T16:30:23 end=2026-11-25T16:30:40 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +C.complete2.r2.vxmtpdraft11 start=2026-11-25T16:31:20 end=2026-11-25T16:33:25 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.complete2.r2.vxmtp start=2026-11-25T16:34:05 end=2026-11-25T16:36:07 rc=0 busy=[AXVisualSupportAgent] gpu=0% +C.complete2.r2.vxdraft11 start=2026-11-25T16:36:47 end=2026-11-25T16:38:54 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.complete2.r2.vx start=2026-11-25T16:39:44 end=2026-11-25T16:42:00 rc=0 busy=[bash] gpu=0% +C.write2.r2.mtp3 start=2026-11-25T16:42:40 end=2026-11-25T16:43:00 rc=0 busy=[mdworker_shared] gpu=0% +C.write2.r2.ngram start=2026-11-25T16:43:40 end=2026-11-25T16:43:55 rc=0 busy=[secd] gpu=0% +C.write2.r2.completion start=2026-11-25T16:44:35 end=2026-11-25T16:44:50 rc=0 busy=[airportd] gpu=0% +C.write2.r2.vxmtpdraft11 start=2026-11-25T16:45:30 end=2026-11-25T16:47:30 rc=0 busy=[cfprefsd] gpu=0% +C.write2.r2.vxmtp start=2026-11-25T16:48:10 end=2026-11-25T16:50:09 rc=0 busy=[bash] gpu=0% +C.write2.r2.vxdraft11 start=2026-11-25T16:51:29 end=2026-11-25T16:53:31 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +C.write2.r2.vx start=2026-11-25T16:54:12 end=2026-11-25T16:56:16 rc=0 busy=[bash] gpu=0% +C.explain2.r2.mtp3 start=2026-11-25T16:56:56 end=2026-11-25T16:57:20 rc=0 busy=[bash] gpu=0% +C.explain2.r2.ngram start=2026-11-25T16:58:00 end=2026-11-25T16:58:19 rc=0 busy=[loginwindow] gpu=0% +C.explain2.r2.completion start=2026-11-25T17:01:10 end=2026-11-25T17:01:27 rc=0 busy=[PerfPowerServices] gpu=0% +C.explain2.r2.vxmtpdraft11 start=2026-11-25T17:02:08 end=2026-11-25T17:04:12 rc=0 busy=[airportd] gpu=0% +C.explain2.r2.vxmtp start=2026-11-25T17:04:53 end=2026-11-25T17:07:07 rc=0 busy=[clocksyncd] gpu=0% +C.explain2.r2.vxdraft11 start=2026-11-25T17:07:47 end=2026-11-25T17:09:53 rc=0 busy=[bash] gpu=0% +C.explain2.r2.vx start=2026-11-25T17:10:33 end=2026-11-25T17:12:50 rc=0 busy=[airportd] gpu=0% +C.edit3.r2.mtp3 start=2026-11-25T17:14:10 end=2026-11-25T17:14:33 rc=0 busy=[cfprefsd] gpu=0% +C.edit3.r2.ngram start=2026-11-25T17:17:04 end=2026-11-25T17:17:14 rc=0 busy=[xprotectd] gpu=0% +C.edit3.r2.completion start=2026-11-25T17:21:25 end=2026-11-25T17:21:44 rc=0 busy=[xprotectd] gpu=0% +C.edit3.r2.vxmtpdraft11 start=2026-11-25T17:36:59 end=2026-11-25T17:39:14 rc=0 busy=[15.1 agy] gpu=0% +C.edit3.r2.vxmtp start=2026-11-25T17:40:54 end=2026-11-25T17:43:05 rc=0 busy=[dasd] gpu=0% +C.edit3.r2.vxdraft11 start=2026-11-25T17:43:46 end=2026-11-25T17:46:00 rc=0 busy=[bash] gpu=0% +C.edit3.r2.vx start=2026-11-25T17:46:40 end=2026-11-25T17:48:59 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.complete3.r2.mtp3 start=2026-11-25T17:49:39 end=2026-11-25T17:50:02 rc=0 busy=[WindowServer] gpu=0% +C.complete3.r2.ngram start=2026-11-25T17:50:42 end=2026-11-25T17:51:02 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.complete3.r2.completion start=2026-11-25T17:51:42 end=2026-11-25T17:52:00 rc=0 busy=[bash] gpu=0% +C.complete3.r2.vxmtpdraft11 start=2026-11-25T17:52:40 end=2026-11-25T17:54:30 rc=0 busy=[WindowServer] gpu=0% +C.complete3.r2.vxmtp start=2026-11-25T17:55:11 end=2026-11-25T17:57:13 rc=0 busy=[WindowServer] gpu=0% +C.complete3.r2.vxdraft11 start=2026-11-25T17:57:54 end=2026-11-25T17:59:51 rc=0 busy=[WindowServer] gpu=0% +C.complete3.r2.vx start=2026-11-25T18:28:59 end=2026-11-25T18:31:08 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.write3.r2.mtp3 start=2026-11-25T18:31:48 end=2026-11-25T18:32:07 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.write3.r2.ngram start=2026-11-25T18:32:47 end=2026-11-25T18:33:02 rc=0 busy=[bash] gpu=0% +C.write3.r2.completion start=2026-11-25T18:33:42 end=2026-11-25T18:33:57 rc=0 busy=[airportd] gpu=0% +C.write3.r2.vxmtpdraft11 start=2026-11-25T18:34:37 end=2026-11-25T18:36:48 rc=0 busy=[bash] gpu=0% +C.write3.r2.vxmtp start=2026-11-25T18:37:28 end=2026-11-25T18:39:26 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.write3.r2.vxdraft11 start=2026-11-25T18:46:09 end=2026-11-25T18:48:12 rc=0 busy=[WindowServer] gpu=0% +C.write3.r2.vx start=2026-11-25T18:48:52 end=2026-11-25T18:51:06 rc=0 busy=[WindowServer] gpu=0% +C.explain3.r2.mtp3 start=2026-11-25T18:51:46 end=2026-11-25T18:52:11 rc=0 busy=[airportd] gpu=0% +C.explain3.r2.ngram start=2026-11-25T18:53:01 end=2026-11-25T18:53:19 rc=0 busy=[bash] gpu=0% +C.explain3.r2.completion start=2026-11-25T18:53:59 end=2026-11-25T18:54:17 rc=0 busy=[bash] gpu=0% +C.explain3.r2.vxmtpdraft11 start=2026-11-25T18:54:57 end=2026-11-25T18:57:10 rc=0 busy=[bash] gpu=0% +C.explain3.r2.vxmtp start=2026-11-25T18:58:01 end=2026-11-25T19:00:08 rc=0 busy=[WindowServer] gpu=0% +C.explain3.r2.vxdraft11 start=2026-11-25T19:00:48 end=2026-11-25T19:02:56 rc=0 busy=[PowerUIAgent] gpu=0% +C.explain3.r2.vx start=2026-11-25T19:03:36 end=2026-11-25T19:05:43 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.edit1.r3.vx start=2026-11-25T19:06:24 end=2026-11-25T19:08:41 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.edit1.r3.vxdraft11 start=2026-11-25T19:09:31 end=2026-11-25T19:11:32 rc=0 busy=[WindowServer] gpu=0% +C.edit1.r3.vxmtp start=2026-11-25T19:12:12 end=2026-11-25T19:14:16 rc=0 busy=[WindowServer] gpu=0% +C.edit1.r3.vxmtpdraft11 start=2026-11-25T19:14:56 end=2026-11-25T19:16:48 rc=0 busy=[WindowServer] gpu=0% +C.edit1.r3.completion start=2026-11-25T19:17:29 end=2026-11-25T19:17:56 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.edit1.r3.ngram start=2026-11-25T19:18:36 end=2026-11-25T19:18:52 rc=0 busy=[bash] gpu=0% +C.edit1.r3.mtp3 start=2026-11-25T19:19:32 end=2026-11-25T19:19:47 rc=0 busy=[bash] gpu=0% +C.complete1.r3.vx start=2026-11-25T19:20:27 end=2026-11-25T19:22:32 rc=0 busy=[secd] gpu=0% +C.complete1.r3.vxdraft11 start=2026-11-25T19:23:13 end=2026-11-25T19:25:19 rc=0 busy=[WindowServer] gpu=0% +C.complete1.r3.vxmtp start=2026-11-25T19:25:59 end=2026-11-25T19:28:02 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.complete1.r3.vxmtpdraft11 start=2026-11-25T19:28:42 end=2026-11-25T19:30:47 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.complete1.r3.completion start=2026-11-25T19:31:27 end=2026-11-25T19:31:53 rc=0 busy=[bash] gpu=0% +C.complete1.r3.ngram start=2026-11-25T19:32:33 end=2026-11-25T19:32:51 rc=0 busy=[bash] gpu=0% +C.complete1.r3.mtp3 start=2026-11-25T19:33:31 end=2026-11-25T19:33:45 rc=0 busy=[airportd] gpu=0% +C.write1.r3.vx start=2026-11-25T19:34:25 end=2026-11-25T19:36:38 rc=0 busy=[bash] gpu=0% +C.write1.r3.vxdraft11 start=2026-11-25T19:37:19 end=2026-11-25T19:39:35 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.write1.r3.vxmtp start=2026-11-25T19:40:15 end=2026-11-25T19:42:26 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.write1.r3.vxmtpdraft11 start=2026-11-25T19:43:06 end=2026-11-25T19:45:07 rc=0 busy=[WindowServer] gpu=0% +C.write1.r3.completion start=2026-11-25T19:45:48 end=2026-11-25T19:46:11 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.write1.r3.ngram start=2026-11-25T19:46:51 end=2026-11-25T19:47:06 rc=0 busy=[launchd] gpu=0% +C.write1.r3.mtp3 start=2026-11-25T19:47:46 end=2026-11-25T19:47:56 rc=0 busy=[cfprefsd] gpu=0% +C.explain1.r3.vx start=2026-11-25T19:48:37 end=2026-11-25T19:50:55 rc=0 busy=[networkserviceproxy] gpu=0% +C.explain1.r3.vxdraft11 start=2026-11-25T19:51:35 end=2026-11-25T19:53:43 rc=0 busy=[WindowServer] gpu=0% +C.explain1.r3.vxmtp start=2026-11-25T19:54:23 end=2026-11-25T19:56:28 rc=0 busy=[AXVisualSupportAgent] gpu=0% +C.explain1.r3.vxmtpdraft11 start=2026-11-25T19:57:08 end=2026-11-25T19:59:22 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.explain1.r3.completion start=2026-11-25T20:00:03 end=2026-11-25T20:00:30 rc=0 busy=[WindowServer] gpu=0% +C.explain1.r3.ngram start=2026-11-25T20:01:10 end=2026-11-25T20:01:28 rc=0 busy=[WindowServer] gpu=0% +C.explain1.r3.mtp3 start=2026-11-25T20:02:08 end=2026-11-25T20:02:24 rc=0 busy=[WindowServer] gpu=0% +C.edit2.r3.vx start=2026-11-25T20:03:05 end=2026-11-25T20:05:21 rc=0 busy=[WindowServer] gpu=0% +C.edit2.r3.vxdraft11 start=2026-11-25T20:06:02 end=2026-11-25T20:08:03 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +C.edit2.r3.vxmtp start=2026-11-25T20:08:53 end=2026-11-25T20:10:55 rc=0 busy=[mdworker_shared] gpu=0% +C.edit2.r3.vxmtpdraft11 start=2026-11-25T20:11:35 end=2026-11-25T20:13:36 rc=0 busy=[WindowServer] gpu=0% +C.edit2.r3.completion start=2026-11-25T20:14:17 end=2026-11-25T20:14:43 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.edit2.r3.ngram start=2026-11-25T20:15:23 end=2026-11-25T20:15:32 rc=0 busy=[bash] gpu=0% +C.edit2.r3.mtp3 start=2026-11-25T20:16:12 end=2026-11-25T20:16:25 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.complete2.r3.vx start=2026-11-25T20:17:05 end=2026-11-25T20:19:21 rc=0 busy=[airportd] gpu=0% +C.complete2.r3.vxdraft11 start=2026-11-25T20:20:01 end=2026-11-25T20:22:06 rc=0 busy=[bash] gpu=0% +C.complete2.r3.vxmtp start=2026-11-25T20:22:47 end=2026-11-25T20:24:49 rc=0 busy=[WindowServer] gpu=0% +C.complete2.r3.vxmtpdraft11 start=2026-11-25T20:25:29 end=2026-11-25T20:27:23 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.complete2.r3.completion start=2026-11-25T20:28:03 end=2026-11-25T20:28:29 rc=0 busy=[WindowServer] gpu=0% +C.complete2.r3.ngram start=2026-11-25T20:29:09 end=2026-11-25T20:29:27 rc=0 busy=[WindowServer] gpu=0% +C.complete2.r3.mtp3 start=2026-11-25T20:30:07 end=2026-11-25T20:30:21 rc=0 busy=[WindowServer] gpu=0% +C.write2.r3.vx start=2026-11-25T20:31:01 end=2026-11-25T20:33:06 rc=0 busy=[WindowServer] gpu=0% +C.write2.r3.vxdraft11 start=2026-11-25T20:33:46 end=2026-11-25T20:35:51 rc=0 busy=[bash] gpu=0% +C.write2.r3.vxmtp start=2026-11-25T20:37:31 end=2026-11-25T20:39:28 rc=0 busy=[bash] gpu=0% +C.write2.r3.vxmtpdraft11 start=2026-11-25T20:40:09 end=2026-11-25T20:42:08 rc=0 busy=[networkserviceproxy] gpu=0% +C.write2.r3.completion start=2026-11-25T20:42:48 end=2026-11-25T20:43:11 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +C.write2.r3.ngram start=2026-11-25T20:43:51 end=2026-11-25T20:44:06 rc=0 busy=[launchd] gpu=0% +C.write2.r3.mtp3 start=2026-11-25T20:44:46 end=2026-11-25T20:44:57 rc=0 busy=[WindowServer] gpu=3% +C.explain2.r3.vx start=2026-11-25T20:46:18 end=2026-11-25T20:48:24 rc=0 busy=[WindowServer] gpu=0% +C.explain2.r3.vxdraft11 start=2026-11-25T20:49:05 end=2026-11-25T20:51:12 rc=0 busy=[0.3 agy] gpu=0% +C.explain2.r3.vxmtp start=2026-11-25T20:51:52 end=2026-11-25T20:53:55 rc=0 busy=[WindowServer] gpu=0% +C.explain2.r3.vxmtpdraft11 start=2026-11-25T20:55:06 end=2026-11-25T20:57:12 rc=0 busy=[WindowServer] gpu=0% +C.explain2.r3.completion start=2026-11-25T20:57:52 end=2026-11-25T20:58:19 rc=0 busy=[biomesyncd] gpu=0% +C.explain2.r3.ngram start=2026-11-25T20:58:59 end=2026-11-25T20:59:18 rc=0 busy=[dasd] gpu=0% +C.explain2.r3.mtp3 start=2026-11-25T20:59:58 end=2026-11-25T21:00:13 rc=0 busy=[bash] gpu=0% +C.edit3.r3.vx start=2026-11-25T21:00:53 end=2026-11-25T21:02:59 rc=0 busy=[dasd] gpu=0% +C.edit3.r3.vxdraft11 start=2026-11-25T21:03:39 end=2026-11-25T21:05:51 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.edit3.r3.vxmtp start=2026-11-25T21:06:41 end=2026-11-25T21:08:46 rc=0 busy=[PerfPowerServices] gpu=0% +C.edit3.r3.vxmtpdraft11 start=2026-11-25T21:09:26 end=2026-11-25T21:11:29 rc=0 busy=[bash] gpu=0% +C.edit3.r3.completion start=2026-11-25T21:12:10 end=2026-11-25T21:12:37 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +C.edit3.r3.ngram start=2026-11-25T21:13:17 end=2026-11-25T21:13:28 rc=0 busy=[bash] gpu=0% +C.edit3.r3.mtp3 start=2026-11-25T21:14:08 end=2026-11-25T21:14:23 rc=0 busy=[WindowServer] gpu=0% +C.complete3.r3.vx start=2026-11-25T21:15:03 end=2026-11-25T21:17:21 rc=0 busy=[WindowServer] gpu=0% +C.complete3.r3.vxdraft11 start=2026-11-25T21:18:01 end=2026-11-25T21:20:06 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.complete3.r3.vxmtp start=2026-11-25T21:20:46 end=2026-11-25T21:22:49 rc=0 busy=[WindowServer] gpu=0% +C.complete3.r3.vxmtpdraft11 start=2026-11-25T21:23:29 end=2026-11-25T21:25:44 rc=0 busy=[WindowServer] gpu=0% +C.complete3.r3.completion start=2026-11-25T21:26:24 end=2026-11-25T21:26:51 rc=0 busy=[WindowServer] gpu=0% +C.complete3.r3.ngram start=2026-11-25T21:27:31 end=2026-11-25T21:27:51 rc=0 busy=[WindowServer] gpu=0% +C.complete3.r3.mtp3 start=2026-11-25T21:29:01 end=2026-11-25T21:29:15 rc=0 busy=[WindowServer] gpu=0% +C.write3.r3.vx start=2026-11-25T21:29:55 end=2026-11-25T21:32:04 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.write3.r3.vxdraft11 start=2026-11-25T21:32:44 end=2026-11-25T21:34:52 rc=0 busy=[WindowServer] gpu=0% +C.write3.r3.vxmtp start=2026-11-25T21:36:12 end=2026-11-25T21:38:15 rc=0 busy=[WindowServer] gpu=0% +C.write3.r3.vxmtpdraft11 start=2026-11-25T21:39:35 end=2026-11-25T21:41:29 rc=0 busy=[WindowServer] gpu=0% +C.write3.r3.completion start=2026-11-25T21:44:30 end=2026-11-25T21:44:54 rc=0 busy=[WindowServer] gpu=0% +C.write3.r3.ngram start=2026-11-25T22:18:54 end=2026-11-25T22:19:16 rc=0 busy=[bash] gpu=0% +C.write3.r3.mtp3 start=2026-11-25T22:19:56 end=2026-11-25T22:20:06 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.explain3.r3.vx start=2026-11-25T22:20:46 end=2026-11-25T22:22:51 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.explain3.r3.vxdraft11 start=2026-11-25T22:23:32 end=2026-11-25T22:25:40 rc=0 busy=[bash] gpu=0% +C.explain3.r3.vxmtp start=2026-11-25T22:26:20 end=2026-11-25T22:28:15 rc=0 busy=[bash] gpu=0% +C.explain3.r3.vxmtpdraft11 start=2026-11-25T22:28:55 end=2026-11-25T22:31:09 rc=0 busy=[com.apple.DriverKit-AppleBCMWLAN] gpu=0% +C.explain3.r3.completion start=2026-11-25T22:31:49 end=2026-11-25T22:32:16 rc=0 busy=[airportd] gpu=0% +C.explain3.r3.ngram start=2026-11-25T22:32:56 end=2026-11-25T22:33:14 rc=0 busy=[bash] gpu=0% +C.explain3.r3.mtp3 start=2026-11-25T22:33:54 end=2026-11-25T22:34:10 rc=0 busy=[bash] gpu=0% +done 2026-11-25T22:34:10 +flash attention: given by FA; chosen: on +draft lengths given: DRAFT=11 MTP_N=3 +C.edit3.r2.mtp3 start=2026-11-25T22:41:20 end=2026-11-25T22:41:34 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.edit3.r2.ngram start=2026-11-25T22:42:14 end=2026-11-25T22:42:25 rc=0 busy=[bash] gpu=0% +C.edit3.r2.completion start=2026-11-25T22:43:05 end=2026-11-25T22:43:23 rc=0 busy=[mediaanalysisd] gpu=0% +C.complete3.r2.vxdraft11 start=2026-11-25T22:44:04 end=2026-11-25T22:46:20 rc=0 busy=[com.apple.AppleUserHIDDrivers] gpu=0% +C.write3.r3.vxdraft11 start=2026-11-25T22:47:00 end=2026-11-25T22:49:02 rc=0 busy=[loginwindow] gpu=0% +C.write3.r3.vxmtp start=2026-11-25T22:49:42 end=2026-11-25T22:51:52 rc=0 busy=[contextstored] gpu=0% +C.write3.r3.vxmtpdraft11 start=2026-11-25T22:52:32 end=2026-11-25T22:54:34 rc=0 busy=[bash] gpu=0% +C.write3.r3.completion start=2026-11-25T22:55:14 end=2026-11-25T22:55:37 rc=0 busy=[bash] gpu=0% +done 2026-11-25T22:55:37 diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/logs.tar.xz b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/logs.tar.xz new file mode 100644 index 0000000..46f26fa Binary files /dev/null and b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/logs.tar.xz differ diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/make_prompts.py b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/make_prompts.py new file mode 100755 index 0000000..4539cca --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/make_prompts.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +"""Write the prompts of this benchmark into prompts/ beside this script. + + python3 make_prompts.py MODEL_DIR VX_CHECKOUT + +MODEL_DIR is the Hugging Face folder of Qwen3.6-35B-A3B. VX_CHECKOUT is a clone of the Vx +repository. The script reads its files at two commits with `git show`, so the clone can be at any +commit. + +- context/ctxN.txt: the first N tokens of the sources of this app, at QWEN_VX_COMMIT. +- twelve/: the 12 prompts of scripts/make_draft_prompts.py, on Vx at TWELVE_COMMIT. Table T of + run.sh chooses the draft lengths with these prompts. +- heldout/: 12 other prompts of the same 4 kinds, on Vx at HELDOUT_COMMIT. The benchmark chooses + no setting with them. + +The prompts of twelve/ and heldout/ are chat text, as the chat template of Qwen3.6 writes it with +enable_thinking=false. The script checks this against the template. Each prompt is in vx/ and in +llama/. The -f option of llama.cpp drops the last new line of a file, so the llama/ copy has one +more new line at the end. prompts/tokens.csv gives the number of tokens of each prompt. + +Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +See LICENSE for license information. +SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +""" + +import csv +import pathlib +import subprocess +import sys + +HERE = pathlib.Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parents[2] / "scripts")) +import make_draft_prompts # noqa: E402 + +CONTEXTS = [64, 512, 2048, 8192, 16384, 32768] +QWEN_VX_COMMIT = "8b12928" +TWELVE_COMMIT = "7fb49be57" +HELDOUT_COMMIT = "9d7cf3a49" + + +class GitTree: + """The files of `repo` at `commit`, with the `/` and `read_text` of a pathlib.Path.""" + + def __init__(self, repo, commit, rel=""): + self.repo, self.commit, self.rel = repo, commit, rel + + def __truediv__(self, rel): + return GitTree(self.repo, self.commit, f"{self.rel}/{rel}" if self.rel else rel) + + def read_text(self): + cmd = ["git", "-C", str(self.repo), "show", f"{self.commit}:{self.rel}"] + return subprocess.run(cmd, check=True, capture_output=True, text=True).stdout + + +def chat(user): + return f"<|im_start|>user\n{user}<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" + + +def heldout_prompts(vx): + """12 prompts of the same kinds as those of make_draft_prompts.py, on other files and tasks.""" + + def source(rel): + return (vx / rel).read_text() + + def head(rel, share=0.6): + lines = source(rel).splitlines(keepends=True) + return "".join(lines[: int(len(lines) * share)]) + + def fenced(rel, text): + lang = {"py": "python", "rs": "rust", "c": "c"}[rel.rsplit(".", 1)[1]] + return f"`{rel}`:\n\n```{lang}\n{text}```" + + edit = "Output the whole file, and change nothing else." + complete = ( + "This file stops in the middle. Continue it from exactly where it stops. " + "Output only the rest of the file." + ) + explain = "Explain what this code does, function by function." + e1 = "scripts/tools/differential_fuzz/generators/tensors.py" + e2 = "src/hir/check/host_waits.rs" + e3 = "utils/memalg/measure_link.c" + return { + "edit1": f"{fenced(e1, source(e1))}\n\nAdd a type hint to every function parameter and return value. {edit}", + "edit2": f"{fenced(e2, source(e2))}\n\nAdd a `///` doc comment above every function that has none. {edit}", + "edit3": f"{fenced(e3, source(e3))}\n\nAdd a one-line comment above every function that says what it does. {edit}", + "complete1": f"{fenced('src/hir/flatten/affine.rs', head('src/hir/flatten/affine.rs'))}\n\n{complete}", + "complete2": f"{fenced('utils/memalg/shakedown.py', head('utils/memalg/shakedown.py'))}\n\n{complete}", + "complete3": f"{fenced('stdlib/rust_core/src/io.rs', head('stdlib/rust_core/src/io.rs'))}\n\n{complete}", + "write1": "Write a Python function merge_intervals(intervals) that merges overlapping closed intervals " + "and returns them sorted. Add pytest tests for it, with empty input and touching intervals.", + "write2": "Write a C function `void reverse_words(char *s)` that reverses the order of the words in a " + "string in place, with single spaces between words. Add a main() that tests it.", + "write3": "Write a Rust struct Trie with new, insert, contains and starts_with for lowercase ASCII words. " + "Add unit tests.", + "explain1": f"{fenced('src/hir/places.rs', source('src/hir/places.rs'))}\n\n{explain}", + "explain2": f"{fenced('src/hir/check/drop_waits.rs', source('src/hir/check/drop_waits.rs'))}\n\n{explain}", + "explain3": f"{fenced('src/hir/decl_check/bounds.rs', source('src/hir/decl_check/bounds.rs'))}\n\n{explain}", + } + + +def app_sources(): + """The .vx files of src/ at QWEN_VX_COMMIT, one after the other, model.vx first.""" + repo = HERE.parents[2] + cmd = ["git", "-C", str(repo), "ls-tree", "--name-only", QWEN_VX_COMMIT, "src/"] + names = subprocess.run(cmd, check=True, capture_output=True, text=True).stdout.split() + names = sorted((n for n in names if n.endswith(".vx")), key=lambda n: (n != "src/model.vx", n)) + tree = GitTree(repo, QWEN_VX_COMMIT) + return "".join((tree / n).read_text() for n in names) + + +def first_tokens(tok, text, n): + """The text of the first n tokens of `text`. Asserts that this text has exactly those tokens.""" + ids = tok.encode(text, add_special_tokens=False).ids + assert len(ids) >= n, f"the sources have only {len(ids)} tokens, fewer than {n}" + cut = tok.decode(ids[:n], skip_special_tokens=False) + assert tok.encode(cut, add_special_tokens=False).ids == ids[:n], f"the first {n} tokens do not encode back to themselves" + return cut + + +def check_chat_format(model_dir, user): + from transformers import AutoTokenizer + + t = AutoTokenizer.from_pretrained(model_dir) + messages = [{"role": "user", "content": user}] + want = t.apply_chat_template(messages, tokenize=False, add_generation_prompt=True, enable_thinking=False) + assert chat(user) == want, f"the chat text differs from the template of {model_dir}:\n{want!r}" + + +def main(): + if len(sys.argv) != 3: + sys.exit(__doc__.split("\n\n")[1]) + from tokenizers import Tokenizer + + model_dir, vx = pathlib.Path(sys.argv[1]).expanduser(), pathlib.Path(sys.argv[2]).expanduser() + tok = Tokenizer.from_file(str(model_dir / "tokenizer.json")) + out = HERE / "prompts" + texts = {} + sources = app_sources() + for n in CONTEXTS: + texts[f"context/ctx{n}"] = first_tokens(tok, sources, n) + twelve = make_draft_prompts.prompts(GitTree(vx, TWELVE_COMMIT)) + check_chat_format(model_dir, twelve["write1"]) + for name, user in twelve.items(): + texts[f"twelve/{name}"] = chat(user) + for name, user in heldout_prompts(GitTree(vx, HELDOUT_COMMIT)).items(): + texts[f"heldout/{name}"] = chat(user) + rows = [] + for key, text in texts.items(): + kind, name = key.split("/") + for side, extra in (("vx", ""), ("llama", "\n")): + path = out / kind / side / f"{name}.txt" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text + extra) + rows.append({"prompt": key, "tokens": len(tok.encode(text, add_special_tokens=False).ids)}) + with open(out / "tokens.csv", "w", newline="") as f: + w = csv.DictWriter(f, ["prompt", "tokens"]) + w.writeheader() + w.writerows(rows) + print(len(texts), "prompts in", out) + + +if __name__ == "__main__": + main() diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/parse.py b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/parse.py new file mode 100755 index 0000000..399d952 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/parse.py @@ -0,0 +1,404 @@ +#!/usr/bin/env python3 +"""Read the logs of run.sh, and write runs.csv and summary.md. + + python3 parse.py OUT + python3 parse.py OUT --choose + +OUT is the folder that run.sh wrote. The token counts of the prompts come from prompts/tokens.csv. +A number is missing from a row when its log does not have it, for example after a failed run. +With --choose, the script prints the fastest draft length of each program in table T, as +DRAFT=… MTP_N=…, for run.sh. + +Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +See LICENSE for license information. +SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +""" + +import csv +import math +import re +import statistics +import sys +from collections import defaultdict +from pathlib import Path + +HERE = Path(__file__).resolve().parent +PROGRAMS = { + "vx": "qwen-vx", + "vxdraft": "qwen-vx --draft", + "vxmtp": "qwen-vx --mtp", + "vxmtpdraft": "qwen-vx --mtp --draft", + "completion": "llama-completion", + "cache": "llama.cpp ngram-cache", + "ngram": "llama.cpp ngram-mod", + "mtp": "llama.cpp draft-mtp", +} +# The variable of run.sh that takes the chosen draft length of each program. +CHOICES = {"vxdraft": "DRAFT", "mtp": "MTP_N"} +# The programs of the app with drafts. Each must write the text of qwen-vx. +VX_DRAFTS = {PROGRAMS[p] for p in ("vxdraft", "vxmtp", "vxmtpdraft")} +KINDS = ["edit", "complete", "write", "explain"] +SETS = {"T": "twelve", "C": "heldout"} + + +def num(pattern, text, cast=float): + m = re.search(pattern, text) + return cast(m[1]) if m else None + + +def parse_log(program, text): + """The numbers of one log. Times are in ms.""" + r = {} + if program.startswith("vx"): + r["ms_per_token"] = num(r"time ms_per_token=([0-9.]+)", text) + r["prompt_ms_per_token"] = num(r"time prompt_ms_per_token=([0-9.]+)", text) + r["prompt_runs_ms"] = [float(x) for x in re.findall(r"time prompt_ms=([0-9.]+)", text)] + m = re.search(r"rounds=(\d+) drafted=(\d+) accepted=(\d+)", text) + if m: + r["checks"], r["drafted"], r["accepted"] = int(m[1]), int(m[2]), int(m[3]) + elif program == "completion": + perf = r"common_perf_print: *" + r["ms_per_token"] = num(perf + r"eval time = *[0-9.]+ ms / *\d+ runs *\( *([0-9.]+) ms per token", text) + r["timed_tokens"] = num(perf + r"eval time = *[0-9.]+ ms / *(\d+) runs", text, int) + r["prompt_ms"] = num(perf + r"prompt eval time = *([0-9.]+) ms", text) + r["llama_prompt_tokens"] = num(perf + r"prompt eval time = *[0-9.]+ ms / *(\d+) tokens", text, int) + else: # llama-speculative-simple + m = re.search(r"decoded +(\d+) tokens in +([0-9.]+) seconds", text) + if m: + r["timed_tokens"] = int(m[1]) + r["ms_per_token"] = float(m[2]) * 1000 / int(m[1]) + m = re.search(r"encoded +(\d+) tokens in +([0-9.]+) seconds", text) + if m: + r["llama_prompt_tokens"], r["prompt_ms"] = int(m[1]), float(m[2]) * 1000 + r["drafted"] = num(r"n_drafted *= *(\d+)", text, int) + r["accepted"] = num(r"n_accept *= *(\d+)", text, int) + if not program.startswith("vx"): + r["threads"] = num(r"n_threads = (\d+)", text, int) + return r + + +LOG_LINE = re.compile(r"\d+\.\d+\.\d+\.\d+ [A-Z] ") + + +def answer(path): + """The text that a program wrote after the chat prompt, without the lines of times and drafts.""" + lines = path.read_text(errors="replace").split("\n") + start = next((i + 2 for i, line in enumerate(lines) if line == ""), None) + assert start is not None, f"{path} has no chat prompt" + out = [] + for line in lines[start:]: + if line.startswith("time ") or LOG_LINE.match(line): + break + line = re.sub(r"context_drafts: rounds=\d+ drafted=\d+ kept=\d+;", "", line) + out.append(re.sub(r"rounds=\d+ drafted=\d+ accepted=\d+;", "", line)) + return "\n".join(out).rstrip("\n") + + +def agree(a, b): + """The number of characters at the start of a and b that are the same.""" + n = 0 + while n < min(len(a), len(b)) and a[n] == b[n]: + n += 1 + return n + + +def read_rows(out): + tokens = {row["prompt"]: int(row["tokens"]) for row in csv.DictReader(open(HERE / "prompts" / "tokens.csv"))} + meta = {} + for line in open(out / "log.txt"): + m = re.match(r"(\S+) start=(\S+) end=(\S+) rc=(\d+) busy=\[(.*)\] gpu=(\d*)%", line) + if m: + meta[m[1]] = dict(start=m[2], end=m[3], rc=int(m[4]), busy=m[5], gpu=m[6]) + fa = re.search(r"flash attention:.*chosen: (\w+)", (out / "env.txt").read_text()) + rows = [] + for name, m in sorted(meta.items()): + if name.startswith("llama-bench"): + continue + parts = name.split(".") + setting = "" + if name.startswith("fa-"): # fa-on.ctx2048.r1 + table, prompt, rnd, program = "fa", f"context/{parts[1]}", parts[2], "completion" + elif parts[0] in ("A", "P"): # A.vx.ctx512.r1 + table, prompt, rnd = parts[0], f"context/{parts[2]}", parts[3] + program = "vx" if parts[1] == "vx" else "completion" + else: # T.edit1.r1.vxdraft7 + table, prompt, rnd = parts[0], f"{SETS[parts[0]]}/{parts[1]}", parts[2] + program, setting = re.fullmatch(r"([a-z]+)(\d*)", parts[3]).groups() + text = (out / "logs" / f"{name}.txt").read_text(errors="replace") + r = parse_log(program, text) + n = tokens[prompt] + if r.get("prompt_ms_per_token") is not None: + r["prompt_ms"] = r["prompt_ms_per_token"] * n + runs = r.get("prompt_runs_ms") or [] + flash = parts[0][3:] if table == "fa" else (fa[1] if fa and not program.startswith("vx") else "") + rows.append(dict( + table=table, prompt=prompt, kind=re.sub(r"\d", "", prompt.split("/")[1]), round=rnd[1:], + program=PROGRAMS[program], setting=setting, prompt_tokens=n, + llama_prompt_tokens=r.get("llama_prompt_tokens"), prompt_ms=r.get("prompt_ms"), + first_prompt_ms=runs[0] if runs else None, later_prompt_ms=" ".join(f"{x:.1f}" for x in runs[1:]), + ms_per_token=r.get("ms_per_token"), timed_tokens=r.get("timed_tokens"), checks=r.get("checks"), + drafted=r.get("drafted"), accepted=r.get("accepted"), flash_attn=flash, threads=r.get("threads"), + errors=len(re.findall(r"^\d+\.\d+\.\d+\.\d+ E ", text, re.M)), + log=f"logs/{name}.txt", **m, + )) + return rows + + +def write_csv(out, rows): + with open(out / "runs.csv", "w", newline="") as f: + w = csv.DictWriter(f, list(rows[0].keys()), lineterminator="\n") + w.writeheader() + for r in rows: + w.writerow({k: (f"{v:.4f}" if isinstance(v, float) else v) for k, v in r.items()}) + + +def geomean(xs): + return math.exp(sum(math.log(x) for x in xs) / len(xs)) + + +def spread(xs, fmt="{:.2f}"): + """The median, and the fastest and the slowest run.""" + return f"{fmt.format(statistics.median(xs))} ({fmt.format(min(xs))}-{fmt.format(max(xs))})" + + +def timed(rows, table, program=None, setting=None): + """The runs of the summary: no failed runs, no runs with error lines, and no runs of the app with + drafts that wrote other text than qwen-vx. The summary keeps the runs of llama.cpp with drafts that wrote + other text: the shape of their batches changes the result at near ties. say_same_text lists them.""" + return [r for r in rows if r["table"] == table and r["rc"] == 0 and r["ms_per_token"] is not None + and not r["errors"] and not (r["program"] in VX_DRAFTS and r.get("same_text") is False) + and (program is None or r["program"] == program) and (setting is None or r["setting"] == setting)] + + +def tuning(rows): + """For each program and draft length of table T: the geometric mean over the prompts, if it ran on all.""" + prompts = {r["prompt"] for r in rows if r["table"] == "T"} + means = {} + for key in {(r["program"], r["setting"]) for r in timed(rows, "T")}: + rr = timed(rows, "T", *key) + if {r["prompt"] for r in rr} == prompts: + means[key] = geomean([r["ms_per_token"] for r in rr]) + return means + + +def choose(rows): + means = tuning(rows) + words = [] + for program, variable in CHOICES.items(): + options = {s: v for (p, s), v in means.items() if p == PROGRAMS[program]} + assert options, f"table T has no complete set of runs of {PROGRAMS[program]}" + words.append(f"{variable}={min(options, key=options.get)}") + return " ".join(words) + + +def plain_log(r): + """The log of the run without drafts of the same program, prompt and round, for a run with drafts.""" + if r["table"] not in SETS or r["program"] in (PROGRAMS["vx"], PROGRAMS["completion"]): + return None + plain = "vx" if r["program"] in VX_DRAFTS else "completion" + return re.sub(r"\.[a-z]+\d*\.txt$", f".{plain}.txt", r["log"]) + + +def mark_same_text(out, rows): + """Whether each run with drafts wrote the text of the run without drafts. The app with drafts must + write the same text. A program of llama.cpp may generate a few more tokens with drafts, so its + text must start with the whole text of llama-completion. same_chars is the number of equal + characters at the start of the two texts.""" + for r in rows: + r["same_text"] = r["same_chars"] = "" + log = plain_log(r) + if log is None or r["rc"] != 0 or not (out / log).exists(): + continue + a, b = answer(out / log), answer(out / r["log"]) + r["same_text"] = a == b if r["program"] in VX_DRAFTS else b.startswith(a) + r["same_chars"] = agree(a, b) + + +def say_same_text(say, rows, table): + for p in PROGRAMS.values(): + rr = [r for r in rows if r["table"] == table and r["program"] == p and r["same_text"] != ""] + if rr: + vx = p in VX_DRAFTS + plain = "qwen-vx" if vx else "llama-completion" + differ = [r for r in rr if not r["same_text"]] + say(f"- {p}: the text of {plain} in {len(rr) - len(differ)} of {len(rr)} runs" + + (f". Other text, {'out of' if vx else 'in'} the summary (the number of equal characters " + f"at the start): " + ", ".join(f"{r['log']} ({r['same_chars']})" for r in differ) + if differ else "")) + + +def summary(out, rows): + lines = [] + say = lines.append + bad = [r["log"] for r in rows if r["rc"] != 0] + if bad: + say("Failed runs: " + ", ".join(bad)) + say("") + errors = [r["log"] for r in rows if r["errors"]] + if errors: + say("Runs with error lines, out of the summary: " + ", ".join(errors)) + say("") + wrong = sorted({r["prompt"] for r in rows if r["llama_prompt_tokens"] not in (None, r["prompt_tokens"])}) + if wrong: + say("llama.cpp read another number of tokens for: " + ", ".join(wrong)) + say("") + # Each start of run.sh adds these lines to env.txt. Show each line once. + lines += dict.fromkeys(line.strip() for line in open(out / "env.txt") + if line.startswith(("flash attention:", "draft lengths"))) + say("") + + say("## Table A: generated tokens after a prompt") + say("") + say("ms for each generated token: the median of the runs, and the fastest and slowest run. The prompt time " + "is that of the first prompt of a process.") + say("") + say("| Prompt tokens | qwen-vx ms | llama.cpp ms | qwen-vx tok/s | llama.cpp tok/s | llama.cpp ms / qwen-vx ms " + "| qwen-vx prompt ms | llama.cpp prompt ms |") + say("| ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |") + for prompt in sorted({r["prompt"] for r in rows if r["table"] == "A"}, key=lambda p: int(p.split("ctx")[1])): + a = [r for r in timed(rows, "A", "qwen-vx") if r["prompt"] == prompt] + b = [r for r in timed(rows, "A", "llama-completion") if r["prompt"] == prompt] + if not a or not b: + continue + ma, mb = statistics.median(r["ms_per_token"] for r in a), statistics.median(r["ms_per_token"] for r in b) + pa = [r["prompt_ms"] for r in a if r["prompt_ms"] is not None] + pb = [r["prompt_ms"] for r in b if r["prompt_ms"] is not None] + say(f"| {a[0]['prompt_tokens']:,} | {spread([r['ms_per_token'] for r in a])} " + f"| {spread([r['ms_per_token'] for r in b])} | {1000 / ma:.1f} | {1000 / mb:.1f} | {mb / ma:.3f} " + f"| {spread(pa, '{:.0f}') if pa else ''} | {spread(pb, '{:.0f}') if pb else ''} |") + say("") + + say("## Table P: the prompt") + say("") + say("Tokens of the prompt each second: the median of the runs, and the slowest and fastest run. qwen-vx ran " + "the prompt several times in one process. The first run includes the first launch of each kernel. " + "llama-completion ran the prompt once, after its warm-up.") + say("") + say("| Prompt tokens | qwen-vx first run | qwen-vx later runs | llama-completion |") + say("| ---: | ---: | ---: | ---: |") + for prompt in sorted({r["prompt"] for r in rows if r["table"] == "P"}, key=lambda p: int(p.split("ctx")[1])): + ok = [r for r in rows if r["table"] == "P" and r["rc"] == 0 and r["prompt"] == prompt] + n = ok[0]["prompt_tokens"] if ok else 0 + first = [n * 1000 / r["first_prompt_ms"] for r in ok if r["program"] == "qwen-vx" and r["first_prompt_ms"]] + later = [n * 1000 / float(x) for r in ok if r["program"] == "qwen-vx" for x in r["later_prompt_ms"].split()] + llama = [n * 1000 / r["prompt_ms"] for r in ok if r["program"] == "llama-completion" and r["prompt_ms"]] + say(f"| {n:,} | {spread(first, '{:.0f}') if first else ''} | {spread(later, '{:.0f}') if later else ''} " + f"| {spread(llama, '{:.0f}') if llama else ''} |") + say("") + + means = tuning(rows) + if means: + say("## Table T: draft lengths, on the 12 tuning prompts") + say("") + say("ms for each generated token: the geometric mean over the 12 prompts, one run each.") + say("") + say("| Program | Draft length | ms | accepted / drafted |") + say("| --- | ---: | ---: | ---: |") + for (program, setting), v in sorted(means.items(), key=lambda kv: (kv[0][0], int(kv[0][1] or 0))): + rr = timed(rows, "T", program, setting) + acc, dr = sum(r["accepted"] or 0 for r in rr), sum(r["drafted"] or 0 for r in rr) + say(f"| {program} | {setting} | {v:.2f} | {f'{acc} / {dr} ({100 * acc / dr:.0f}%)' if dr else ''} |") + say("") + say_same_text(say, rows, "T") + say("") + + programs = [p for p in PROGRAMS.values() if timed(rows, "C", p)] + if programs: + say("## Table C: the 12 held-out prompts") + say("") + say("ms for each generated token: the geometric mean over the prompts of each kind, and the fastest and " + "slowest run.") + say("") + say("| Kind | Prompt tokens | " + " | ".join(programs) + " |") + say("| --- | --- | " + " | ".join("---:" for _ in programs) + " |") + for kind in KINDS + [None]: + cells = [] + for p in programs: + xs = [r["ms_per_token"] for r in timed(rows, "C", p) if kind is None or r["kind"] == kind] + cells.append(f"{geomean(xs):.2f} ({min(xs):.2f}-{max(xs):.2f})" if xs else "") + counts = sorted({r["prompt_tokens"] for r in timed(rows, "C", "qwen-vx") if r["kind"] == kind}) + say(f"| {kind or 'all 12'} | {', '.join(map(str, counts))} | " + " | ".join(cells) + " |") + say("") + mean = {} + for p in programs: + by = defaultdict(list) + for r in timed(rows, "C", p): + by[r["prompt"]].append(r["ms_per_token"]) + mean[p] = {k: statistics.mean(v) for k, v in by.items()} + + def compare(a, b): + ks = [k for k in mean.get(a, {}) if k in mean.get(b, {})] + ratios = [mean[b][k] / mean[a][k] for k in ks] + if ratios: + say(f"- {a} against {b}: {geomean(ratios):.3f}, faster on {sum(x > 1 for x in ratios)} of " + f"{len(ratios)} prompts ({min(ratios):.2f} to {max(ratios):.2f})") + + compare("qwen-vx", "llama-completion") + # Each program of the app with drafts against the plain app, the app with the drafts before it + # in the list, llama-completion and each program of llama.cpp with drafts. One line for each pair. + vx_drafts = [p for p in programs if p in VX_DRAFTS] + for i, a in enumerate(vx_drafts): + for p in ["qwen-vx"] + vx_drafts[:i] + [p for p in programs if p == "llama-completion" or p.startswith("llama.cpp ")]: + compare(a, p) + for p in programs: + if p.startswith("llama.cpp "): + compare(p, "llama-completion") + say("") + say("### Drafts, table C, round 1") + say("") + drafters = [p for p in programs if p not in ("qwen-vx", "llama-completion")] + say("| Kind | " + " | ".join(f"{p} accepted / drafted" for p in drafters) + " |") + say("| --- | " + " | ".join("---:" for _ in drafters) + " |") + for kind in KINDS + [None]: + cells = [] + for p in drafters: + rr = [r for r in timed(rows, "C", p) if r["round"] == "1" and (kind is None or r["kind"] == kind)] + acc, dr = sum(r["accepted"] or 0 for r in rr), sum(r["drafted"] or 0 for r in rr) + checks = sum(r["checks"] or 0 for r in rr) + cells.append((f"{acc} / {dr} ({100 * acc / dr:.0f}%)" if dr else "") + + (f", {acc / checks:.2f} per check" if checks else "")) + say(f"| {kind or 'all 12'} | " + " | ".join(cells) + " |") + say("") + say_same_text(say, rows, "C") + say("") + say("### qwen-vx and llama-completion: where the text starts to differ") + say("") + say("The characters at the start of the generated text that are the same, round 1. The weight files " + "differ in the token embedding and the output matrix, so the greedy text of the two programs can differ.") + say("") + say("| Prompt | Same characters | Characters of llama-completion |") + say("| --- | ---: | ---: |") + for prompt in sorted({r["prompt"] for r in rows if r["table"] == "C"}): + pair = {r["program"]: r for r in rows if r["table"] == "C" and r["prompt"] == prompt and r["round"] == "1" + and r["rc"] == 0} + if PROGRAMS["vx"] in pair and PROGRAMS["completion"] in pair: + a = answer(out / pair[PROGRAMS["completion"]]["log"]) + say(f"| {prompt.split('/')[1]} | {agree(a, answer(out / pair[PROGRAMS['vx']]['log']))} | {len(a)} |") + say("") + + for name in ("llama-bench-pp", "llama-bench-tg"): + path = out / "logs" / f"{name}.txt" + if path.exists(): + say(f"## {name}") + say("") + lines += [line for line in path.read_text().splitlines() if line.startswith("|")] + say("") + (out / "summary.md").write_text("\n".join(lines) + "\n") + print("\n".join(lines)) + + +def main(): + if len(sys.argv) not in (2, 3) or sys.argv[2:] not in ([], ["--choose"]): + sys.exit(__doc__.split("\n\n")[1]) + out = Path(sys.argv[1]) + rows = read_rows(out) + mark_same_text(out, rows) + if sys.argv[2:] == ["--choose"]: + print(choose(rows)) + return + write_csv(out, rows) + summary(out, rows) + + +if __name__ == "__main__": + main() diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/context/llama/ctx16384.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/context/llama/ctx16384.txt new file mode 100644 index 0000000..86bc604 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/context/llama/ctx16384.txt @@ -0,0 +1,902 @@ +//===- model.vx - Qwen app --------------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// One token of a Qwen2 or Qwen3 MoE decoder on the GPU, with the kernels of `std::nn`. `State` +// holds every tensor that a token writes, and the KV cache. It is made once, before the first +// token, so the token loop allocates nothing. +import core::convert; +import core::num; +import std::nn; +import std::vec; +import qwen::attention; +import qwen::products; +import qwen::q6; +import qwen::weights; + +/// The keys and the values of every position so far, for one layer: [max_seq, kv_heads, head_dim]. +/// They are f16, half the memory of f32. The kernels compute in f32, and round only what they +/// store here. +struct Cache { + k : Tensor, + v : Tensor, +} + +/// The tensors of a mixture-of-experts layer: the router's score of each expert, the chosen +/// experts and their weights, and the SwiGLU output of each chosen expert, [experts_per_token, +/// moe_intermediate_size]. +struct Experts { + router_logits : Tensor, + ids : Tensor, + weights : Tensor, + mlp : Tensor, +} + +/// The tensors that a token writes, in GPU memory, and one `Cache` for each layer. `cos` and `sin` +/// are [max_seq, head_dim / 2]. +struct State { + max_seq : i32, + x : Tensor, + xn : Tensor, + q : Tensor, + k : Tensor, + v : Tensor, + q_turned : Tensor, + attended : Tensor, + attention_parts : Tensor, + vec_parts : Tensor, + mlp : Tensor, + experts : Experts, + logits : Tensor, + cos : Tensor, + sin : Tensor, + caches : Vec, +} + +/// The state for up to `max_seq` positions. The angles of RoPE are computed in f64, as in +/// `reference.py`, and rounded to f32 once. +fn new_state(c : &Config, max_seq : i32) -> State { + assert(max_seq > 0 && max_seq <= c.max_positions, "max_seq must be between 1 and the max_positions of the model"); + let half = c.head_dim / 2; + let mut hcos = Tensor([max_seq, half]); + let mut hsin = Tensor([max_seq, half]); + for p in 0..max_seq { + for i in 0..half { + let angle = f64::from(p) / f64::powf(c.rope_theta, f64::from(2 * i) / f64::from(c.head_dim)); + hcos[p][i] = f64::cos(angle) as f32; + hsin[p][i] = f64::sin(angle) as f32; + } + } + // A dense model uses none of the tensors of the experts, so one value each is enough. + let experts = i32::max(c.num_experts, 1); + let chosen = i32::max(c.experts_per_token, 1); + let moe_inter = i32::max(c.moe_intermediate_size, 1); + // The flash attention of a prompt reads the cache in blocks of 64 positions. + let rows = (max_seq + 63) / 64 * 64; + let mut caches = Vec::new(); + for l in 0..c.num_layers { + caches.push(Cache { + k: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + }); + } + return State { + max_seq: max_seq, + x: transfer(Tensor([c.hidden_size]), Memory::HBM), + xn: transfer(Tensor([c.hidden_size]), Memory::HBM), + q: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + k: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + q_turned: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attended: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attention_parts: transfer(split_attention_scratch(max_seq, c.num_q_heads, c.num_kv_heads, c.head_dim), Memory::HBM), + vec_parts: transfer(vec_attention_scratch(c.num_q_heads), Memory::HBM), + mlp: transfer(Tensor([c.intermediate_size]), Memory::HBM), + experts: Experts { + router_logits: transfer(Tensor([experts]), Memory::HBM), + ids: transfer(Tensor([chosen]), Memory::HBM), + weights: transfer(Tensor([chosen]), Memory::HBM), + mlp: transfer(Tensor([chosen, moe_inter]), Memory::HBM), + }, + logits: transfer(Tensor([c.vocab_size]), Memory::HBM), + cos: transfer(hcos, Memory::HBM), + sin: transfer(hsin, Memory::HBM), + caches: caches, + }; +} + +/// y = m x, with the kernel for the dtype of `m`, which has `rows` x `cols` weights. +fn matvec(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U6 { + matvec_q6(y, &m.codes, &m.high, &m.group_scales, x, rows, cols); + } else if m.dtype == U4 { + nn_matvec_q4(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x. +fn matvec_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_matvec_q4_add(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_add(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec_add(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x, for x of [heads, head_dim]. +fn matvec_heads_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, heads : i32, head_dim : i32) -> void { + if m.dtype == U4 { + matvec_q4_heads_add_blocks(y, &m.codes, &m.group_scales, x, rows, heads, head_dim); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_heads_add(y, &m.codes, &m.scales, x, rows, heads, head_dim); + } else { + nn_matvec_heads_add(y, &m.bf16, x, rows, heads, head_dim); + } + return; +} + +/// The Q, K and V of x: m x + b, split by heads. +fn qkv(q : &mut Tensor, k : &mut Tensor, v : &mut Tensor, m : &WeightMatrix, b : &Tensor, x : &Tensor, c : &Config) -> void { + if m.dtype == U4 { + qkv_q4_blocks(q, k, v, &m.codes, &m.group_scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } else if m.dtype == F8E4M3 { + nn_qkv_fp8(q, k, v, &m.codes, &m.scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } else { + nn_qkv(q, k, v, &m.bf16, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } + return; +} + +/// The SwiGLU of a dense MLP, for the gate rows and then the up rows of `m`. +fn swiglu(out : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_swiglu_q4(out, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_swiglu_fp8(out, &m.codes, &m.scales, x, rows, cols); + } else { + nn_swiglu(out, &m.bf16, x, rows, cols); + } + return; +} + +/// The mixture of experts of a layer: the router chooses experts_per_token experts and their +/// weights, and x gets the sum of their outputs for xn, each times its weight. +fn add_experts(e : &mut Experts, x : &mut Tensor, xn : &Tensor, layer : &Layer, c : &Config) -> void { + let k = c.experts_per_token; + let inter = c.moe_intermediate_size; + nn_matvec(&mut e.router_logits, &layer.router, xn, c.num_experts, c.hidden_size); + nn_top_k(&mut e.ids, &mut e.weights, &e.router_logits, c.num_experts, k); + let gate_up = &layer.gate_up; + let down = &layer.down; + if gate_up.dtype == U4 { + moe_swiglu_q4_blocks(&mut e.mlp, &gate_up.codes, &gate_up.group_scales, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + moe_down_q4_add_blocks(x, &down.codes, &down.group_scales, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + } else { + assert(gate_up.dtype == BF16, "the experts of a mixture-of-experts model must be bf16 or Q4_0"); + nn_moe_swiglu(&mut e.mlp, &gate_up.bf16, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + nn_moe_down_add(x, &down.bf16, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + } + return; +} + +/// Runs the token in `token` at position `pos` through every layer. The hidden state of the +/// token is then in `s.x`, and its keys and values are in the caches. +fn run_layers(w : &Weights, s : &mut State, token : &Tensor, pos : i32) -> void { + let c = &w.config; + let eps = c.rms_norm_eps as f32; + assert(pos >= 0 && pos < s.max_seq, "the position is past the end of the KV cache"); + nn_embed(&mut s.x, &w.embed, token, c.hidden_size); + let mut l = 0; + for cache in s.caches.iter_mut() { + let layer = &w.layers[l]; + nn_rms_norm(&mut s.xn, &s.x, &layer.attn_norm, c.hidden_size, eps); + qkv(&mut s.q, &mut s.k, &mut s.v, &layer.qkv, &layer.qkv_bias, &s.xn, c); + if c.qk_norm { + norm_rope_and_store(&mut s.q_turned, &mut cache.k, &mut cache.v, &s.q, &s.k, &s.v, &layer.q_norm, &layer.k_norm, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.head_dim, eps); + } else { + rope_and_store(&mut s.q_turned, &mut cache.k, &mut cache.v, &s.q, &s.k, &s.v, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } + if c.head_dim == 128 { + vec_attention(&mut s.attended, &mut s.vec_parts, &s.q_turned, &cache.k, &cache.v, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } else { + split_attention(&mut s.attended, &mut s.attention_parts, &s.q_turned, &cache.k, &cache.v, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } + matvec_heads_add(&mut s.x, &layer.attn_out, &s.attended, c.hidden_size, c.num_q_heads, c.head_dim); + nn_rms_norm(&mut s.xn, &s.x, &layer.mlp_norm, c.hidden_size, eps); + if c.num_experts > 0 { + add_experts(&mut s.experts, &mut s.x, &s.xn, layer, c); + } else { + swiglu(&mut s.mlp, &layer.gate_up, &s.xn, c.intermediate_size, c.hidden_size); + matvec_add(&mut s.x, &layer.down, &s.mlp, c.hidden_size, c.intermediate_size); + } + l = l + 1; + } + return; +} + +/// The logits of the token whose hidden state is in `s.x`, and in `next` the index of the largest +/// one. Both stay in GPU memory. +fn predict(w : &Weights, s : &mut State, next : &mut Tensor) -> void { + let c = &w.config; + nn_rms_norm(&mut s.xn, &s.x, &w.final_norm, c.hidden_size, c.rms_norm_eps as f32); + if c.tied_embeddings { + nn_matvec(&mut s.logits, &w.embed, &s.xn, c.vocab_size, c.hidden_size); + } else { + matvec(&mut s.logits, &w.lm_head, &s.xn, c.vocab_size, c.hidden_size); + } + nn_argmax(next, &s.logits, c.vocab_size); + return; +} +//===- attention.vx - Qwen app ----------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// The attention of one generated token, with the positions split among blocks. This is a copy of +// `nn_attention` and its kernels from `std::nn` on Vx main (vx-lang/Vx#3216), with `split_` in place +// of `nn_` in their names. Vx v0.0.4 has the older `nn_attention`, which has one block for each head +// of Q, so its time grows with the number of positions. Remove this file, and call `nn_attention` +// of `std::nn`, when a Vx release has the new one (#4). +// +// `vec_attention`, for head_dim 128, has the design of llama.cpp's flash attention for one token +// (kernel_flash_attn_ext_vec and kernel_flash_attn_ext_vec_reduce), MIT License, Copyright (c) 2023-2026 +// The ggml authors. scripts/mlir_kernels/decode_attention.py writes its kernels: change that script, not +// the MLIR. +import core::num; +import std::nn; + +/// Attention of the token at position `pos` over rows 0 to `pos` of the KV cache, with a softmax +/// of the scores q . k / sqrt(head_dim). `part` is scratch space from `split_attention_scratch`. +/// +/// The blocks of the first kernel split the positions, 32 to a block below position 640 and 64 from +/// there on. A block serves the 8 heads of Q that share a head of K and V, so it reads each row of +/// the cache once for all 8. A second kernel merges the parts of the blocks for each head. +fn split_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_heads % kv_heads == 0, "split_attention: q_heads must be a multiple of kv_heads"); + assert(head_dim % 32 == 0 && head_dim <= 128, "split_attention: head_dim must be a multiple of 32, and at most 128"); + let mut n_pos = 32; + if pos >= 640 { + n_pos = 64; + } + assert(part.extent(0) >= kv_heads * ((q_heads / kv_heads + 7) / 8) && part.extent(1) >= (pos + n_pos) / n_pos && part.extent(2) >= 8 && part.extent(3) >= head_dim + 2, "split_attention: `part` is too small for this position. Make it with split_attention_scratch"); + if n_pos == 32 { + split_attention_parts_32(part, q, k_cache, v_cache, pos, q_heads, kv_heads, head_dim); + } else { + split_attention_parts_64(part, q, k_cache, v_cache, pos, q_heads, kv_heads, head_dim); + } + split_attention_merge(out, part, pos, n_pos, q_heads, kv_heads, head_dim); + return; +} + +/// Attention of the token at position `pos`, as `split_attention`, for head_dim 128, with the kernels of +/// llama.cpp's flash attention for one token. `vec_attention_parts` splits the blocks of 32 positions among +/// `nwg` SIMD groups for each head of Q: 32 of them, or 64 when each of 32 would have more than 2 blocks. +/// (llama.cpp goes on to 4 SIMD groups of 32 a block, but 128 parts are no faster here: their merge costs what +/// they save.) `vec_attention_merge` then merges the parts. `part` is scratch space from +/// `vec_attention_scratch`. +fn vec_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_heads % kv_heads == 0 && head_dim == 128, "vec_attention: q_heads must be a multiple of kv_heads, and head_dim 128"); + assert(part.extent(0) >= q_heads && part.extent(1) >= 128 && part.extent(2) == 132, "vec_attention: `part` is too small. Make it with vec_attention_scratch"); + let mut nwg = 32; + if 2 * nwg * 32 < pos + 1 { + nwg = nwg * 2; + } + vec_attention_parts(part, q, k_cache, v_cache, pos, q_heads, q_heads / kv_heads, nwg, 1.0 / (head_dim as f32).sqrt()); + vec_attention_merge(out, part, nwg, q_heads); + return; +} + +/// The scratch space of `vec_attention`, on the CPU: up to 128 parts for each head of Q, each the sum of V +/// (128 values), the largest score, and the sum of the weights. A part has 132 values, so that each starts +/// at a multiple of 16 bytes. +fn vec_attention_scratch(q_heads : i32) -> Tensor { + return Tensor([q_heads, 128, 132]); +} + +/// The parts of `vec_attention`, as llama.cpp's kernel_flash_attn_ext_vec. Block (h, w) is a SIMD group for +/// query head h. It does the blocks of 32 positions w, w + nwg, w + 2 nwg, ... up to `pos`, and writes +/// part[h][w]. Lane l owns values 4 l to 4 l + 3 of the head, so that the 32 lanes read a row of K or V in +/// one 256-byte load. For each row, the lanes add up their parts of q . k; then each lane keeps the score +/// of one row, and the lanes take the weights of the rows from each other for the sum of V. A part is the +/// sum of V, not divided, then the largest score and the sum of the weights. +fn vec_attention_parts(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, group : i32, nwg : i32, scale : f32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for w in 0..nwg across blocks { + let g = h / group; + let _d = mlir!( threads : 32, inputs : (%part = part : memref, %q = q : memref, %k3 = k_cache : memref, %v3 = v_cache : memref, %pos = pos : i32, %nwg = nwg : i32, %scale = scale : f32, %h = h : i32, %w = w : i32, %g = g : i32), returns : i32, dialects : ["arith", "memref", "scf", "gpu", "vector", "math"], ensures : [reads_only(q), reads_only(k_cache), reads_only(v_cache), writes_only(part[h][w])]) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %c4 = arith.constant 4 : index + %c32 = arith.constant 32 : index + %c128 = arith.constant 128 : index + %c129 = arith.constant 129 : index + %c32i = arith.constant 32 : i32 + %neg = arith.constant -3.0e38 : f32 + %zero = arith.constant 0.0 : f32 + %vz4 = arith.constant dense<0.0> : vector<4xf32> + %l = gpu.thread_id x + %l4 = arith.muli %l, %c4 : index + %hi = arith.index_cast %h : i32 to index + %wi = arith.index_cast %w : i32 to index + %gi = arith.index_cast %g : i32 to index + %posi = arith.index_cast %pos : i32 to index + %nwgi = arith.index_cast %nwg : i32 to index + %g128 = arith.muli %gi, %c128 : index + %kd = arith.addi %g128, %l4 : index + %P = memref.dim %k3, %c0 : memref + %KH = memref.dim %k3, %c1 : memref + %Wd = arith.muli %KH, %c128 : index + %k = memref.reinterpret_cast %k3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to memref> + %v = memref.reinterpret_cast %v3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to memref> + %qv = vector.load %q[%hi, %l4] {alignment = 16} : memref, vector<4xf32> + %scv = vector.broadcast %scale : f32 to vector<4xf32> + %qs = arith.mulf %qv, %scv : vector<4xf32> + %nkv = arith.addi %posi, %c32 : index + %chunks = arith.divui %nkv, %c32 : index + %st:3 = scf.for %ic = %wi to %chunks step %nwgi iter_args(%M = %neg, %S = %zero, %o = %vz4) -> (f32, f32, vector<4xf32>) { + %r0 = arith.muli %ic, %c32 : index + %my = scf.for %cc = %c0 to %c32 step %c1 iter_args(%m = %neg) -> (f32) { + %row = arith.addi %r0, %cc : index + %rowc = arith.minui %row, %posi : index + %kh = vector.load %k[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> + %kf = arith.extf %kh : vector<4xf16> to vector<4xf32> + %pr = arith.mulf %kf, %qs : vector<4xf32> + %pl = vector.reduction , %pr : vector<4xf32> into f32 + %sc = gpu.subgroup_reduce add %pl : (f32) -> f32 + %live = arith.cmpi ule, %row, %posi : index + %scm = arith.select %live, %sc, %neg : f32 + %mine = arith.cmpi eq, %cc, %l : index + %m2 = arith.select %mine, %scm, %m : f32 + scf.yield %m2 : f32 + } + %bm = gpu.subgroup_reduce maxnumf %my : (f32) -> f32 + %Mn = arith.maxnumf %M, %bm : f32 + %dm = arith.subf %M, %Mn : f32 + %ms = math.exp %dm : f32 + %dp = arith.subf %my, %Mn : f32 + %p = math.exp %dp : f32 + %bs = gpu.subgroup_reduce add %p : (f32) -> f32 + %Ss = arith.mulf %S, %ms : f32 + %Sn = arith.addf %Ss, %bs : f32 + %msv = vector.broadcast %ms : f32 to vector<4xf32> + %o1 = arith.mulf %o, %msv : vector<4xf32> + %o2 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%oa = %o1) -> (vector<4xf32>) { + %row = arith.addi %r0, %cc : index + %rowc = arith.minui %row, %posi : index + %vh = vector.load %v[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> + %vf = arith.extf %vh : vector<4xf16> to vector<4xf32> + %cci = arith.index_cast %cc : index to i32 + %pc, %pv = gpu.shuffle idx %p, %cci, %c32i : f32 + %pcv = vector.broadcast %pc : f32 to vector<4xf32> + %on = vector.fma %vf, %pcv, %oa : vector<4xf32> + scf.yield %on : vector<4xf32> + } + scf.yield %Mn, %Sn, %o2 : f32, f32, vector<4xf32> + } + vector.store %st#2, %part[%hi, %wi, %l4] : memref, vector<4xf32> + %lane0 = arith.cmpi eq, %l, %c0 : index + scf.if %lane0 { + memref.store %st#0, %part[%hi, %wi, %c128] : memref + memref.store %st#1, %part[%hi, %wi, %c129] : memref + } + macro.yield %h : i32 + }; + } + } + } + return; +} + +/// Merges the first `parts` parts of `vec_attention_parts` for each head of Q, as llama.cpp's +/// kernel_flash_attn_ext_vec_reduce. A block of 4 SIMD groups does one head: each lane weighs up to 4 parts, +/// and the SIMD groups add them up for 4 values of the head at a time. +fn vec_attention_merge(out : &mut Tensor, part : &Tensor, parts : i32, q_heads : i32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + let _d = mlir!( threads : 128, inputs : (%out = out : memref, %part = part : memref, %parts = parts : i32, %h = h : i32), returns : i32, dialects : ["arith", "memref", "scf", "gpu", "vector", "math"], ensures : [reads_only(part), writes_only(out[h])]) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %c2 = arith.constant 2 : index + %c3 = arith.constant 3 : index + %c4 = arith.constant 4 : index + %c16 = arith.constant 16 : index + %c32 = arith.constant 32 : index + %c64 = arith.constant 64 : index + %c96 = arith.constant 96 : index + %c128 = arith.constant 128 : index + %c129 = arith.constant 129 : index + %neg = arith.constant -3.0e38 : f32 + %zero = arith.constant 0.0 : f32 + %one = arith.constant 1.0 : f32 + %tid = gpu.thread_id x + %sg = arith.divui %tid, %c32 : index + %l = arith.remui %tid, %c32 : index + %hi = arith.index_cast %h : i32 to index + %np = arith.index_cast %parts : i32 to index + %last = arith.subi %np, %c1 : index + %p0 = arith.addi %l, %c0 : index + %live0 = arith.cmpi ult, %p0, %np : index + %pc0 = arith.minui %p0, %last : index + %mr0 = memref.load %part[%hi, %pc0, %c128] : memref + %m0 = arith.select %live0, %mr0, %neg : f32 + %p1 = arith.addi %l, %c32 : index + %live1 = arith.cmpi ult, %p1, %np : index + %pc1 = arith.minui %p1, %last : index + %mr1 = memref.load %part[%hi, %pc1, %c128] : memref + %m1 = arith.select %live1, %mr1, %neg : f32 + %p2 = arith.addi %l, %c64 : index + %live2 = arith.cmpi ult, %p2, %np : index + %pc2 = arith.minui %p2, %last : index + %mr2 = memref.load %part[%hi, %pc2, %c128] : memref + %m2 = arith.select %live2, %mr2, %neg : f32 + %p3 = arith.addi %l, %c96 : index + %live3 = arith.cmpi ult, %p3, %np : index + %pc3 = arith.minui %p3, %last : index + %mr3 = memref.load %part[%hi, %pc3, %c128] : memref + %m3 = arith.select %live3, %mr3, %neg : f32 + %m01 = arith.maxnumf %m0, %m1 : f32 + %m23 = arith.maxnumf %m2, %m3 : f32 + %mx = arith.maxnumf %m01, %m23 : f32 + %big = gpu.subgroup_reduce maxnumf %mx : (f32) -> f32 + %dm0 = arith.subf %m0, %big : f32 + %w0 = math.exp %dm0 : f32 + %s0 = memref.load %part[%hi, %pc0, %c129] : memref + %ws0 = arith.mulf %w0, %s0 : f32 + %wv0 = vector.broadcast %w0 : f32 to vector<4xf32> + %dm1 = arith.subf %m1, %big : f32 + %w1 = math.exp %dm1 : f32 + %s1 = memref.load %part[%hi, %pc1, %c129] : memref + %ws1 = arith.mulf %w1, %s1 : f32 + %wv1 = vector.broadcast %w1 : f32 to vector<4xf32> + %dm2 = arith.subf %m2, %big : f32 + %w2 = math.exp %dm2 : f32 + %s2 = memref.load %part[%hi, %pc2, %c129] : memref + %ws2 = arith.mulf %w2, %s2 : f32 + %wv2 = vector.broadcast %w2 : f32 to vector<4xf32> + %dm3 = arith.subf %m3, %big : f32 + %w3 = math.exp %dm3 : f32 + %s3 = memref.load %part[%hi, %pc3, %c129] : memref + %ws3 = arith.mulf %w3, %s3 : f32 + %wv3 = vector.broadcast %w3 : f32 to vector<4xf32> + %t01 = arith.addf %ws0, %ws1 : f32 + %t23 = arith.addf %ws2, %ws3 : f32 + %ts = arith.addf %t01, %t23 : f32 + %total = gpu.subgroup_reduce add %ts : (f32) -> f32 + %inv = arith.divf %one, %total : f32 + %lane0 = arith.cmpi eq, %l, %c0 : index + %sg4 = arith.muli %sg, %c4 : index + %vz4 = arith.constant dense<0.0> : vector<4xf32> + scf.for %n = %c0 to %c128 step %c16 { + %d = arith.addi %n, %sg4 : index + %x0 = vector.load %part[%hi, %pc0, %d] {alignment = 16} : memref, vector<4xf32> + %a0 = vector.fma %x0, %wv0, %vz4 : vector<4xf32> + %x1 = vector.load %part[%hi, %pc1, %d] {alignment = 16} : memref, vector<4xf32> + %a1 = vector.fma %x1, %wv1, %a0 : vector<4xf32> + %x2 = vector.load %part[%hi, %pc2, %d] {alignment = 16} : memref, vector<4xf32> + %a2 = vector.fma %x2, %wv2, %a1 : vector<4xf32> + %x3 = vector.load %part[%hi, %pc3, %d] {alignment = 16} : memref, vector<4xf32> + %a3 = vector.fma %x3, %wv3, %a2 : vector<4xf32> + %e0 = vector.extract %a3[0] : f32 from vector<4xf32> + %r0 = gpu.subgroup_reduce add %e0 : (f32) -> f32 + %o0 = arith.mulf %r0, %inv : f32 + %e1 = vector.extract %a3[1] : f32 from vector<4xf32> + %r1 = gpu.subgroup_reduce add %e1 : (f32) -> f32 + %o1 = arith.mulf %r1, %inv : f32 + %e2 = vector.extract %a3[2] : f32 from vector<4xf32> + %r2 = gpu.subgroup_reduce add %e2 : (f32) -> f32 + %o2 = arith.mulf %r2, %inv : f32 + %e3 = vector.extract %a3[3] : f32 from vector<4xf32> + %r3 = gpu.subgroup_reduce add %e3 : (f32) -> f32 + %o3 = arith.mulf %r3, %inv : f32 + scf.if %lane0 { + %d0 = arith.addi %d, %c0 : index + memref.store %o0, %out[%hi, %d0] : memref + %d1 = arith.addi %d, %c1 : index + memref.store %o1, %out[%hi, %d1] : memref + %d2 = arith.addi %d, %c2 : index + memref.store %o2, %out[%hi, %d2] : memref + %d3 = arith.addi %d, %c3 : index + memref.store %o3, %out[%hi, %d3] : memref + } + } + macro.yield %h : i32 + }; + } + } + return; +} + +/// The scratch space of `split_attention` for positions below `max_seq`, on the CPU. Transfer it to the +/// memory of the other tensors. Each block of positions writes the weighted sum of V for each of its +/// heads, then the largest score and the sum of the weights. +fn split_attention_scratch(max_seq : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> Tensor { + // 20 blocks of 32 positions below position 640, and blocks of 64 positions from there on. + let mut splits = (max_seq + 63) / 64; + if splits < 20 { + splits = 20; + } + return Tensor([kv_heads * ((q_heads / kv_heads + 7) / 8), splits, 8, head_dim + 2]); +} + +/// The parts of `split_attention` for blocks of 32 positions: 4 SIMD groups of 2 heads of Q. +fn split_attention_parts_32(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + let group = q_heads / kv_heads; + let tiles = (group + 7) / 8; + let scale = 1.0 / (head_dim as f32).sqrt(); + spawn on(Topology::Device) { + for gt in 0..kv_heads * tiles across blocks { + for c in 0..(pos + 32) / 32 across blocks { + let mut w = unsafe { Tensor::uninit() }; + let mut top = unsafe { + Tensor::uninit() + }; + let mut sums = unsafe { + Tensor::uninit() + }; + let g = gt / tiles; + let base = g * group + (gt - g * tiles) * 8; + let left = group - (gt - g * tiles) * 8; + for s in 0..4 across subgroups { + let first = base + s * 2; + let mut heads = left - s * 2; + if heads > 2 { + heads = 2; + } + // A head past the last one of the group reads the last one again, and its sums go nowhere. + let mut h0 = first + 0; + if 0 >= heads { + h0 = first + heads - 1; + } + let mut h1 = first + 1; + if 1 >= heads { + h1 = first + heads - 1; + } + for l in 0..32 across lanes(32) { + // The scores of the position of the lane, for each head. A position past `pos` reads row + // `pos`, and its score is -3e38. + let mut t0 = c * 32 + 0 + l; + if t0 > pos { + t0 = pos; + } + let mut dot0_0 : f32 = 0.0; + let mut dot0_1 : f32 = 0.0; + for d in 0..head_dim { + let k0 = k_cache[t0][g][d] as f32; + let q0 = q[h0][d]; + dot0_0 = dot0_0 + q0 * k0; + let q1 = q[h1][d]; + dot0_1 = dot0_1 + q1 * k0; + } + let mut s0_0 : f32 = -3.0e38; + if c * 32 + 0 + l <= pos { + s0_0 = dot0_0 * scale; + } + w[s][0][0 + l] = s0_0; + top[s][0][l] = s0_0; + let mut s0_1 : f32 = -3.0e38; + if c * 32 + 0 + l <= pos { + s0_1 = dot0_1 * scale; + } + w[s][1][0 + l] = s0_1; + top[s][1][l] = s0_1; + } + let big0 = lanes::max(&top[s][0], 32); + let big1 = lanes::max(&top[s][1], 32); + // The weight of each position, as exp(score - the largest score of the block). + for l in 0..32 across lanes(32) { + let e0_0 = (w[s][0][0 + l] - big0).fast_exp(); + w[s][0][0 + l] = e0_0; + sums[s][0][l] = e0_0; + let e0_1 = (w[s][1][0 + l] - big1).fast_exp(); + w[s][1][0 + l] = e0_1; + sums[s][1][l] = e0_1; + } + let total0 = lanes::sum(&sums[s][0], 32); + let total1 = lanes::sum(&sums[s][1], 32); + // The weighted sum of the rows of V. Lane l takes values l, l + 32, l + 64 and l + 96. + for l in 0..32 across lanes(32) { + let mut acc0_0 : f32 = 0.0; + let mut acc0_1 : f32 = 0.0; + let mut acc0_2 : f32 = 0.0; + let mut acc0_3 : f32 = 0.0; + let mut acc1_0 : f32 = 0.0; + let mut acc1_1 : f32 = 0.0; + let mut acc1_2 : f32 = 0.0; + let mut acc1_3 : f32 = 0.0; + // With head_dim below 128, values past it read others again, and their sums go nowhere. + let d0 = (0 + l) % head_dim; + let d1 = (32 + l) % head_dim; + let d2 = (64 + l) % head_dim; + let d3 = (96 + l) % head_dim; + let mut last = pos - c * 32; + if last > 31 { + last = 31; + } + for t in 0..last + 1 { + let row = c * 32 + t; + let v0 = v_cache[row][g][d0] as f32; + let v1 = v_cache[row][g][d1] as f32; + let v2 = v_cache[row][g][d2] as f32; + let v3 = v_cache[row][g][d3] as f32; + let w0 = w[s][0][t]; + acc0_0 = acc0_0 + w0 * v0; + acc0_1 = acc0_1 + w0 * v1; + acc0_2 = acc0_2 + w0 * v2; + acc0_3 = acc0_3 + w0 * v3; + let w1 = w[s][1][t]; + acc1_0 = acc1_0 + w1 * v0; + acc1_1 = acc1_1 + w1 * v1; + acc1_2 = acc1_2 + w1 * v2; + acc1_3 = acc1_3 + w1 * v3; + } + if 0 < heads { + if 0 < head_dim { + part[gt][c][s * 2 + 0][0 + l] = acc0_0; + } + if 32 < head_dim { + part[gt][c][s * 2 + 0][32 + l] = acc0_1; + } + if 64 < head_dim { + part[gt][c][s * 2 + 0][64 + l] = acc0_2; + } + if 96 < head_dim { + part[gt][c][s * 2 + 0][96 + l] = acc0_3; + } + } + if 1 < heads { + if 0 < head_dim { + part[gt][c][s * 2 + 1][0 + l] = acc1_0; + } + if 32 < head_dim { + part[gt][c][s * 2 + 1][32 + l] = acc1_1; + } + if 64 < head_dim { + part[gt][c][s * 2 + 1][64 + l] = acc1_2; + } + if 96 < head_dim { + part[gt][c][s * 2 + 1][96 + l] = acc1_3; + } + } + } + if 0 < heads { + part[gt][c][s * 2 + 0][head_dim] = big0; + part[gt][c][s * 2 + 0][head_dim + 1] = total0; + } + if 1 < heads { + part[gt][c][s * 2 + 1][head_dim] = big1; + part[gt][c][s * 2 + 1][head_dim + 1] = total1; + } + } + } + } + } + return; +} + +/// The parts of `split_attention` for blocks of 64 positions: 2 SIMD groups of 4 heads of Q. +fn split_attention_parts_64(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + let group = q_heads / kv_heads; + let tiles = (group + 7) / 8; + let scale = 1.0 / (head_dim as f32).sqrt(); + spawn on(Topology::Device) { + for gt in 0..kv_heads * tiles across blocks { + for c in 0..(pos + 64) / 64 across blocks { + let mut w = unsafe { Tensor::uninit() }; + let mut top = unsafe { + Tensor::uninit() + }; + let mut sums = unsafe { + Tensor::uninit() + }; + let g = gt / tiles; + let base = g * group + (gt - g * tiles) * 8; + let left = group - (gt - g * tiles) * 8; + for s in 0..2 across subgroups { + let first = base + s * 4; + let mut heads = left - s * 4; + if heads > 4 { + heads = 4; + } + // A head past the last one of the group reads the last one again, and its sums go nowhere. + let mut h0 = first + 0; + if 0 >= heads { + h0 = first + heads - 1; + } + let mut h1 = first + 1; + if 1 >= heads { + h1 = first + heads - 1; + } + let mut h2 = first + 2; + if 2 >= heads { + h2 = first + heads - 1; + } + let mut h3 = first + 3; + if 3 >= heads { + h3 = first + heads - 1; + } + for l in 0..32 across lanes(32) { + // The scores of each of the 2 positions of the lane, for each head. A position past `pos` reads row + // `pos`, and its score is -3e38. + let mut t0 = c * 64 + 0 + l; + if t0 > pos { + t0 = pos; + } + let mut dot0_0 : f32 = 0.0; + let mut dot0_1 : f32 = 0.0; + let mut dot0_2 : f32 = 0.0; + let mut dot0_3 : f32 = 0.0; + let mut t1 = c * 64 + 32 + l; + if t1 > pos { + t1 = pos; + } + let mut dot1_0 : f32 = 0.0; + let mut dot1_1 : f32 = 0.0; + let mut dot1_2 : f32 = 0.0; + let mut dot1_3 : f32 = 0.0; + for d in 0..head_dim { + let k0 = k_cache[t0][g][d] as f32; + let k1 = k_cache[t1][g][d] as f32; + let q0 = q[h0][d]; + dot0_0 = dot0_0 + q0 * k0; + dot1_0 = dot1_0 + q0 * k1; + let q1 = q[h1][d]; + dot0_1 = dot0_1 + q1 * k0; + dot1_1 = dot1_1 + q1 * k1; + let q2 = q[h2][d]; + dot0_2 = dot0_2 + q2 * k0; + dot1_2 = dot1_2 + q2 * k1; + let q3 = q[h3][d]; + dot0_3 = dot0_3 + q3 * k0; + dot1_3 = dot1_3 + q3 * k1; + } + let mut s0_0 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_0 = dot0_0 * scale; + } + w[s][0][0 + l] = s0_0; + let mut s1_0 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_0 = dot1_0 * scale; + } + w[s][0][32 + l] = s1_0; + top[s][0][l] = s0_0.max(s1_0); + let mut s0_1 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_1 = dot0_1 * scale; + } + w[s][1][0 + l] = s0_1; + let mut s1_1 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_1 = dot1_1 * scale; + } + w[s][1][32 + l] = s1_1; + top[s][1][l] = s0_1.max(s1_1); + let mut s0_2 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_2 = dot0_2 * scale; + } + w[s][2][0 + l] = s0_2; + let mut s1_2 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_2 = dot1_2 * scale; + } + w[s][2][32 + l] = s1_2; + top[s][2][l] = s0_2.max(s1_2); + let mut s0_3 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_3 = dot0_3 * scale; + } + w[s][3][0 + l] = s0_3; + let mut s1_3 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_3 = dot1_3 * scale; + } + w[s][3][32 + l] = s1_3; + top[s][3][l] = s0_3.max(s1_3); + } + let big0 = lanes::max(&top[s][0], 32); + let big1 = lanes::max(&top[s][1], 32); + let big2 = lanes::max(&top[s][2], 32); + let big3 = lanes::max(&top[s][3], 32); + // The weight of each position, as exp(score - the largest score of the block). + for l in 0..32 across lanes(32) { + let e0_0 = (w[s][0][0 + l] - big0).fast_exp(); + w[s][0][0 + l] = e0_0; + let e1_0 = (w[s][0][32 + l] - big0).fast_exp(); + w[s][0][32 + l] = e1_0; + sums[s][0][l] = e0_0 + e1_0; + let e0_1 = (w[s][1][0 + l] - big1).fast_exp(); + w[s][1][0 + l] = e0_1; + let e1_1 = (w[s][1][32 + l] - big1).fast_exp(); + w[s][1][32 + l] = e1_1; + sums[s][1][l] = e0_1 + e1_1; + let e0_2 = (w[s][2][0 + l] - big2).fast_exp(); + w[s][2][0 + l] = e0_2; + let e1_2 = (w[s][2][32 + l] - big2).fast_exp(); + w[s][2][32 + l] = e1_2; + sums[s][2][l] = e0_2 + e1_2; + let e0_3 = (w[s][3][0 + l] - big3).fast_exp(); + w[s][3][0 + l] = e0_3; + let e1_3 = (w[s][3][32 + l] - big3).fast_exp(); + w[s][3][32 + l] = e1_3; + sums[s][3][l] = e0_3 + e1_3; + } + let total0 = lanes::sum(&sums[s][0], 32); + let total1 = lanes::sum(&sums[s][1], 32); + let total2 = lanes::sum(&sums[s][2], 32); + let total3 = lanes::sum(&sums[s][3], 32); + // The weighted sum of the rows of V. Lane l takes values l, l + 32, l + 64 and l + 96. + for l in 0..32 across lanes(32) { + let mut acc0_0 : f32 = 0.0; + let mut acc0_1 : f32 = 0.0; + let mut acc0_2 : f32 = 0.0; + let mut acc0_3 : f32 = 0.0; + let mut acc1_0 : f32 = 0.0; + let mut acc1_1 : f32 = 0.0; + let mut acc1_2 : f32 = 0.0; + let mut acc1_3 : f32 = 0.0; + let mut acc2_0 : f32 = 0.0; + let mut acc2_1 : f32 = 0.0; + let mut acc2_2 : f32 = 0.0; + let mut acc2_3 : f32 = 0.0; + let mut acc3_0 : f32 = 0.0; + let mut acc3_1 : f32 = 0.0; + let mut acc3_2 : f32 = 0.0; + let mut acc3_3 : f32 = 0.0; + // With head_dim below 128, values past it read others again, and their sums go nowhere. + let d0 = (0 + l) % head_dim; + let d1 = (32 + l) % head_dim; + let d2 = (64 + l) % head_dim; + let d3 = (96 + l) % head_dim; + let mut last = pos - c * 64; + if last > 63 { + last = 63; + } + for t in 0..last + 1 { + let row = c * 64 + t; + let v0 = v_cache[row][g][d0] as f32; + let v1 = v_cache[row][g][d1] as f32; + let v2 = v_cache[row][g][d2] as f32; + let v3 = v_cache[row][g][d3] as f32; + let w0 = w[s][0][t]; + acc0_0 = acc0_0 + w0 * v0; + acc0_1 = acc0_1 + w0 * v1; + acc0_2 = acc0_2 + w0 * v2; + acc0_3 = acc0_3 + w0 * v3; + let w1 = w[s][1][t]; + acc1_0 = acc1_0 + w1 * v0; + acc1_1 = acc1_1 + w1 * v1; + acc1_2 = acc1_2 + w1 * v2; + acc1_3 = acc1_3 + w1 * v3; + let w2 = w[s][2][t]; + acc2_0 = acc2_0 + w2 * v0; + acc2_1 = acc2_1 + w2 * v1; + acc2_2 = acc2_2 + w2 * v2; + acc2_3 = acc2_3 + w2 * v3; + let w3 = w[s][3][t]; + acc3_0 = acc3_0 + w3 * v0; + acc3_1 = acc3_1 + w3 * v1; + acc3_2 = acc3_2 + w3 * v2; + acc3_3 = acc3_3 + w3 * v3 diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/context/llama/ctx2048.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/context/llama/ctx2048.txt new file mode 100644 index 0000000..90e3bb2 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/context/llama/ctx2048.txt @@ -0,0 +1,138 @@ +//===- model.vx - Qwen app --------------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// One token of a Qwen2 or Qwen3 MoE decoder on the GPU, with the kernels of `std::nn`. `State` +// holds every tensor that a token writes, and the KV cache. It is made once, before the first +// token, so the token loop allocates nothing. +import core::convert; +import core::num; +import std::nn; +import std::vec; +import qwen::attention; +import qwen::products; +import qwen::q6; +import qwen::weights; + +/// The keys and the values of every position so far, for one layer: [max_seq, kv_heads, head_dim]. +/// They are f16, half the memory of f32. The kernels compute in f32, and round only what they +/// store here. +struct Cache { + k : Tensor, + v : Tensor, +} + +/// The tensors of a mixture-of-experts layer: the router's score of each expert, the chosen +/// experts and their weights, and the SwiGLU output of each chosen expert, [experts_per_token, +/// moe_intermediate_size]. +struct Experts { + router_logits : Tensor, + ids : Tensor, + weights : Tensor, + mlp : Tensor, +} + +/// The tensors that a token writes, in GPU memory, and one `Cache` for each layer. `cos` and `sin` +/// are [max_seq, head_dim / 2]. +struct State { + max_seq : i32, + x : Tensor, + xn : Tensor, + q : Tensor, + k : Tensor, + v : Tensor, + q_turned : Tensor, + attended : Tensor, + attention_parts : Tensor, + vec_parts : Tensor, + mlp : Tensor, + experts : Experts, + logits : Tensor, + cos : Tensor, + sin : Tensor, + caches : Vec, +} + +/// The state for up to `max_seq` positions. The angles of RoPE are computed in f64, as in +/// `reference.py`, and rounded to f32 once. +fn new_state(c : &Config, max_seq : i32) -> State { + assert(max_seq > 0 && max_seq <= c.max_positions, "max_seq must be between 1 and the max_positions of the model"); + let half = c.head_dim / 2; + let mut hcos = Tensor([max_seq, half]); + let mut hsin = Tensor([max_seq, half]); + for p in 0..max_seq { + for i in 0..half { + let angle = f64::from(p) / f64::powf(c.rope_theta, f64::from(2 * i) / f64::from(c.head_dim)); + hcos[p][i] = f64::cos(angle) as f32; + hsin[p][i] = f64::sin(angle) as f32; + } + } + // A dense model uses none of the tensors of the experts, so one value each is enough. + let experts = i32::max(c.num_experts, 1); + let chosen = i32::max(c.experts_per_token, 1); + let moe_inter = i32::max(c.moe_intermediate_size, 1); + // The flash attention of a prompt reads the cache in blocks of 64 positions. + let rows = (max_seq + 63) / 64 * 64; + let mut caches = Vec::new(); + for l in 0..c.num_layers { + caches.push(Cache { + k: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + }); + } + return State { + max_seq: max_seq, + x: transfer(Tensor([c.hidden_size]), Memory::HBM), + xn: transfer(Tensor([c.hidden_size]), Memory::HBM), + q: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + k: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + q_turned: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attended: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attention_parts: transfer(split_attention_scratch(max_seq, c.num_q_heads, c.num_kv_heads, c.head_dim), Memory::HBM), + vec_parts: transfer(vec_attention_scratch(c.num_q_heads), Memory::HBM), + mlp: transfer(Tensor([c.intermediate_size]), Memory::HBM), + experts: Experts { + router_logits: transfer(Tensor([experts]), Memory::HBM), + ids: transfer(Tensor([chosen]), Memory::HBM), + weights: transfer(Tensor([chosen]), Memory::HBM), + mlp: transfer(Tensor([chosen, moe_inter]), Memory::HBM), + }, + logits: transfer(Tensor([c.vocab_size]), Memory::HBM), + cos: transfer(hcos, Memory::HBM), + sin: transfer(hsin, Memory::HBM), + caches: caches, + }; +} + +/// y = m x, with the kernel for the dtype of `m`, which has `rows` x `cols` weights. +fn matvec(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U6 { + matvec_q6(y, &m.codes, &m.high, &m.group_scales, x, rows, cols); + } else if m.dtype == U4 { + nn_matvec_q4(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x. +fn matvec_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_matvec_q4_add(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_add(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec_add(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x, for x of [heads, head_dim]. +fn matvec_heads_add(y : diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/context/llama/ctx32768.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/context/llama/ctx32768.txt new file mode 100644 index 0000000..893602a --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/context/llama/ctx32768.txt @@ -0,0 +1,1975 @@ +//===- model.vx - Qwen app --------------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// One token of a Qwen2 or Qwen3 MoE decoder on the GPU, with the kernels of `std::nn`. `State` +// holds every tensor that a token writes, and the KV cache. It is made once, before the first +// token, so the token loop allocates nothing. +import core::convert; +import core::num; +import std::nn; +import std::vec; +import qwen::attention; +import qwen::products; +import qwen::q6; +import qwen::weights; + +/// The keys and the values of every position so far, for one layer: [max_seq, kv_heads, head_dim]. +/// They are f16, half the memory of f32. The kernels compute in f32, and round only what they +/// store here. +struct Cache { + k : Tensor, + v : Tensor, +} + +/// The tensors of a mixture-of-experts layer: the router's score of each expert, the chosen +/// experts and their weights, and the SwiGLU output of each chosen expert, [experts_per_token, +/// moe_intermediate_size]. +struct Experts { + router_logits : Tensor, + ids : Tensor, + weights : Tensor, + mlp : Tensor, +} + +/// The tensors that a token writes, in GPU memory, and one `Cache` for each layer. `cos` and `sin` +/// are [max_seq, head_dim / 2]. +struct State { + max_seq : i32, + x : Tensor, + xn : Tensor, + q : Tensor, + k : Tensor, + v : Tensor, + q_turned : Tensor, + attended : Tensor, + attention_parts : Tensor, + vec_parts : Tensor, + mlp : Tensor, + experts : Experts, + logits : Tensor, + cos : Tensor, + sin : Tensor, + caches : Vec, +} + +/// The state for up to `max_seq` positions. The angles of RoPE are computed in f64, as in +/// `reference.py`, and rounded to f32 once. +fn new_state(c : &Config, max_seq : i32) -> State { + assert(max_seq > 0 && max_seq <= c.max_positions, "max_seq must be between 1 and the max_positions of the model"); + let half = c.head_dim / 2; + let mut hcos = Tensor([max_seq, half]); + let mut hsin = Tensor([max_seq, half]); + for p in 0..max_seq { + for i in 0..half { + let angle = f64::from(p) / f64::powf(c.rope_theta, f64::from(2 * i) / f64::from(c.head_dim)); + hcos[p][i] = f64::cos(angle) as f32; + hsin[p][i] = f64::sin(angle) as f32; + } + } + // A dense model uses none of the tensors of the experts, so one value each is enough. + let experts = i32::max(c.num_experts, 1); + let chosen = i32::max(c.experts_per_token, 1); + let moe_inter = i32::max(c.moe_intermediate_size, 1); + // The flash attention of a prompt reads the cache in blocks of 64 positions. + let rows = (max_seq + 63) / 64 * 64; + let mut caches = Vec::new(); + for l in 0..c.num_layers { + caches.push(Cache { + k: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + }); + } + return State { + max_seq: max_seq, + x: transfer(Tensor([c.hidden_size]), Memory::HBM), + xn: transfer(Tensor([c.hidden_size]), Memory::HBM), + q: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + k: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + q_turned: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attended: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attention_parts: transfer(split_attention_scratch(max_seq, c.num_q_heads, c.num_kv_heads, c.head_dim), Memory::HBM), + vec_parts: transfer(vec_attention_scratch(c.num_q_heads), Memory::HBM), + mlp: transfer(Tensor([c.intermediate_size]), Memory::HBM), + experts: Experts { + router_logits: transfer(Tensor([experts]), Memory::HBM), + ids: transfer(Tensor([chosen]), Memory::HBM), + weights: transfer(Tensor([chosen]), Memory::HBM), + mlp: transfer(Tensor([chosen, moe_inter]), Memory::HBM), + }, + logits: transfer(Tensor([c.vocab_size]), Memory::HBM), + cos: transfer(hcos, Memory::HBM), + sin: transfer(hsin, Memory::HBM), + caches: caches, + }; +} + +/// y = m x, with the kernel for the dtype of `m`, which has `rows` x `cols` weights. +fn matvec(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U6 { + matvec_q6(y, &m.codes, &m.high, &m.group_scales, x, rows, cols); + } else if m.dtype == U4 { + nn_matvec_q4(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x. +fn matvec_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_matvec_q4_add(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_add(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec_add(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x, for x of [heads, head_dim]. +fn matvec_heads_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, heads : i32, head_dim : i32) -> void { + if m.dtype == U4 { + matvec_q4_heads_add_blocks(y, &m.codes, &m.group_scales, x, rows, heads, head_dim); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_heads_add(y, &m.codes, &m.scales, x, rows, heads, head_dim); + } else { + nn_matvec_heads_add(y, &m.bf16, x, rows, heads, head_dim); + } + return; +} + +/// The Q, K and V of x: m x + b, split by heads. +fn qkv(q : &mut Tensor, k : &mut Tensor, v : &mut Tensor, m : &WeightMatrix, b : &Tensor, x : &Tensor, c : &Config) -> void { + if m.dtype == U4 { + qkv_q4_blocks(q, k, v, &m.codes, &m.group_scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } else if m.dtype == F8E4M3 { + nn_qkv_fp8(q, k, v, &m.codes, &m.scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } else { + nn_qkv(q, k, v, &m.bf16, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } + return; +} + +/// The SwiGLU of a dense MLP, for the gate rows and then the up rows of `m`. +fn swiglu(out : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_swiglu_q4(out, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_swiglu_fp8(out, &m.codes, &m.scales, x, rows, cols); + } else { + nn_swiglu(out, &m.bf16, x, rows, cols); + } + return; +} + +/// The mixture of experts of a layer: the router chooses experts_per_token experts and their +/// weights, and x gets the sum of their outputs for xn, each times its weight. +fn add_experts(e : &mut Experts, x : &mut Tensor, xn : &Tensor, layer : &Layer, c : &Config) -> void { + let k = c.experts_per_token; + let inter = c.moe_intermediate_size; + nn_matvec(&mut e.router_logits, &layer.router, xn, c.num_experts, c.hidden_size); + nn_top_k(&mut e.ids, &mut e.weights, &e.router_logits, c.num_experts, k); + let gate_up = &layer.gate_up; + let down = &layer.down; + if gate_up.dtype == U4 { + moe_swiglu_q4_blocks(&mut e.mlp, &gate_up.codes, &gate_up.group_scales, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + moe_down_q4_add_blocks(x, &down.codes, &down.group_scales, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + } else { + assert(gate_up.dtype == BF16, "the experts of a mixture-of-experts model must be bf16 or Q4_0"); + nn_moe_swiglu(&mut e.mlp, &gate_up.bf16, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + nn_moe_down_add(x, &down.bf16, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + } + return; +} + +/// Runs the token in `token` at position `pos` through every layer. The hidden state of the +/// token is then in `s.x`, and its keys and values are in the caches. +fn run_layers(w : &Weights, s : &mut State, token : &Tensor, pos : i32) -> void { + let c = &w.config; + let eps = c.rms_norm_eps as f32; + assert(pos >= 0 && pos < s.max_seq, "the position is past the end of the KV cache"); + nn_embed(&mut s.x, &w.embed, token, c.hidden_size); + let mut l = 0; + for cache in s.caches.iter_mut() { + let layer = &w.layers[l]; + nn_rms_norm(&mut s.xn, &s.x, &layer.attn_norm, c.hidden_size, eps); + qkv(&mut s.q, &mut s.k, &mut s.v, &layer.qkv, &layer.qkv_bias, &s.xn, c); + if c.qk_norm { + norm_rope_and_store(&mut s.q_turned, &mut cache.k, &mut cache.v, &s.q, &s.k, &s.v, &layer.q_norm, &layer.k_norm, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.head_dim, eps); + } else { + rope_and_store(&mut s.q_turned, &mut cache.k, &mut cache.v, &s.q, &s.k, &s.v, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } + if c.head_dim == 128 { + vec_attention(&mut s.attended, &mut s.vec_parts, &s.q_turned, &cache.k, &cache.v, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } else { + split_attention(&mut s.attended, &mut s.attention_parts, &s.q_turned, &cache.k, &cache.v, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } + matvec_heads_add(&mut s.x, &layer.attn_out, &s.attended, c.hidden_size, c.num_q_heads, c.head_dim); + nn_rms_norm(&mut s.xn, &s.x, &layer.mlp_norm, c.hidden_size, eps); + if c.num_experts > 0 { + add_experts(&mut s.experts, &mut s.x, &s.xn, layer, c); + } else { + swiglu(&mut s.mlp, &layer.gate_up, &s.xn, c.intermediate_size, c.hidden_size); + matvec_add(&mut s.x, &layer.down, &s.mlp, c.hidden_size, c.intermediate_size); + } + l = l + 1; + } + return; +} + +/// The logits of the token whose hidden state is in `s.x`, and in `next` the index of the largest +/// one. Both stay in GPU memory. +fn predict(w : &Weights, s : &mut State, next : &mut Tensor) -> void { + let c = &w.config; + nn_rms_norm(&mut s.xn, &s.x, &w.final_norm, c.hidden_size, c.rms_norm_eps as f32); + if c.tied_embeddings { + nn_matvec(&mut s.logits, &w.embed, &s.xn, c.vocab_size, c.hidden_size); + } else { + matvec(&mut s.logits, &w.lm_head, &s.xn, c.vocab_size, c.hidden_size); + } + nn_argmax(next, &s.logits, c.vocab_size); + return; +} +//===- attention.vx - Qwen app ----------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// The attention of one generated token, with the positions split among blocks. This is a copy of +// `nn_attention` and its kernels from `std::nn` on Vx main (vx-lang/Vx#3216), with `split_` in place +// of `nn_` in their names. Vx v0.0.4 has the older `nn_attention`, which has one block for each head +// of Q, so its time grows with the number of positions. Remove this file, and call `nn_attention` +// of `std::nn`, when a Vx release has the new one (#4). +// +// `vec_attention`, for head_dim 128, has the design of llama.cpp's flash attention for one token +// (kernel_flash_attn_ext_vec and kernel_flash_attn_ext_vec_reduce), MIT License, Copyright (c) 2023-2026 +// The ggml authors. scripts/mlir_kernels/decode_attention.py writes its kernels: change that script, not +// the MLIR. +import core::num; +import std::nn; + +/// Attention of the token at position `pos` over rows 0 to `pos` of the KV cache, with a softmax +/// of the scores q . k / sqrt(head_dim). `part` is scratch space from `split_attention_scratch`. +/// +/// The blocks of the first kernel split the positions, 32 to a block below position 640 and 64 from +/// there on. A block serves the 8 heads of Q that share a head of K and V, so it reads each row of +/// the cache once for all 8. A second kernel merges the parts of the blocks for each head. +fn split_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_heads % kv_heads == 0, "split_attention: q_heads must be a multiple of kv_heads"); + assert(head_dim % 32 == 0 && head_dim <= 128, "split_attention: head_dim must be a multiple of 32, and at most 128"); + let mut n_pos = 32; + if pos >= 640 { + n_pos = 64; + } + assert(part.extent(0) >= kv_heads * ((q_heads / kv_heads + 7) / 8) && part.extent(1) >= (pos + n_pos) / n_pos && part.extent(2) >= 8 && part.extent(3) >= head_dim + 2, "split_attention: `part` is too small for this position. Make it with split_attention_scratch"); + if n_pos == 32 { + split_attention_parts_32(part, q, k_cache, v_cache, pos, q_heads, kv_heads, head_dim); + } else { + split_attention_parts_64(part, q, k_cache, v_cache, pos, q_heads, kv_heads, head_dim); + } + split_attention_merge(out, part, pos, n_pos, q_heads, kv_heads, head_dim); + return; +} + +/// Attention of the token at position `pos`, as `split_attention`, for head_dim 128, with the kernels of +/// llama.cpp's flash attention for one token. `vec_attention_parts` splits the blocks of 32 positions among +/// `nwg` SIMD groups for each head of Q: 32 of them, or 64 when each of 32 would have more than 2 blocks. +/// (llama.cpp goes on to 4 SIMD groups of 32 a block, but 128 parts are no faster here: their merge costs what +/// they save.) `vec_attention_merge` then merges the parts. `part` is scratch space from +/// `vec_attention_scratch`. +fn vec_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_heads % kv_heads == 0 && head_dim == 128, "vec_attention: q_heads must be a multiple of kv_heads, and head_dim 128"); + assert(part.extent(0) >= q_heads && part.extent(1) >= 128 && part.extent(2) == 132, "vec_attention: `part` is too small. Make it with vec_attention_scratch"); + let mut nwg = 32; + if 2 * nwg * 32 < pos + 1 { + nwg = nwg * 2; + } + vec_attention_parts(part, q, k_cache, v_cache, pos, q_heads, q_heads / kv_heads, nwg, 1.0 / (head_dim as f32).sqrt()); + vec_attention_merge(out, part, nwg, q_heads); + return; +} + +/// The scratch space of `vec_attention`, on the CPU: up to 128 parts for each head of Q, each the sum of V +/// (128 values), the largest score, and the sum of the weights. A part has 132 values, so that each starts +/// at a multiple of 16 bytes. +fn vec_attention_scratch(q_heads : i32) -> Tensor { + return Tensor([q_heads, 128, 132]); +} + +/// The parts of `vec_attention`, as llama.cpp's kernel_flash_attn_ext_vec. Block (h, w) is a SIMD group for +/// query head h. It does the blocks of 32 positions w, w + nwg, w + 2 nwg, ... up to `pos`, and writes +/// part[h][w]. Lane l owns values 4 l to 4 l + 3 of the head, so that the 32 lanes read a row of K or V in +/// one 256-byte load. For each row, the lanes add up their parts of q . k; then each lane keeps the score +/// of one row, and the lanes take the weights of the rows from each other for the sum of V. A part is the +/// sum of V, not divided, then the largest score and the sum of the weights. +fn vec_attention_parts(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, group : i32, nwg : i32, scale : f32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for w in 0..nwg across blocks { + let g = h / group; + let _d = mlir!( threads : 32, inputs : (%part = part : memref, %q = q : memref, %k3 = k_cache : memref, %v3 = v_cache : memref, %pos = pos : i32, %nwg = nwg : i32, %scale = scale : f32, %h = h : i32, %w = w : i32, %g = g : i32), returns : i32, dialects : ["arith", "memref", "scf", "gpu", "vector", "math"], ensures : [reads_only(q), reads_only(k_cache), reads_only(v_cache), writes_only(part[h][w])]) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %c4 = arith.constant 4 : index + %c32 = arith.constant 32 : index + %c128 = arith.constant 128 : index + %c129 = arith.constant 129 : index + %c32i = arith.constant 32 : i32 + %neg = arith.constant -3.0e38 : f32 + %zero = arith.constant 0.0 : f32 + %vz4 = arith.constant dense<0.0> : vector<4xf32> + %l = gpu.thread_id x + %l4 = arith.muli %l, %c4 : index + %hi = arith.index_cast %h : i32 to index + %wi = arith.index_cast %w : i32 to index + %gi = arith.index_cast %g : i32 to index + %posi = arith.index_cast %pos : i32 to index + %nwgi = arith.index_cast %nwg : i32 to index + %g128 = arith.muli %gi, %c128 : index + %kd = arith.addi %g128, %l4 : index + %P = memref.dim %k3, %c0 : memref + %KH = memref.dim %k3, %c1 : memref + %Wd = arith.muli %KH, %c128 : index + %k = memref.reinterpret_cast %k3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to memref> + %v = memref.reinterpret_cast %v3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to memref> + %qv = vector.load %q[%hi, %l4] {alignment = 16} : memref, vector<4xf32> + %scv = vector.broadcast %scale : f32 to vector<4xf32> + %qs = arith.mulf %qv, %scv : vector<4xf32> + %nkv = arith.addi %posi, %c32 : index + %chunks = arith.divui %nkv, %c32 : index + %st:3 = scf.for %ic = %wi to %chunks step %nwgi iter_args(%M = %neg, %S = %zero, %o = %vz4) -> (f32, f32, vector<4xf32>) { + %r0 = arith.muli %ic, %c32 : index + %my = scf.for %cc = %c0 to %c32 step %c1 iter_args(%m = %neg) -> (f32) { + %row = arith.addi %r0, %cc : index + %rowc = arith.minui %row, %posi : index + %kh = vector.load %k[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> + %kf = arith.extf %kh : vector<4xf16> to vector<4xf32> + %pr = arith.mulf %kf, %qs : vector<4xf32> + %pl = vector.reduction , %pr : vector<4xf32> into f32 + %sc = gpu.subgroup_reduce add %pl : (f32) -> f32 + %live = arith.cmpi ule, %row, %posi : index + %scm = arith.select %live, %sc, %neg : f32 + %mine = arith.cmpi eq, %cc, %l : index + %m2 = arith.select %mine, %scm, %m : f32 + scf.yield %m2 : f32 + } + %bm = gpu.subgroup_reduce maxnumf %my : (f32) -> f32 + %Mn = arith.maxnumf %M, %bm : f32 + %dm = arith.subf %M, %Mn : f32 + %ms = math.exp %dm : f32 + %dp = arith.subf %my, %Mn : f32 + %p = math.exp %dp : f32 + %bs = gpu.subgroup_reduce add %p : (f32) -> f32 + %Ss = arith.mulf %S, %ms : f32 + %Sn = arith.addf %Ss, %bs : f32 + %msv = vector.broadcast %ms : f32 to vector<4xf32> + %o1 = arith.mulf %o, %msv : vector<4xf32> + %o2 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%oa = %o1) -> (vector<4xf32>) { + %row = arith.addi %r0, %cc : index + %rowc = arith.minui %row, %posi : index + %vh = vector.load %v[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> + %vf = arith.extf %vh : vector<4xf16> to vector<4xf32> + %cci = arith.index_cast %cc : index to i32 + %pc, %pv = gpu.shuffle idx %p, %cci, %c32i : f32 + %pcv = vector.broadcast %pc : f32 to vector<4xf32> + %on = vector.fma %vf, %pcv, %oa : vector<4xf32> + scf.yield %on : vector<4xf32> + } + scf.yield %Mn, %Sn, %o2 : f32, f32, vector<4xf32> + } + vector.store %st#2, %part[%hi, %wi, %l4] : memref, vector<4xf32> + %lane0 = arith.cmpi eq, %l, %c0 : index + scf.if %lane0 { + memref.store %st#0, %part[%hi, %wi, %c128] : memref + memref.store %st#1, %part[%hi, %wi, %c129] : memref + } + macro.yield %h : i32 + }; + } + } + } + return; +} + +/// Merges the first `parts` parts of `vec_attention_parts` for each head of Q, as llama.cpp's +/// kernel_flash_attn_ext_vec_reduce. A block of 4 SIMD groups does one head: each lane weighs up to 4 parts, +/// and the SIMD groups add them up for 4 values of the head at a time. +fn vec_attention_merge(out : &mut Tensor, part : &Tensor, parts : i32, q_heads : i32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + let _d = mlir!( threads : 128, inputs : (%out = out : memref, %part = part : memref, %parts = parts : i32, %h = h : i32), returns : i32, dialects : ["arith", "memref", "scf", "gpu", "vector", "math"], ensures : [reads_only(part), writes_only(out[h])]) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %c2 = arith.constant 2 : index + %c3 = arith.constant 3 : index + %c4 = arith.constant 4 : index + %c16 = arith.constant 16 : index + %c32 = arith.constant 32 : index + %c64 = arith.constant 64 : index + %c96 = arith.constant 96 : index + %c128 = arith.constant 128 : index + %c129 = arith.constant 129 : index + %neg = arith.constant -3.0e38 : f32 + %zero = arith.constant 0.0 : f32 + %one = arith.constant 1.0 : f32 + %tid = gpu.thread_id x + %sg = arith.divui %tid, %c32 : index + %l = arith.remui %tid, %c32 : index + %hi = arith.index_cast %h : i32 to index + %np = arith.index_cast %parts : i32 to index + %last = arith.subi %np, %c1 : index + %p0 = arith.addi %l, %c0 : index + %live0 = arith.cmpi ult, %p0, %np : index + %pc0 = arith.minui %p0, %last : index + %mr0 = memref.load %part[%hi, %pc0, %c128] : memref + %m0 = arith.select %live0, %mr0, %neg : f32 + %p1 = arith.addi %l, %c32 : index + %live1 = arith.cmpi ult, %p1, %np : index + %pc1 = arith.minui %p1, %last : index + %mr1 = memref.load %part[%hi, %pc1, %c128] : memref + %m1 = arith.select %live1, %mr1, %neg : f32 + %p2 = arith.addi %l, %c64 : index + %live2 = arith.cmpi ult, %p2, %np : index + %pc2 = arith.minui %p2, %last : index + %mr2 = memref.load %part[%hi, %pc2, %c128] : memref + %m2 = arith.select %live2, %mr2, %neg : f32 + %p3 = arith.addi %l, %c96 : index + %live3 = arith.cmpi ult, %p3, %np : index + %pc3 = arith.minui %p3, %last : index + %mr3 = memref.load %part[%hi, %pc3, %c128] : memref + %m3 = arith.select %live3, %mr3, %neg : f32 + %m01 = arith.maxnumf %m0, %m1 : f32 + %m23 = arith.maxnumf %m2, %m3 : f32 + %mx = arith.maxnumf %m01, %m23 : f32 + %big = gpu.subgroup_reduce maxnumf %mx : (f32) -> f32 + %dm0 = arith.subf %m0, %big : f32 + %w0 = math.exp %dm0 : f32 + %s0 = memref.load %part[%hi, %pc0, %c129] : memref + %ws0 = arith.mulf %w0, %s0 : f32 + %wv0 = vector.broadcast %w0 : f32 to vector<4xf32> + %dm1 = arith.subf %m1, %big : f32 + %w1 = math.exp %dm1 : f32 + %s1 = memref.load %part[%hi, %pc1, %c129] : memref + %ws1 = arith.mulf %w1, %s1 : f32 + %wv1 = vector.broadcast %w1 : f32 to vector<4xf32> + %dm2 = arith.subf %m2, %big : f32 + %w2 = math.exp %dm2 : f32 + %s2 = memref.load %part[%hi, %pc2, %c129] : memref + %ws2 = arith.mulf %w2, %s2 : f32 + %wv2 = vector.broadcast %w2 : f32 to vector<4xf32> + %dm3 = arith.subf %m3, %big : f32 + %w3 = math.exp %dm3 : f32 + %s3 = memref.load %part[%hi, %pc3, %c129] : memref + %ws3 = arith.mulf %w3, %s3 : f32 + %wv3 = vector.broadcast %w3 : f32 to vector<4xf32> + %t01 = arith.addf %ws0, %ws1 : f32 + %t23 = arith.addf %ws2, %ws3 : f32 + %ts = arith.addf %t01, %t23 : f32 + %total = gpu.subgroup_reduce add %ts : (f32) -> f32 + %inv = arith.divf %one, %total : f32 + %lane0 = arith.cmpi eq, %l, %c0 : index + %sg4 = arith.muli %sg, %c4 : index + %vz4 = arith.constant dense<0.0> : vector<4xf32> + scf.for %n = %c0 to %c128 step %c16 { + %d = arith.addi %n, %sg4 : index + %x0 = vector.load %part[%hi, %pc0, %d] {alignment = 16} : memref, vector<4xf32> + %a0 = vector.fma %x0, %wv0, %vz4 : vector<4xf32> + %x1 = vector.load %part[%hi, %pc1, %d] {alignment = 16} : memref, vector<4xf32> + %a1 = vector.fma %x1, %wv1, %a0 : vector<4xf32> + %x2 = vector.load %part[%hi, %pc2, %d] {alignment = 16} : memref, vector<4xf32> + %a2 = vector.fma %x2, %wv2, %a1 : vector<4xf32> + %x3 = vector.load %part[%hi, %pc3, %d] {alignment = 16} : memref, vector<4xf32> + %a3 = vector.fma %x3, %wv3, %a2 : vector<4xf32> + %e0 = vector.extract %a3[0] : f32 from vector<4xf32> + %r0 = gpu.subgroup_reduce add %e0 : (f32) -> f32 + %o0 = arith.mulf %r0, %inv : f32 + %e1 = vector.extract %a3[1] : f32 from vector<4xf32> + %r1 = gpu.subgroup_reduce add %e1 : (f32) -> f32 + %o1 = arith.mulf %r1, %inv : f32 + %e2 = vector.extract %a3[2] : f32 from vector<4xf32> + %r2 = gpu.subgroup_reduce add %e2 : (f32) -> f32 + %o2 = arith.mulf %r2, %inv : f32 + %e3 = vector.extract %a3[3] : f32 from vector<4xf32> + %r3 = gpu.subgroup_reduce add %e3 : (f32) -> f32 + %o3 = arith.mulf %r3, %inv : f32 + scf.if %lane0 { + %d0 = arith.addi %d, %c0 : index + memref.store %o0, %out[%hi, %d0] : memref + %d1 = arith.addi %d, %c1 : index + memref.store %o1, %out[%hi, %d1] : memref + %d2 = arith.addi %d, %c2 : index + memref.store %o2, %out[%hi, %d2] : memref + %d3 = arith.addi %d, %c3 : index + memref.store %o3, %out[%hi, %d3] : memref + } + } + macro.yield %h : i32 + }; + } + } + return; +} + +/// The scratch space of `split_attention` for positions below `max_seq`, on the CPU. Transfer it to the +/// memory of the other tensors. Each block of positions writes the weighted sum of V for each of its +/// heads, then the largest score and the sum of the weights. +fn split_attention_scratch(max_seq : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> Tensor { + // 20 blocks of 32 positions below position 640, and blocks of 64 positions from there on. + let mut splits = (max_seq + 63) / 64; + if splits < 20 { + splits = 20; + } + return Tensor([kv_heads * ((q_heads / kv_heads + 7) / 8), splits, 8, head_dim + 2]); +} + +/// The parts of `split_attention` for blocks of 32 positions: 4 SIMD groups of 2 heads of Q. +fn split_attention_parts_32(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + let group = q_heads / kv_heads; + let tiles = (group + 7) / 8; + let scale = 1.0 / (head_dim as f32).sqrt(); + spawn on(Topology::Device) { + for gt in 0..kv_heads * tiles across blocks { + for c in 0..(pos + 32) / 32 across blocks { + let mut w = unsafe { Tensor::uninit() }; + let mut top = unsafe { + Tensor::uninit() + }; + let mut sums = unsafe { + Tensor::uninit() + }; + let g = gt / tiles; + let base = g * group + (gt - g * tiles) * 8; + let left = group - (gt - g * tiles) * 8; + for s in 0..4 across subgroups { + let first = base + s * 2; + let mut heads = left - s * 2; + if heads > 2 { + heads = 2; + } + // A head past the last one of the group reads the last one again, and its sums go nowhere. + let mut h0 = first + 0; + if 0 >= heads { + h0 = first + heads - 1; + } + let mut h1 = first + 1; + if 1 >= heads { + h1 = first + heads - 1; + } + for l in 0..32 across lanes(32) { + // The scores of the position of the lane, for each head. A position past `pos` reads row + // `pos`, and its score is -3e38. + let mut t0 = c * 32 + 0 + l; + if t0 > pos { + t0 = pos; + } + let mut dot0_0 : f32 = 0.0; + let mut dot0_1 : f32 = 0.0; + for d in 0..head_dim { + let k0 = k_cache[t0][g][d] as f32; + let q0 = q[h0][d]; + dot0_0 = dot0_0 + q0 * k0; + let q1 = q[h1][d]; + dot0_1 = dot0_1 + q1 * k0; + } + let mut s0_0 : f32 = -3.0e38; + if c * 32 + 0 + l <= pos { + s0_0 = dot0_0 * scale; + } + w[s][0][0 + l] = s0_0; + top[s][0][l] = s0_0; + let mut s0_1 : f32 = -3.0e38; + if c * 32 + 0 + l <= pos { + s0_1 = dot0_1 * scale; + } + w[s][1][0 + l] = s0_1; + top[s][1][l] = s0_1; + } + let big0 = lanes::max(&top[s][0], 32); + let big1 = lanes::max(&top[s][1], 32); + // The weight of each position, as exp(score - the largest score of the block). + for l in 0..32 across lanes(32) { + let e0_0 = (w[s][0][0 + l] - big0).fast_exp(); + w[s][0][0 + l] = e0_0; + sums[s][0][l] = e0_0; + let e0_1 = (w[s][1][0 + l] - big1).fast_exp(); + w[s][1][0 + l] = e0_1; + sums[s][1][l] = e0_1; + } + let total0 = lanes::sum(&sums[s][0], 32); + let total1 = lanes::sum(&sums[s][1], 32); + // The weighted sum of the rows of V. Lane l takes values l, l + 32, l + 64 and l + 96. + for l in 0..32 across lanes(32) { + let mut acc0_0 : f32 = 0.0; + let mut acc0_1 : f32 = 0.0; + let mut acc0_2 : f32 = 0.0; + let mut acc0_3 : f32 = 0.0; + let mut acc1_0 : f32 = 0.0; + let mut acc1_1 : f32 = 0.0; + let mut acc1_2 : f32 = 0.0; + let mut acc1_3 : f32 = 0.0; + // With head_dim below 128, values past it read others again, and their sums go nowhere. + let d0 = (0 + l) % head_dim; + let d1 = (32 + l) % head_dim; + let d2 = (64 + l) % head_dim; + let d3 = (96 + l) % head_dim; + let mut last = pos - c * 32; + if last > 31 { + last = 31; + } + for t in 0..last + 1 { + let row = c * 32 + t; + let v0 = v_cache[row][g][d0] as f32; + let v1 = v_cache[row][g][d1] as f32; + let v2 = v_cache[row][g][d2] as f32; + let v3 = v_cache[row][g][d3] as f32; + let w0 = w[s][0][t]; + acc0_0 = acc0_0 + w0 * v0; + acc0_1 = acc0_1 + w0 * v1; + acc0_2 = acc0_2 + w0 * v2; + acc0_3 = acc0_3 + w0 * v3; + let w1 = w[s][1][t]; + acc1_0 = acc1_0 + w1 * v0; + acc1_1 = acc1_1 + w1 * v1; + acc1_2 = acc1_2 + w1 * v2; + acc1_3 = acc1_3 + w1 * v3; + } + if 0 < heads { + if 0 < head_dim { + part[gt][c][s * 2 + 0][0 + l] = acc0_0; + } + if 32 < head_dim { + part[gt][c][s * 2 + 0][32 + l] = acc0_1; + } + if 64 < head_dim { + part[gt][c][s * 2 + 0][64 + l] = acc0_2; + } + if 96 < head_dim { + part[gt][c][s * 2 + 0][96 + l] = acc0_3; + } + } + if 1 < heads { + if 0 < head_dim { + part[gt][c][s * 2 + 1][0 + l] = acc1_0; + } + if 32 < head_dim { + part[gt][c][s * 2 + 1][32 + l] = acc1_1; + } + if 64 < head_dim { + part[gt][c][s * 2 + 1][64 + l] = acc1_2; + } + if 96 < head_dim { + part[gt][c][s * 2 + 1][96 + l] = acc1_3; + } + } + } + if 0 < heads { + part[gt][c][s * 2 + 0][head_dim] = big0; + part[gt][c][s * 2 + 0][head_dim + 1] = total0; + } + if 1 < heads { + part[gt][c][s * 2 + 1][head_dim] = big1; + part[gt][c][s * 2 + 1][head_dim + 1] = total1; + } + } + } + } + } + return; +} + +/// The parts of `split_attention` for blocks of 64 positions: 2 SIMD groups of 4 heads of Q. +fn split_attention_parts_64(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + let group = q_heads / kv_heads; + let tiles = (group + 7) / 8; + let scale = 1.0 / (head_dim as f32).sqrt(); + spawn on(Topology::Device) { + for gt in 0..kv_heads * tiles across blocks { + for c in 0..(pos + 64) / 64 across blocks { + let mut w = unsafe { Tensor::uninit() }; + let mut top = unsafe { + Tensor::uninit() + }; + let mut sums = unsafe { + Tensor::uninit() + }; + let g = gt / tiles; + let base = g * group + (gt - g * tiles) * 8; + let left = group - (gt - g * tiles) * 8; + for s in 0..2 across subgroups { + let first = base + s * 4; + let mut heads = left - s * 4; + if heads > 4 { + heads = 4; + } + // A head past the last one of the group reads the last one again, and its sums go nowhere. + let mut h0 = first + 0; + if 0 >= heads { + h0 = first + heads - 1; + } + let mut h1 = first + 1; + if 1 >= heads { + h1 = first + heads - 1; + } + let mut h2 = first + 2; + if 2 >= heads { + h2 = first + heads - 1; + } + let mut h3 = first + 3; + if 3 >= heads { + h3 = first + heads - 1; + } + for l in 0..32 across lanes(32) { + // The scores of each of the 2 positions of the lane, for each head. A position past `pos` reads row + // `pos`, and its score is -3e38. + let mut t0 = c * 64 + 0 + l; + if t0 > pos { + t0 = pos; + } + let mut dot0_0 : f32 = 0.0; + let mut dot0_1 : f32 = 0.0; + let mut dot0_2 : f32 = 0.0; + let mut dot0_3 : f32 = 0.0; + let mut t1 = c * 64 + 32 + l; + if t1 > pos { + t1 = pos; + } + let mut dot1_0 : f32 = 0.0; + let mut dot1_1 : f32 = 0.0; + let mut dot1_2 : f32 = 0.0; + let mut dot1_3 : f32 = 0.0; + for d in 0..head_dim { + let k0 = k_cache[t0][g][d] as f32; + let k1 = k_cache[t1][g][d] as f32; + let q0 = q[h0][d]; + dot0_0 = dot0_0 + q0 * k0; + dot1_0 = dot1_0 + q0 * k1; + let q1 = q[h1][d]; + dot0_1 = dot0_1 + q1 * k0; + dot1_1 = dot1_1 + q1 * k1; + let q2 = q[h2][d]; + dot0_2 = dot0_2 + q2 * k0; + dot1_2 = dot1_2 + q2 * k1; + let q3 = q[h3][d]; + dot0_3 = dot0_3 + q3 * k0; + dot1_3 = dot1_3 + q3 * k1; + } + let mut s0_0 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_0 = dot0_0 * scale; + } + w[s][0][0 + l] = s0_0; + let mut s1_0 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_0 = dot1_0 * scale; + } + w[s][0][32 + l] = s1_0; + top[s][0][l] = s0_0.max(s1_0); + let mut s0_1 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_1 = dot0_1 * scale; + } + w[s][1][0 + l] = s0_1; + let mut s1_1 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_1 = dot1_1 * scale; + } + w[s][1][32 + l] = s1_1; + top[s][1][l] = s0_1.max(s1_1); + let mut s0_2 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_2 = dot0_2 * scale; + } + w[s][2][0 + l] = s0_2; + let mut s1_2 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_2 = dot1_2 * scale; + } + w[s][2][32 + l] = s1_2; + top[s][2][l] = s0_2.max(s1_2); + let mut s0_3 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_3 = dot0_3 * scale; + } + w[s][3][0 + l] = s0_3; + let mut s1_3 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_3 = dot1_3 * scale; + } + w[s][3][32 + l] = s1_3; + top[s][3][l] = s0_3.max(s1_3); + } + let big0 = lanes::max(&top[s][0], 32); + let big1 = lanes::max(&top[s][1], 32); + let big2 = lanes::max(&top[s][2], 32); + let big3 = lanes::max(&top[s][3], 32); + // The weight of each position, as exp(score - the largest score of the block). + for l in 0..32 across lanes(32) { + let e0_0 = (w[s][0][0 + l] - big0).fast_exp(); + w[s][0][0 + l] = e0_0; + let e1_0 = (w[s][0][32 + l] - big0).fast_exp(); + w[s][0][32 + l] = e1_0; + sums[s][0][l] = e0_0 + e1_0; + let e0_1 = (w[s][1][0 + l] - big1).fast_exp(); + w[s][1][0 + l] = e0_1; + let e1_1 = (w[s][1][32 + l] - big1).fast_exp(); + w[s][1][32 + l] = e1_1; + sums[s][1][l] = e0_1 + e1_1; + let e0_2 = (w[s][2][0 + l] - big2).fast_exp(); + w[s][2][0 + l] = e0_2; + let e1_2 = (w[s][2][32 + l] - big2).fast_exp(); + w[s][2][32 + l] = e1_2; + sums[s][2][l] = e0_2 + e1_2; + let e0_3 = (w[s][3][0 + l] - big3).fast_exp(); + w[s][3][0 + l] = e0_3; + let e1_3 = (w[s][3][32 + l] - big3).fast_exp(); + w[s][3][32 + l] = e1_3; + sums[s][3][l] = e0_3 + e1_3; + } + let total0 = lanes::sum(&sums[s][0], 32); + let total1 = lanes::sum(&sums[s][1], 32); + let total2 = lanes::sum(&sums[s][2], 32); + let total3 = lanes::sum(&sums[s][3], 32); + // The weighted sum of the rows of V. Lane l takes values l, l + 32, l + 64 and l + 96. + for l in 0..32 across lanes(32) { + let mut acc0_0 : f32 = 0.0; + let mut acc0_1 : f32 = 0.0; + let mut acc0_2 : f32 = 0.0; + let mut acc0_3 : f32 = 0.0; + let mut acc1_0 : f32 = 0.0; + let mut acc1_1 : f32 = 0.0; + let mut acc1_2 : f32 = 0.0; + let mut acc1_3 : f32 = 0.0; + let mut acc2_0 : f32 = 0.0; + let mut acc2_1 : f32 = 0.0; + let mut acc2_2 : f32 = 0.0; + let mut acc2_3 : f32 = 0.0; + let mut acc3_0 : f32 = 0.0; + let mut acc3_1 : f32 = 0.0; + let mut acc3_2 : f32 = 0.0; + let mut acc3_3 : f32 = 0.0; + // With head_dim below 128, values past it read others again, and their sums go nowhere. + let d0 = (0 + l) % head_dim; + let d1 = (32 + l) % head_dim; + let d2 = (64 + l) % head_dim; + let d3 = (96 + l) % head_dim; + let mut last = pos - c * 64; + if last > 63 { + last = 63; + } + for t in 0..last + 1 { + let row = c * 64 + t; + let v0 = v_cache[row][g][d0] as f32; + let v1 = v_cache[row][g][d1] as f32; + let v2 = v_cache[row][g][d2] as f32; + let v3 = v_cache[row][g][d3] as f32; + let w0 = w[s][0][t]; + acc0_0 = acc0_0 + w0 * v0; + acc0_1 = acc0_1 + w0 * v1; + acc0_2 = acc0_2 + w0 * v2; + acc0_3 = acc0_3 + w0 * v3; + let w1 = w[s][1][t]; + acc1_0 = acc1_0 + w1 * v0; + acc1_1 = acc1_1 + w1 * v1; + acc1_2 = acc1_2 + w1 * v2; + acc1_3 = acc1_3 + w1 * v3; + let w2 = w[s][2][t]; + acc2_0 = acc2_0 + w2 * v0; + acc2_1 = acc2_1 + w2 * v1; + acc2_2 = acc2_2 + w2 * v2; + acc2_3 = acc2_3 + w2 * v3; + let w3 = w[s][3][t]; + acc3_0 = acc3_0 + w3 * v0; + acc3_1 = acc3_1 + w3 * v1; + acc3_2 = acc3_2 + w3 * v2; + acc3_3 = acc3_3 + w3 * v3; + } + if 0 < heads { + if 0 < head_dim { + part[gt][c][s * 4 + 0][0 + l] = acc0_0; + } + if 32 < head_dim { + part[gt][c][s * 4 + 0][32 + l] = acc0_1; + } + if 64 < head_dim { + part[gt][c][s * 4 + 0][64 + l] = acc0_2; + } + if 96 < head_dim { + part[gt][c][s * 4 + 0][96 + l] = acc0_3; + } + } + if 1 < heads { + if 0 < head_dim { + part[gt][c][s * 4 + 1][0 + l] = acc1_0; + } + if 32 < head_dim { + part[gt][c][s * 4 + 1][32 + l] = acc1_1; + } + if 64 < head_dim { + part[gt][c][s * 4 + 1][64 + l] = acc1_2; + } + if 96 < head_dim { + part[gt][c][s * 4 + 1][96 + l] = acc1_3; + } + } + if 2 < heads { + if 0 < head_dim { + part[gt][c][s * 4 + 2][0 + l] = acc2_0; + } + if 32 < head_dim { + part[gt][c][s * 4 + 2][32 + l] = acc2_1; + } + if 64 < head_dim { + part[gt][c][s * 4 + 2][64 + l] = acc2_2; + } + if 96 < head_dim { + part[gt][c][s * 4 + 2][96 + l] = acc2_3; + } + } + if 3 < heads { + if 0 < head_dim { + part[gt][c][s * 4 + 3][0 + l] = acc3_0; + } + if 32 < head_dim { + part[gt][c][s * 4 + 3][32 + l] = acc3_1; + } + if 64 < head_dim { + part[gt][c][s * 4 + 3][64 + l] = acc3_2; + } + if 96 < head_dim { + part[gt][c][s * 4 + 3][96 + l] = acc3_3; + } + } + } + if 0 < heads { + part[gt][c][s * 4 + 0][head_dim] = big0; + part[gt][c][s * 4 + 0][head_dim + 1] = total0; + } + if 1 < heads { + part[gt][c][s * 4 + 1][head_dim] = big1; + part[gt][c][s * 4 + 1][head_dim + 1] = total1; + } + if 2 < heads { + part[gt][c][s * 4 + 2][head_dim] = big2; + part[gt][c][s * 4 + 2][head_dim + 1] = total2; + } + if 3 < heads { + part[gt][c][s * 4 + 3][head_dim] = big3; + part[gt][c][s * 4 + 3][head_dim + 1] = total3; + } + } + } + } + } + return; +} + +/// Merges the parts of `split_attention` of blocks of `n_pos` positions. A block does 32 values of one +/// head of Q, a value for each lane. +fn split_attention_merge(out : &mut Tensor, part : &Tensor, pos : i32, n_pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + let group = q_heads / kv_heads; + let tiles = (group + 7) / 8; + let splits = (pos + n_pos) / n_pos; + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for dq in 0..head_dim / 32 across blocks { + let mut top = unsafe { + Tensor::uninit() + }; + let g = h / group; + let tile = (h - g * group) / 8; + let gt = g * tiles + tile; + let at = h - g * group - tile * 8; + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let mut m : f32 = -3.0e38; + let mut c = l; + while c < splits { + m = m.max(part[gt][c][at][head_dim]); + c = c + 32; + } + top[s][0][l] = m; + } + let big = lanes::max(&top[s][0], 32); + for l in 0..32 across lanes(32) { + let d = dq * 32 + l; + let mut total : f32 = 0.0; + let mut acc : f32 = 0.0; + for c in 0..splits { + let w = (part[gt][c][at][head_dim] - big).fast_exp(); + total = total + w * part[gt][c][at][head_dim + 1]; + acc = acc + w * part[gt][c][at][d]; + } + out[h][d] = acc / total; + } + } + } + } + } + return; +} + +// The kernels that store the K and V of a generated token: copies of `nn_rope_and_store` and +// `nn_norm_rope_and_store` of `std::nn`, with a KV cache of f16. They compute in f32 and round +// what they store. + +/// RoPE for the token at position `pos`, and its K and V into the KV cache. Writes each head of +/// q, turned, to `q_out`, and each head of k, turned, and of v to row `pos` of the cache. Value i +/// of a head pairs with value i + head_dim / 2, as in the Llama and Qwen models of Hugging Face. +/// Both turn by the angle whose cosine and sine are cos[pos][i] and sin[pos][i]. +fn rope_and_store(q_out : &mut Tensor, k_cache : &mut Tensor, v_cache : &mut Tensor, q : &Tensor, k : &Tensor, v : &Tensor, cos : &Tensor, sin : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + let half = head_dim / 2; + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(q_out.extent(0), q_out.extent(1), q_heads, head_dim); + nn_check_heads(k.extent(0), k.extent(1), kv_heads, head_dim); + nn_check_heads(v.extent(0), v.extent(1), kv_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(pos < cos.extent(0) && pos < sin.extent(0) && half <= cos.extent(1) && half <= sin.extent(1), "rope_and_store: `cos` and `sin` need a row for `pos` with head_dim / 2 values"); + spawn on(Topology::Device) { + for h in 0..q_heads + kv_heads across blocks { + for i in 0..128 across lanes { + if i < head_dim { + // Value i of the head, its partner, and the angle that they share. + let mut j = i; + let mut sign : f32 = -1.0; + let mut partner = i + half; + if i >= half { + j = i - half; + sign = 1.0; + partner = i - half; + } + let c = cos[pos][j]; + let s = sin[pos][j]; + if h < q_heads { + q_out[h][i] = q[h][i] * c + sign * q[h][partner] * s; + } else { + k_cache[pos][h - q_heads][i] = (k[h - q_heads][i] * c + sign * k[h - q_heads][partner] * s) as f16; + v_cache[pos][h - q_heads][i] = v[h - q_heads][i] as f16; + } + } + } + } + } + return; +} + +/// As `rope_and_store`, after an RMSNorm over each head of q and of k: value i of a head x +/// becomes x[i] / sqrt(mean(x^2) + eps) * norm[i], where `norm` is `q_norm` for q and `k_norm` +/// for k. Qwen3 has these norms. +fn norm_rope_and_store(q_out : &mut Tensor, k_cache : &mut Tensor, v_cache : &mut Tensor, q : &Tensor, k : &Tensor, v : &Tensor, q_norm : &Tensor, k_norm : &Tensor, cos : &Tensor, sin : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32, eps : f32) -> void { + let half = head_dim / 2; + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(q_out.extent(0), q_out.extent(1), q_heads, head_dim); + nn_check_heads(k.extent(0), k.extent(1), kv_heads, head_dim); + nn_check_heads(v.extent(0), v.extent(1), kv_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_norm.len() >= head_dim && k_norm.len() >= head_dim, "norm_rope_and_store: `q_norm` and `k_norm` need head_dim values"); + assert(pos < cos.extent(0) && pos < sin.extent(0) && half <= cos.extent(1) && half <= sin.extent(1), "norm_rope_and_store: `cos` and `sin` need a row for `pos` with head_dim / 2 values"); + spawn on(Topology::Device) { + for h in 0..q_heads + kv_heads across blocks { + let mut x = unsafe { Tensor::uninit() }; + let mut part = unsafe { Tensor::uninit() }; + for i in 0..128 across lanes { + let mut a : f32 = 0.0; + if i < head_dim { + if h < q_heads { + a = q[h][i]; + } else { + a = k[h - q_heads][i]; + } + } + x[i] = a; + part[i] = a * a; + } + let ss = lanes::sum(&part, 128); + let inv = 1.0 / (ss / (head_dim as f32) + eps).sqrt(); + for i in 0..128 across lanes { + if i < head_dim { + // Value i of the head, its partner, and the angle that they share. + let mut j = i; + let mut sign : f32 = -1.0; + let mut partner = i + half; + if i >= half { + j = i - half; + sign = 1.0; + partner = i - half; + } + let c = cos[pos][j]; + let s = sin[pos][j]; + if h < q_heads { + let a = x[i] * inv * (q_norm[i] as f32); + let b = x[partner] * inv * (q_norm[partner] as f32); + q_out[h][i] = a * c + sign * b * s; + } else { + let a = x[i] * inv * (k_norm[i] as f32); + let b = x[partner] * inv * (k_norm[partner] as f32); + k_cache[pos][h - q_heads][i] = (a * c + sign * b * s) as f16; + v_cache[pos][h - q_heads][i] = v[h - q_heads][i] as f16; + } + } + } + } + } + return; +} +//===- deltanet.vx - Qwen app -----------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// One generated token through the Gated DeltaNet of a linear attention layer of Qwen3.5 and +// Qwen3.6 (#89), after the product `linear_in` and before the product `linear_out`. The math is +// that of `modeling_qwen3_5_moe.py` of transformers: +// +// - `proj`, the output of `linear_in`, has q (k_heads x 128), k (k_heads x 128), v (v_heads x 128), +// z (v_heads x 128), then b and a (v_heads each), at the offsets that the caller gives. +// - q, k and v go through a causal depthwise convolution of width 4 and a SiLU. q and k then get an +// L2 norm for each head (eps 1e-6 inside the square root), and q is multiplied by 1/sqrt(128). +// - beta = sigmoid(b), and the decay exp(g) with g = -exp(A_log) softplus(a + dt_bias). The weight +// file stores -exp(A_log) as `neg_a`. +// - Head h of v uses head h / (v_heads / k_heads) of q and k. Its state S[k][v] decays, then +// S += k (beta (v - k . S)), and the output is q . S. +// - The output gets an RMS norm for each head, times the norm weight, times silu(z). +// +// All the heads have 128 values. The state of a layer is `conv_state` [2 k_heads + v_heads, 128, 3], +// the last 3 inputs of each channel of the convolution, oldest first, and `state` [v_heads, 128, 128] +// as S[v][k]: the 128 values of k for one value of v are next to each other, so that the 32 lanes of +// a SIMD group read them in one load. Both start at zero. +import core::num; +import std::nn; +import qwen::simd; + +/// The scratch tensors of one token, in GPU memory: q and k after the convolution and the norm +/// [k_heads, 128], v after the convolution [v_heads, 128], beta and the decay exp(g) of each head of +/// v, and q . S [v_heads, 128]. +struct DeltaNetScratch { + q : Tensor, + k : Tensor, + v : Tensor, + beta : Tensor, + decay : Tensor, + o : Tensor, +} + +fn deltanet_scratch(k_heads : i32, v_heads : i32) -> DeltaNetScratch { + return DeltaNetScratch { + q : transfer(Tensor([k_heads, 128]), Memory::HBM), + k : transfer(Tensor([k_heads, 128]), Memory::HBM), + v : transfer(Tensor([v_heads, 128]), Memory::HBM), + beta : transfer(Tensor([v_heads]), Memory::HBM), + decay : transfer(Tensor([v_heads]), Memory::HBM), + o : transfer(Tensor([v_heads, 128]), Memory::HBM), + }; +} + +/// A tensor of zeros in GPU memory. +fn dn_zeros(a : i32, b : i32, c : i32) -> Tensor { + let mut x = Tensor([a, b, c]); + for i in 0..a { + for j in 0..b { + for k in 0..c { + x[i][j][k] = 0.0; + } + } + } + return transfer(x, Memory::HBM); +} + +/// The state of one layer at the start: zero. +fn deltanet_conv_state(k_heads : i32, v_heads : i32) -> Tensor { + return dn_zeros(2 * k_heads + v_heads, 128, 3); +} + +fn deltanet_state(v_heads : i32) -> Tensor { + return dn_zeros(v_heads, 128, 128); +} + +/// The Gated DeltaNet of one token: `y` (v_heads x 128 values, the input of `linear_out`) from `proj` +/// (the output of `linear_in`). z starts at `z_at` of `proj`, b at `b_at` and a at `a_at`. `conv` has +/// 4 taps for each of the (2 k_heads + v_heads) x 128 channels, channel c at 4 c, oldest tap +/// first. `neg_a` and `dt_bias` have v_heads values, and `norm` 128. +fn deltanet_step(y : &mut Tensor, conv_state : &mut Tensor, state : &mut Tensor, t : &mut DeltaNetScratch, proj : &Tensor, conv : &Tensor, neg_a : &Tensor, dt_bias : &Tensor, norm : &Tensor, z_at : i32, b_at : i32, a_at : i32, k_heads : i32, v_heads : i32, eps : f32) -> void { + let channels = (2 * k_heads + v_heads) * 128; + assert(k_heads > 0 && v_heads % k_heads == 0 && v_heads <= 64, "deltanet_step: v_heads must be a multiple of k_heads, and at most 64"); + assert(conv_state.extent(0) == 2 * k_heads + v_heads && conv_state.extent(1) == 128 && conv_state.extent(2) == 3, "deltanet_step: conv_state must be [2 k_heads + v_heads, 128, 3]"); + assert(state.extent(0) == v_heads && state.extent(1) == 128 && state.extent(2) == 128, "deltanet_step: state must be [v_heads, 128, 128]"); + assert(conv.len() == channels * 4, "deltanet_step: conv must have 4 taps for each channel"); + assert(proj.len() >= channels && proj.len() >= z_at + v_heads * 128 && proj.len() >= b_at + v_heads && proj.len() >= a_at + v_heads, "deltanet_step: proj is too short for its offsets"); + assert(neg_a.len() >= v_heads && dt_bias.len() >= v_heads && norm.len() >= 128 && y.len() >= v_heads * 128, "deltanet_step: a tensor is too short"); + deltanet_conv(&mut t.q, &mut t.k, &mut t.v, conv_state, proj, conv, k_heads, v_heads); + deltanet_gates(&mut t.beta, &mut t.decay, proj, neg_a, dt_bias, b_at, a_at, v_heads); + deltanet_recur(&mut t.o, state, &t.q, &t.k, &t.v, &t.beta, &t.decay, v_heads / k_heads, v_heads); + deltanet_gated_norm(y, &t.o, proj, norm, z_at, v_heads, eps); + return; +} + +/// The convolution and the SiLU of q, k and v, and the L2 norms of q and k. Block h does the 128 +/// channels of one head: heads 0 to k_heads - 1 of q, then those of k, then those of v. The channels +/// of `proj` are in the same order, so channel i of block h is h * 128 + i. +fn deltanet_conv(qn : &mut Tensor, kn : &mut Tensor, vv : &mut Tensor, conv_state : &mut Tensor, proj : &Tensor, conv : &Tensor, k_heads : i32, v_heads : i32) -> void { + spawn on(Topology::Device) { + for h in 0..2 * k_heads + v_heads across blocks { + let mut y = unsafe { Tensor::uninit() }; + let mut part = unsafe { Tensor::uninit() }; + for i in 0..128 across lanes { + let c = h * 128 + i; + let x0 = conv_state[h][i][0]; + let x1 = conv_state[h][i][1]; + let x2 = conv_state[h][i][2]; + let x3 = proj[c]; + let a = conv[c * 4] * x0 + conv[c * 4 + 1] * x1 + conv[c * 4 + 2] * x2 + conv[c * 4 + 3] * x3; + let s = a / (1.0 + (0.0 - a).fast_exp()); + conv_state[h][i][0] = x1; + conv_state[h][i][1] = x2; + conv_state[h][i][2] = x3; + y[i] = s; + part[i] = s * s; + } + let ss = lanes::sum(&part, 128); + let inv = 1.0 / (ss + 0.000001).sqrt(); + for i in 0..128 across lanes { + if h < k_heads { + qn[h][i] = y[i] * inv * 0.08838834764831845; + } else if h < 2 * k_heads { + kn[h - k_heads][i] = y[i] * inv; + } else { + vv[h - 2 * k_heads][i] = y[i]; + } + } + } + } + return; +} + +/// beta = sigmoid(b) and the decay exp(neg_a softplus(a + dt_bias)) of each head of v. softplus(x) +/// is x above 20, as in torch. +fn deltanet_gates(beta : &mut Tensor, decay : &mut Tensor, proj : &Tensor, neg_a : &Tensor, dt_bias : &Tensor, b_at : i32, a_at : i32, v_heads : i32) -> void { + spawn on(Topology::Device) { + for blk in 0..1 across blocks { + for j in 0..64 across lanes { + if j < v_heads { + let b = proj[b_at + j]; + beta[j] = 1.0 / (1.0 + (0.0 - b).fast_exp()); + let x = proj[a_at + j] + dt_bias[j]; + let mut sp = x; + if x <= 20.0 { + sp = simd_log(1.0 + x.fast_exp()); + } + decay[j] = (neg_a[j] * sp).fast_exp(); + } + } + } + } + return; +} + +/// The update of the state and the output q . S, for each head h of v. Block (h, vq) is one SIMD +/// group for values vq * 32 to vq * 32 + 31 of v. Lane l owns values 4 l to 4 l + 3 of k. For each +/// value of v, the lanes add up k . S, then each lane updates its 4 values of S and the lanes add up +/// q . S. Lane m keeps the output of value m. +fn deltanet_recur(o : &mut Tensor, state : &mut Tensor, qn : &Tensor, kn : &Tensor, vv : &Tensor, beta : &Tensor, decay : &Tensor, group : i32, v_heads : i32) -> void { + spawn on(Topology::Device) { + for h in 0..v_heads across blocks { + for vq in 0..4 across blocks { + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let g = h / group; + let d = 4 * l; + let q0 = qn[g][d]; + let q1 = qn[g][d + 1]; + let q2 = qn[g][d + 2]; + let q3 = qn[g][d + 3]; + let k0 = kn[g][d]; + let k1 = kn[g][d + 1]; + let k2 = kn[g][d + 2]; + let k3 = kn[g][d + 3]; + let b = beta[h]; + let dec = decay[h]; + let mut mine : f32 = 0.0; + for m in 0..32 { + let v = vq * 32 + m; + let s0 = state[h][v][d] * dec; + let s1 = state[h][v][d + 1] * dec; + let s2 = state[h][v][d + 2] * dec; + let s3 = state[h][v][d + 3] * dec; + let kv = simd_sum(s0 * k0 + s1 * k1 + s2 * k2 + s3 * k3); + let delta = (vv[h][v] - kv) * b; + let n0 = s0 + k0 * delta; + let n1 = s1 + k1 * delta; + let n2 = s2 + k2 * delta; + let n3 = s3 + k3 * delta; + state[h][v][d] = n0; + state[h][v][d + 1] = n1; + state[h][v][d + 2] = n2; + state[h][v][d + 3] = n3; + let out = simd_sum(n0 * q0 + n1 * q1 + n2 * q2 + n3 * q3); + if m == l { + mine = out; + } + } + o[h][vq * 32 + l] = mine; + } + } + } + } + } + return; +} + +/// y = rms_norm(o) * norm * silu(z), for each head of v. Block h does one head. +fn deltanet_gated_norm(y : &mut Tensor, o : &Tensor, proj : &Tensor, norm : &Tensor, z_at : i32, v_heads : i32, eps : f32) -> void { + spawn on(Topology::Device) { + for h in 0..v_heads across blocks { + let mut part = unsafe { Tensor::uninit() }; + for i in 0..128 across lanes { + let a = o[h][i]; + part[i] = a * a; + } + let ss = lanes::sum(&part, 128); + let inv = 1.0 / (ss / 128.0 + eps).sqrt(); + for i in 0..128 across lanes { + let z = proj[z_at + h * 128 + i]; + y[h * 128 + i] = o[h][i] * inv * norm[i] * (z / (1.0 + (0.0 - z).fast_exp())); + } + } + } + return; +} +//===- gated_attention.vx - Qwen app ----------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// The full attention of one token in a layer of Qwen3.5 and Qwen3.6 (#89), between the product +// `qkv` and the product `attn_out`, with the math of `modeling_qwen3_5_moe.py` of transformers: +// +// - `qkvg`, the output of `qkv`, has q (q_heads x 256), k (kv_heads x 256), v (kv_heads x 256), +// then the gate (q_heads x 256). +// - q and k get an RMS norm for each head, times their norm weights, which the weight file stores +// as 1 + w. RoPE then turns the first `rot` values of each head (rotate_half inside those +// values), and leaves the others. +// - Attention with the scale 1/sqrt(256) over the KV cache, which is f16 [position, kv_head, 256]. +// - The output is multiplied by sigmoid(gate). +// +// The attention has the design of `vec_attention` (llama.cpp's kernel_flash_attn_ext_vec, MIT +// License, Copyright (c) 2023-2026 The ggml authors), for 256 values a head: each block is a SIMD +// group of one head of q, and lane l owns values 8 l to 8 l + 7. +import core::num; +import std::nn; +import qwen::simd; + +/// The norms and RoPE of q and k at position `pos`, and the store of k and v into the caches. Block h +/// does head h of q, then the heads of k. `cos` and `sin` have rot / 2 values for each position. +fn gated_norm_rope_and_store(q_out : &mut Tensor, k_cache : &mut Tensor, v_cache : &mut Tensor, qkvg : &Tensor, q_norm : &Tensor, k_norm : &Tensor, cos : &Tensor, sin : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, rot : i32, eps : f32) -> void { + let half = rot / 2; + assert(q_out.extent(0) == q_heads && q_out.extent(1) == 256, "gated_norm_rope_and_store: q_out must be [q_heads, 256]"); + assert(k_cache.extent(0) > pos && k_cache.extent(1) == kv_heads && k_cache.extent(2) == 256 && v_cache.extent(0) > pos && v_cache.extent(1) == kv_heads && v_cache.extent(2) == 256, "gated_norm_rope_and_store: the caches must be [positions, kv_heads, 256] with a row for pos"); + assert(qkvg.len() >= (2 * q_heads + 2 * kv_heads) * 256 && q_norm.len() >= 256 && k_norm.len() >= 256, "gated_norm_rope_and_store: a tensor is too short"); + assert(rot % 2 == 0 && rot <= 256 && pos < cos.extent(0) && pos < sin.extent(0) && half <= cos.extent(1) && half <= sin.extent(1), "gated_norm_rope_and_store: `cos` and `sin` need a row for `pos` with rot / 2 values"); + spawn on(Topology::Device) { + for h in 0..q_heads + kv_heads across blocks { + let mut x = unsafe { Tensor::uninit() }; + let mut part = unsafe { Tensor::uninit() }; + for i in 0..256 across lanes { + let a = qkvg[h * 256 + i]; + x[i] = a; + part[i] = a * a; + } + let ss = lanes::sum(&part, 256); + let inv = 1.0 / (ss / 256.0 + eps).sqrt(); + for i in 0..256 across lanes { + let mut w = q_norm[i]; + if h >= q_heads { + w = k_norm[i]; + } + let a = x[i] * inv * w; + let mut r = a; + if i < rot { + // Value i, its partner, and the angle that they share. + let mut j = i; + let mut sign : f32 = -1.0; + let mut partner = i + half; + if i >= half { + j = i - half; + sign = 1.0; + partner = i - half; + } + let mut wp = q_norm[partner]; + if h >= q_heads { + wp = k_norm[partner]; + } + let b = x[partner] * inv * wp; + r = a * cos[pos][j] + sign * b * sin[pos][j]; + } + if h < q_heads { + q_out[h][i] = r; + } else { + k_cache[pos][h - q_heads][i] = r as f16; + v_cache[pos][h - q_heads][i] = qkvg[(q_heads + kv_heads + h - q_heads) * 256 + i] as f16; + } + } + } + } + return; +} + +/// The attention of the token at position `pos`, times sigmoid(gate): y[h * 256 + d] for each head +/// h of q. `part` is scratch space from `gated_attention_scratch`. +fn gated_attention(y : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, qkvg : &Tensor, pos : i32, q_heads : i32, kv_heads : i32) -> void { + assert(q.extent(0) == q_heads && q.extent(1) == 256 && q_heads % kv_heads == 0, "gated_attention: q must be [q_heads, 256], and q_heads a multiple of kv_heads"); + assert(k_cache.extent(0) > pos && k_cache.extent(1) == kv_heads && k_cache.extent(2) == 256 && v_cache.extent(0) > pos && v_cache.extent(1) == kv_heads && v_cache.extent(2) == 256, "gated_attention: the caches must be [positions, kv_heads, 256] with a row for pos"); + assert(part.extent(0) >= q_heads && part.extent(1) >= 64 && part.extent(2) == 260, "gated_attention: `part` is too small. Make it with gated_attention_scratch"); + assert(y.len() >= q_heads * 256 && qkvg.len() >= (2 * q_heads + 2 * kv_heads) * 256, "gated_attention: a tensor is too short"); + let mut nwg = 32; + if 2 * nwg * 32 < pos + 1 { + nwg = nwg * 2; + } + gated_attention_parts(part, q, k_cache, v_cache, pos, q_heads, q_heads / kv_heads, nwg, 0.0625); + gated_attention_merge(y, part, qkvg, nwg, q_heads, (q_heads + 2 * kv_heads) * 256); + return; +} + +/// The scratch space of `gated_attention`, on the CPU: up to 64 parts for each head of q, each the sum +/// of V (256 values), the largest score, and the sum of the weights. +fn gated_attention_scratch(q_heads : i32) -> Tensor { + return Tensor([q_heads, 64, 260]); +} + +/// The parts of `gated_attention`. Block (h, w) is a SIMD group for head h of q. It does the blocks of +/// 32 positions w, w + nwg, w + 2 nwg, ... up to `pos`, and writes part[h][w]: the sum of V, not +/// divided, then the largest score and the sum of the weights. For each row, the lanes add up their +/// parts of q . k, and lane r keeps the score of row r. Each lane then takes the weight of each row +/// from the lane that keeps it, for the sum of V. +fn gated_attention_parts(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, group : i32, nwg : i32, scale : f32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for w in 0..nwg across blocks { + let mut stats = unsafe { Tensor::uninit() }; + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let g = h / group; + let d = 8 * l; + let q0 = q[h][d] * scale; + let q1 = q[h][d + 1] * scale; + let q2 = q[h][d + 2] * scale; + let q3 = q[h][d + 3] * scale; + let q4 = q[h][d + 4] * scale; + let q5 = q[h][d + 5] * scale; + let q6 = q[h][d + 6] * scale; + let q7 = q[h][d + 7] * scale; + let mut big : f32 = -3.0e38; + let mut total : f32 = 0.0; + let mut o0 : f32 = 0.0; + let mut o1 : f32 = 0.0; + let mut o2 : f32 = 0.0; + let mut o3 : f32 = 0.0; + let mut o4 : f32 = 0.0; + let mut o5 : f32 = 0.0; + let mut o6 : f32 = 0.0; + let mut o7 : f32 = 0.0; + let chunks = (pos + 32) / 32; + let mut c = w; + while c < chunks { + let r0 = c * 32; + let mut mine : f32 = -3.0e38; + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > pos { + kept = pos; + } + let k0 = half4_at(k_cache, kept, g, d, 0); + let k1 = half4_at(k_cache, kept, g, d, 1); + let k2 = half4_at(k_cache, kept, g, d, 2); + let k3 = half4_at(k_cache, kept, g, d, 3); + let k4 = half4_at(k_cache, kept, g, d + 4, 0); + let k5 = half4_at(k_cache, kept, g, d + 4, 1); + let k6 = half4_at(k_cache, kept, g, d + 4, 2); + let k7 = half4_at(k_cache, kept, g, d + 4, 3); + let mut score = simd_sum(((k0 * q0 + k1 * q1) + (k2 * q2 + k3 * q3)) + ((k4 * q4 + k5 * q5) + (k6 * q6 + k7 * q7))); + if row > pos { + score = -3.0e38; + } + if r == l { + mine = score; + } + } + let top = big.max(simd_max(mine)); + let shrink = (big - top).fast_exp(); + let p = (mine - top).fast_exp(); + total = total * shrink + simd_sum(p); + o0 = o0 * shrink; + o1 = o1 * shrink; + o2 = o2 * shrink; + o3 = o3 * shrink; + o4 = o4 * shrink; + o5 = o5 * shrink; + o6 = o6 * shrink; + o7 = o7 * shrink; + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > pos { + kept = pos; + } + let pr = simd_value(p, r); + o0 = o0 + half4_at(v_cache, kept, g, d, 0) * pr; + o1 = o1 + half4_at(v_cache, kept, g, d, 1) * pr; + o2 = o2 + half4_at(v_cache, kept, g, d, 2) * pr; + o3 = o3 + half4_at(v_cache, kept, g, d, 3) * pr; + o4 = o4 + half4_at(v_cache, kept, g, d + 4, 0) * pr; + o5 = o5 + half4_at(v_cache, kept, g, d + 4, 1) * pr; + o6 = o6 + half4_at(v_cache, kept, g, d + 4, 2) * pr; + o7 = o7 + half4_at(v_cache, kept, g, d + 4, 3) * pr; + } + big = top; + c = c + nwg; + } + part[h][w][d] = o0; + part[h][w][d + 1] = o1; + part[h][w][d + 2] = o2; + part[h][w][d + 3] = o3; + part[h][w][d + 4] = o4; + part[h][w][d + 5] = o5; + part[h][w][d + 6] = o6; + part[h][w][d + 7] = o7; + // Every lane has the same largest score and sum of the weights. Lanes 0 and 1 keep them for + // the next loop. + if l < 2 { + let mut x = big; + if l == 1 { + x = total; + } + stats[s][l] = x; + } + } + for l in 0..2 across lanes(32) { + part[h][w][256 + l] = stats[s][l]; + } + } + } + } + } + return; +} + +/// Merges the first `parts` parts of `gated_attention_parts` for each head of q, and multiplies by +/// sigmoid of the gate, which starts at `gate_at` of `qkvg`. A block of 32 lanes does 32 values of one +/// head, a value for each lane. +fn gated_attention_merge(y : &mut Tensor, part : &Tensor, qkvg : &Tensor, parts : i32, q_heads : i32, gate_at : i32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for dq in 0..8 across blocks { + let mut top = unsafe { Tensor::uninit() }; + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let mut m : f32 = -3.0e38; + let mut c = l; + while c < parts { + m = m.max(part[h][c][256]); + c = c + 32; + } + top[s][l] = m; + } + let big = lanes::max(&top[s], 32); + for l in 0..32 across lanes(32) { + let d = dq * 32 + l; + let mut total : f32 = 0.0; + let mut acc : f32 = 0.0; + for c in 0..parts { + let w = (part[h][c][256] - big).fast_exp(); + total = total + w * part[h][c][257]; + acc = acc + w * part[h][c][d]; + } + let gate = qkvg[gate_at + h * 256 + d]; + y[h * 256 + d] = acc / total / (1.0 + (0.0 - gate).fast_exp()); + } + } + } + } + } + return; +} +//===- main.vx - Qwen app ---------------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// Generates tokens with greedy decoding, on the GPU: +// +// vxc src/main.vx --package qwen=src --host default \ +// --machine ~/.vx/current/fleet/m4-uma.vx -- WEIGHTS --tokens 750,75698,1445 --steps 16 +// vxc src/main.vx ... -- WEIGHTS --tokenizer TOKENIZER --prompt "def fibonacci(n):" --steps 64 +// vxc src/main.vx ... -- WEIGHTS --tokenizer TOKENIZER --chat --prompt-file FILE --steps 512 +// +// With --tokens, it prints the lines that `scripts/reference.py` prints, without the margin, and +// then the time of a token. `scripts/compare.py` compares the two outputs. +// +// With --tokenizer, a file of `scripts/convert_tokenizer.py`, the prompt is text: --prompt TEXT or +// --prompt-file FILE. The program prints the prompt and the text that it generates. It stops at a +// special token, such as <|im_end|>, or after --steps tokens. --chat puts the prompt in the chat +// format of the Instruct models and prints only the reply. --lines prints the lines of --tokens +// in place of the text. +import core::convert; +import std::time; +import std::vec; +import qwen::weights; +import qwen::model; +import qwen::qwen35; +import qwen::prefill35; +import qwen::prefill; +import qwen::session; +import qwen::speculate; +import qwen::round; +import qwen::tokenizer; + +/// The options of the command line. +struct Options { + weights : *const i8, + tokens : *const i8, + tokenizer : *const i8, + prompt : *const i8, + prompt_file : *const i8, + steps : *const i8, + has_tokens : bool, + has_tokenizer : bool, + has_prompt : bool, + has_prompt_file : bool, + has_steps : bool, + context : *const i8, + has_context : bool, + requests : *const i8, + has_requests : bool, + replies : *const i8, + has_replies : bool, + session : bool, + chat : bool, + lines : bool, + draft : *const i8, + has_draft : bool, +} + +/// The options of `argv`. Asserts that they are complete and that they fit together. +fn parse_options(argc : i32, argv : *mut *mut i8) -> Options { + assert(argc >= 4, "give: WEIGHTS --tokens 1,2,3 --steps N, or WEIGHTS --tokenizer FILE (--prompt TEXT | --prompt-file FILE) [--chat] [--lines] --steps N"); + let empty : *const i8 = ""; + let mut o = Options { + weights: unsafe { argv[1] }, tokens: empty, tokenizer: empty, prompt: empty, prompt_file: empty, + steps: empty, has_tokens: false, has_tokenizer: false, has_prompt: false, has_prompt_file: false, + has_steps: false, context: empty, has_context: false, requests: empty, has_requests: false, replies: empty, has_replies: false, session: false, chat: false, lines: false, draft: empty, has_draft: false, + }; + let mut i = 2; + while i < argc { + let name = unsafe { argv[i] }; + if same(name, "--chat") { + o.chat = true; + i = i + 1; + } else if same(name, "--session") { + o.session = true; + i = i + 1; + } else if same(name, "--lines") { + o.lines = true; + i = i + 1; + } else { + assert(i + 1 < argc, "give: WEIGHTS --tokens 1,2,3 --steps N, or WEIGHTS --tokenizer FILE (--prompt TEXT | --prompt-file FILE) [--chat] [--lines] --steps N"); + let value = unsafe { argv[i + 1] }; + if same(name, "--tokens") { + o.tokens = value; + o.has_tokens = true; + } else if same(name, "--tokenizer") { + o.tokenizer = value; + o.has_tokenizer = true; + } else if same(name, "--prompt") { + o.prompt = value; + o.has_prompt = true; + } else if same(name, "--prompt-file") { + o.prompt_file = value; + o.has_prompt_file = true; + } else if same(name, "--context") { + o.context = value; + o.has_context = true; + } else if same(name, "--requests") { + o.requests = value; + o.has_requests = true; + } else if same(name, "--replies") { + o.replies = value; + o.has_replies = true; + } else if same(name, "--draft") { + o.draft = value; + o.has_draft = true; + } else { + assert(same(name, "--steps"), "give: WEIGHTS --tokens 1,2,3 --steps N, or WEIGHTS --tokenizer FILE (--prompt TEXT | --prompt-file FILE) [--chat] [--lines] --steps N"); + o.steps = value; + o.has_steps = true; + } + i = i + 2; + } + } + if o.session { + assert(o.has_tokenizer && o.has_context && o.has_requests && o.has_replies && !o.has_tokens && !o.has_prompt && !o.has_prompt_file && !o.has_steps, "give: WEIGHTS --tokenizer FILE --session --context N --requests FILE --replies FILE"); + return o; + } + assert(o.has_steps, "give: WEIGHTS --tokens 1,2,3 --steps N, or WEIGHTS --tokenizer FILE (--prompt TEXT | --prompt-file FILE) [--chat] [--lines] --steps N"); + let one_text = o.has_prompt != o.has_prompt_file; + let no_text = !o.has_prompt && !o.has_prompt_file; + assert((o.has_tokens && no_text) || (o.has_tokenizer && !o.has_tokens && one_text), "give: WEIGHTS --tokens 1,2,3 --steps N, or WEIGHTS --tokenizer FILE (--prompt TEXT | --prompt-file FILE) [--chat] [--lines] --steps N"); + assert(o.has_tokenizer || (!o.chat && !o.lines), "--chat and --lines need --tokenizer"); + return o; +} + +/// The comma-separated numbers of `text`. Asserts that it has only digits and commas, and no empty +/// number. +fn parse_numbers(text : *const i8) -> Vec { + let mut numbers = Vec::new(); + let mut value : i32 = 0; + let mut digits = 0; + let mut empty = false; + let mut i : i64 = 0; + let mut ch = i32::from(unsafe { text[0] }); + while ch != 0 { + if ch == 44 { + empty = empty || digits == 0; + numbers.push(value); + value = 0; + digits = 0; + } else { + assert(ch >= 48 && ch <= 57, "a list of numbers can have only digits and commas"); + value = value * 10 + (ch - 48); + digits = digits + 1; + } + i = i + 1; + ch = i32::from(unsafe { text[i] }); + } + assert(!empty && digits > 0, "an empty number in a comma-separated list"); + numbers.push(value); + return numbers; +} + +/// The number of tokens that text mode runs through the model before it reads them. A read waits +/// for all the work that the GPU was given, and then the GPU has nothing to do until the CPU gives +/// it the next token: about 0.37 ms of a 21.9 ms token on the M4. The input of a token is the +/// argmax of the token before it, in GPU memory, so the GPU can run several tokens without the +/// CPU. Then the GPU waits only once for each AHEAD tokens. Up to AHEAD - 1 tokens after the end +/// of the text are run and thrown away. +const AHEAD : i32 = 8; + +/// The GPU tensor of one token. +struct Slot { + next : Tensor, +} + +/// The token in `t`. Reading it waits for the GPU to finish the work before it. +fn read_token(t : &Tensor) -> i32 { + let h = transfer(t, Memory::CPU_DRAM); + return h[0]; +} + +/// The logit `token` of `logits`. +fn read_logit(logits : &Tensor, token : i32) -> f32 { + let h = transfer(logits, Memory::CPU_DRAM); + return h[token]; +} + +/// Whether the C string `a` is `b`. +fn same(a : *const i8, b : *const i8) -> bool { + return unsafe { strcmp(a, b) } == 0; +} + +/// The token ids of the prompt: the numbers of --tokens, or the tokens of the text. +fn prompt_ids(o : &Options, t : &Tokenizer) -> Vec { + if o.has_tokens { + return parse_numbers(o.tokens); + } + let text = if o.has_prompt { + c_text(o.prompt) + } else { + read_text_file(o.prompt_file) + }; + let full = if o.chat { + chat_text(&text) + } else { + text + }; + let ids = encode(t, full.bytes, full.length); + assert(ids.len() > 0, "the prompt has no tokens"); + return ids; +} + +/// Shows token number `step`, as the loop of `main` does: its text, or a line with its logit. +/// Gives false at the end of the text, where the loop stops. +fn show(t : &Tokenizer, w : &Weights, text_mode : bool, step : i32, token : i32, logit : f32) -> bool { + if text_mode { + if is_special(t, token) || token == w.config.eos_token_id { + return false; + } + write_token(t, token); + } else { + println!("step={} token={} logit={};", step, token, logit); + } + return true; +} + +/// The logit `token` of position j of a round. +fn round_logit(r : &Round, j : i32, token : i32) -> f32 { + let h = transfer(&r.logits, Memory::CPU_DRAM); + return h[j][token]; +} + +/// The loop of `main` with speculative decoding (src/speculate.vx). Each step is a round of the +/// last token and a draft from the context, or a plain step when the draft would not pay: when the +/// longest earlier match of the end of the context is shorter than 6 tokens, or after 2 rounds in a +/// row that accepted nothing, until a longer match than theirs appears. A draft has up to `max` +/// tokens. `first` is the first generated token, from the logits in `s.logits`. Shows the same +/// `steps` tokens as the loop of `main`, and gives the number of tokens after the first. +fn generate_with_drafts(w : &Weights, s : &mut State, t : &Tokenizer, text_mode : bool, prompt : &Vec, first : i32, steps : i32, max : i32, start : &mut Instant) -> i32 { + assert(can_round(w), "--draft needs a model of Q4_0 experts with QK norms, head_dim 128 and a 6-bit lm_head"); + assert(max >= 1 && max < ROUND_MAX, "--draft must be 1 to ROUND_MAX - 1"); + assert(steps >= ROUND_MAX, "--draft needs --steps of at least ROUND_MAX"); + let mut r = new_round(&w.config); + // One run of the round kernels for each n to 8, so that their compile time is not in the time + // of a token: it restarts the clock. Larger rounds use the same kernels. The rounds write rows of + // the KV cache that the steps write again before they read them. + let mut warm = Vec::new(); + for n in 1..9 { + warm.push(first); + run_round(w, s, &mut r, &warm, prompt.len(), n); + } + let _ready = transfer(&r.next, Memory::CPU_DRAM); + *start = Instant::now(); + // The tokens of a run of plain steps: token j is in ring[j]. + let mut ring = Vec::new(); + for j in 0..AHEAD { + ring.push(Slot { + next: transfer(Tensor([1]), Memory::HBM), + }); + } + // The length of the next run of plain steps: 1 after a round, then 2, 4 and up to AHEAD while + // no draft comes up. The GPU runs the tokens of a run before the CPU reads them. Lines mode + // prints the logit of each token, so it reads each one. + let mut run = 1; + let mut context = Vec::new(); + for i in 0..prompt.len() { + context.push(prompt[i]); + } + let mut token = first; + context.push(token); + // The position of `token`, which is not in the KV cache yet. + let mut pos = prompt.len(); + let mut step = 0; + let mut rounds = 0; + let mut drafted = 0; + let mut accepted = 0; + // Rounds in a row that accepted nothing, and the length of the match of the last of them. + let mut misses = 0; + let mut missed_length = 0; + let mut going = show(t, w, text_mode, 0, token, read_logit(&s.logits, token)); + while going && step + 1 < steps { + let room = steps - step - 1; + let m = longest_match(&context); + if misses >= 2 && m.length > missed_length { + misses = 0; + } + let mut k = i32::min(i32::min(draft_length(m.length), max), room - 1); + if misses >= 2 { + k = 0; + } + let draft = tokens_after(&context, m.end, k); + k = draft.len(); + if k == 0 { + // Plain steps, with the kernels of one token each. + let mut n = 1; + if text_mode { + n = i32::min(run, room); + } + let mut h = Tensor([1]); + h[0] = token; + let input = transfer(h, Memory::HBM); + run_layers(w, s, &input, pos); + predict(w, s, &mut ring[0].next); + for j in 1..n { + run_layers(w, s, &ring[j - 1].next, pos + j); + predict(w, s, &mut ring[j].next); + } + let mut j = 0; + while j < n && going { + token = read_token(&ring[j].next); + context.push(token); + step = step + 1; + pos = pos + 1; + let mut logit : f32 = 0.0; + if !text_mode { + logit = read_logit(&s.logits, token); + } + going = show(t, w, text_mode, step, token, logit); + j = j + 1; + } + run = i32::min(run * 2, AHEAD); + } else { + run = 1; + let mut inputs = Vec::new(); + inputs.push(token); + for i in 0..k { + inputs.push(draft[i]); + } + run_round(w, s, &mut r, &inputs, pos, k + 1); + let choice = transfer(&r.next, Memory::CPU_DRAM); + rounds = rounds + 1; + drafted = drafted + k; + // c0 is the next token; each draft token that equals the choice before it adds the next one. + let mut j = 0; + let mut more = true; + while more && going { + token = choice[j]; + context.push(token); + step = step + 1; + let mut logit : f32 = 0.0; + if !text_mode { + logit = round_logit(&r, j, token); + } + going = show(t, w, text_mode, step, token, logit); + more = j < k && draft[j] == token; + if more { + accepted = accepted + 1; + j = j + 1; + } + } + pos = pos + j + 1; + if j == 0 { + misses = misses + 1; + missed_length = m.length; + } else { + misses = 0; + } + } + } + println!("rounds={} drafted={} accepted={};", rounds, drafted, accepted); + return step; +} + +/// `main` for a Qwen3.5 or Qwen3.6 model (weight file v2, arch 1). The prompt runs in chunks +/// (src/prefill35.vx). There are no drafts yet (#89). Prints the same lines diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/context/llama/ctx512.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/context/llama/ctx512.txt new file mode 100644 index 0000000..f61da32 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/context/llama/ctx512.txt @@ -0,0 +1,43 @@ +//===- model.vx - Qwen app --------------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// One token of a Qwen2 or Qwen3 MoE decoder on the GPU, with the kernels of `std::nn`. `State` +// holds every tensor that a token writes, and the KV cache. It is made once, before the first +// token, so the token loop allocates nothing. +import core::convert; +import core::num; +import std::nn; +import std::vec; +import qwen::attention; +import qwen::products; +import qwen::q6; +import qwen::weights; + +/// The keys and the values of every position so far, for one layer: [max_seq, kv_heads, head_dim]. +/// They are f16, half the memory of f32. The kernels compute in f32, and round only what they +/// store here. +struct Cache { + k : Tensor, + v : Tensor, +} + +/// The tensors of a mixture-of-experts layer: the router's score of each expert, the chosen +/// experts and their weights, and the SwiGLU output of each chosen expert, [experts_per_token, +/// moe_intermediate_size]. +struct Experts { + router_logits : Tensor, + ids : Tensor, + weights : Tensor, + mlp : Tensor, +} + +/// The tensors that a token writes, in GPU memory, and one `Cache` for each layer. `cos` and `sin` +/// are [max_seq, head_dim / 2]. +struct State { + max_seq : i32, + x : Tensor, + xn : Tensor, + v : Tensor, +} + +/// The tensors of a mixture-of-experts layer: the router's score of each expert, the chosen +/// experts and their weights, and the SwiGLU output of each chosen expert, [experts_per_token, +/// moe_intermediate_size]. +struct Experts { + router_logits : Tensor, + ids : Tensor, + weights : Tensor, + mlp : Tensor, +} + +/// The tensors that a token writes, in GPU memory, and one `Cache` for each layer. `cos` and `sin` +/// are [max_seq, head_dim / 2]. +struct State { + max_seq : i32, + x : Tensor, + xn : Tensor, + q : Tensor, + k : Tensor, + v : Tensor, + q_turned : Tensor, + attended : Tensor, + attention_parts : Tensor, + vec_parts : Tensor, + mlp : Tensor, + experts : Experts, + logits : Tensor, + cos : Tensor, + sin : Tensor, + caches : Vec, +} + +/// The state for up to `max_seq` positions. The angles of RoPE are computed in f64, as in +/// `reference.py`, and rounded to f32 once. +fn new_state(c : &Config, max_seq : i32) -> State { + assert(max_seq > 0 && max_seq <= c.max_positions, "max_seq must be between 1 and the max_positions of the model"); + let half = c.head_dim / 2; + let mut hcos = Tensor([max_seq, half]); + let mut hsin = Tensor([max_seq, half]); + for p in 0..max_seq { + for i in 0..half { + let angle = f64::from(p) / f64::powf(c.rope_theta, f64::from(2 * i) / f64::from(c.head_dim)); + hcos[p][i] = f64::cos(angle) as f32; + hsin[p][i] = f64::sin(angle) as f32; + } + } + // A dense model uses none of the tensors of the experts, so one value each is enough. + let experts = i32::max(c.num_experts, 1); + let chosen = i32::max(c.experts_per_token, 1); + let moe_inter = i32::max(c.moe_intermediate_size, 1); + // The flash attention of a prompt reads the cache in blocks of 64 positions. + let rows = (max_seq + 63) / 64 * 64; + let mut caches = Vec::new(); + for l in 0..c.num_layers { + caches.push(Cache { + k: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + }); + } + return State { + max_seq: max_seq, + x: transfer(Tensor([c.hidden_size]), Memory::HBM), + xn: transfer(Tensor([c.hidden_size]), Memory::HBM), + q: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + k: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + q_turned: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attended: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attention_parts: transfer(split_attention_scratch(max_seq, c.num_q_heads, c.num_kv_heads, c.head_dim), Memory::HBM), + vec_parts: transfer(vec_attention_scratch(c.num_q_heads), Memory::HBM), + mlp: transfer(Tensor([c.intermediate_size]), Memory::HBM), + experts: Experts { + router_logits: transfer(Tensor([experts]), Memory::HBM), + ids: transfer(Tensor([chosen]), Memory::HBM), + weights: transfer(Tensor([chosen]), Memory::HBM), + mlp: transfer(Tensor([chosen, moe_inter]), Memory::HBM), + }, + logits: transfer(Tensor([c.vocab_size]), Memory::HBM), + cos: transfer(hcos, Memory::HBM), + sin: transfer(hsin, Memory::HBM), + caches: caches, + }; +} + +/// y = m x, with the kernel for the dtype of `m`, which has `rows` x `cols` weights. +fn matvec(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U6 { + matvec_q6(y, &m.codes, &m.high, &m.group_scales, x, rows, cols); + } else if m.dtype == U4 { + nn_matvec_q4(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x. +fn matvec_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_matvec_q4_add(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_add(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec_add(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x, for x of [heads, head_dim]. +fn matvec_heads_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, heads : i32, head_dim : i32) -> void { + if m.dtype == U4 { + matvec_q4_heads_add_blocks(y, &m.codes, &m.group_scales, x, rows, heads, head_dim); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_heads_add(y, &m.codes, &m.scales, x, rows, heads, head_dim); + } else { + nn_matvec_heads_add(y, &m.bf16, x, rows, heads, head_dim); + } + return; +} + +/// The Q, K and V of x: m x + b, split by heads. +fn qkv(q : &mut Tensor, k : &mut Tensor, v : &mut Tensor, m : &WeightMatrix, b : &Tensor, x : &Tensor, c : &Config) -> void { + if m.dtype == U4 { + qkv_q4_blocks(q, k, v, &m.codes, &m.group_scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } else if m.dtype == F8E4M3 { + nn_qkv_fp8(q, k, v, &m.codes, &m.scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } else { + nn_qkv(q, k, v, &m.bf16, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } + return; +} + +/// The SwiGLU of a dense MLP, for the gate rows and then the up rows of `m`. +fn swiglu(out : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_swiglu_q4(out, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_swiglu_fp8(out, &m.codes, &m.scales, x, rows, cols); + } else { + nn_swiglu(out, &m.bf16, x, rows, cols); + } + return; +} + +/// The mixture of experts of a layer: the router chooses experts_per_token experts and their +/// weights, and x gets the sum of their outputs for xn, each times its weight. +fn add_experts(e : &mut Experts, x : &mut Tensor, xn : &Tensor, layer : &Layer, c : &Config) -> void { + let k = c.experts_per_token; + let inter = c.moe_intermediate_size; + nn_matvec(&mut e.router_logits, &layer.router, xn, c.num_experts, c.hidden_size); + nn_top_k(&mut e.ids, &mut e.weights, &e.router_logits, c.num_experts, k); + let gate_up = &layer.gate_up; + let down = &layer.down; + if gate_up.dtype == U4 { + moe_swiglu_q4_blocks(&mut e.mlp, &gate_up.codes, &gate_up.group_scales, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + moe_down_q4_add_blocks(x, &down.codes, &down.group_scales, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + } else { + assert(gate_up.dtype == BF16, "the experts of a mixture-of-experts model must be bf16 or Q4_0"); + nn_moe_swiglu(&mut e.mlp, &gate_up.bf16, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + nn_moe_down_add(x, &down.bf16, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + } + return; +} + +/// Runs the token in `token` at position `pos` through every layer. The hidden state of the +/// token is then in `s.x`, and its keys and values are in the caches. +fn run_layers(w : &Weights, s : &mut State, token : &Tensor, pos : i32) -> void { + let c = &w.config; + let eps = c.rms_norm_eps as f32; + assert(pos >= 0 && pos < s.max_seq, "the position is past the end of the KV cache"); + nn_embed(&mut s.x, &w.embed, token, c.hidden_size); + let mut l = 0; + for cache in s.caches.iter_mut() { + let layer = &w.layers[l]; + nn_rms_norm(&mut s.xn, &s.x, &layer.attn_norm, c.hidden_size, eps); + qkv(&mut s.q, &mut s.k, &mut s.v, &layer.qkv, &layer.qkv_bias, &s.xn, c); + if c.qk_norm { + norm_rope_and_store(&mut s.q_turned, &mut cache.k, &mut cache.v, &s.q, &s.k, &s.v, &layer.q_norm, &layer.k_norm, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.head_dim, eps); + } else { + rope_and_store(&mut s.q_turned, &mut cache.k, &mut cache.v, &s.q, &s.k, &s.v, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } + if c.head_dim == 128 { + vec_attention(&mut s.attended, &mut s.vec_parts, &s.q_turned, &cache.k, &cache.v, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } else { + split_attention(&mut s.attended, &mut s.attention_parts, &s.q_turned, &cache.k, &cache.v, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } + matvec_heads_add(&mut s.x, &layer.attn_out, &s.attended, c.hidden_size, c.num_q_heads, c.head_dim); + nn_rms_norm(&mut s.xn, &s.x, &layer.mlp_norm, c.hidden_size, eps); + if c.num_experts > 0 { + add_experts(&mut s.experts, &mut s.x, &s.xn, layer, c); + } else { + swiglu(&mut s.mlp, &layer.gate_up, &s.xn, c.intermediate_size, c.hidden_size); + matvec_add(&mut s.x, &layer.down, &s.mlp, c.hidden_size, c.intermediate_size); + } + l = l + 1; + } + return; +} + +/// The logits of the token whose hidden state is in `s.x`, and in `next` the index of the largest +/// one. Both stay in GPU memory. +fn predict(w : &Weights, s : &mut State, next : &mut Tensor) -> void { + let c = &w.config; + nn_rms_norm(&mut s.xn, &s.x, &w.final_norm, c.hidden_size, c.rms_norm_eps as f32); + if c.tied_embeddings { + nn_matvec(&mut s.logits, &w.embed, &s.xn, c.vocab_size, c.hidden_size); + } else { + matvec(&mut s.logits, &w.lm_head, &s.xn, c.vocab_size, c.hidden_size); + } + nn_argmax(next, &s.logits, c.vocab_size); + return; +} +//===- attention.vx - Qwen app ----------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// The attention of one generated token, with the positions split among blocks. This is a copy of +// `nn_attention` and its kernels from `std::nn` on Vx main (vx-lang/Vx#3216), with `split_` in place +// of `nn_` in their names. Vx v0.0.4 has the older `nn_attention`, which has one block for each head +// of Q, so its time grows with the number of positions. Remove this file, and call `nn_attention` +// of `std::nn`, when a Vx release has the new one (#4). +// +// `vec_attention`, for head_dim 128, has the design of llama.cpp's flash attention for one token +// (kernel_flash_attn_ext_vec and kernel_flash_attn_ext_vec_reduce), MIT License, Copyright (c) 2023-2026 +// The ggml authors. scripts/mlir_kernels/decode_attention.py writes its kernels: change that script, not +// the MLIR. +import core::num; +import std::nn; + +/// Attention of the token at position `pos` over rows 0 to `pos` of the KV cache, with a softmax +/// of the scores q . k / sqrt(head_dim). `part` is scratch space from `split_attention_scratch`. +/// +/// The blocks of the first kernel split the positions, 32 to a block below position 640 and 64 from +/// there on. A block serves the 8 heads of Q that share a head of K and V, so it reads each row of +/// the cache once for all 8. A second kernel merges the parts of the blocks for each head. +fn split_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_heads % kv_heads == 0, "split_attention: q_heads must be a multiple of kv_heads"); + assert(head_dim % 32 == 0 && head_dim <= 128, "split_attention: head_dim must be a multiple of 32, and at most 128"); + let mut n_pos = 32; + if pos >= 640 { + n_pos = 64; + } + assert(part.extent(0) >= kv_heads * ((q_heads / kv_heads + 7) / 8) && part.extent(1) >= (pos + n_pos) / n_pos && part.extent(2) >= 8 && part.extent(3) >= head_dim + 2, "split_attention: `part` is too small for this position. Make it with split_attention_scratch"); + if n_pos == 32 { + split_attention_parts_32(part, q, k_cache, v_cache, pos, q_heads, kv_heads, head_dim); + } else { + split_attention_parts_64(part, q, k_cache, v_cache, pos, q_heads, kv_heads, head_dim); + } + split_attention_merge(out, part, pos, n_pos, q_heads, kv_heads, head_dim); + return; +} + +/// Attention of the token at position `pos`, as `split_attention`, for head_dim 128, with the kernels of +/// llama.cpp's flash attention for one token. `vec_attention_parts` splits the blocks of 32 positions among +/// `nwg` SIMD groups for each head of Q: 32 of them, or 64 when each of 32 would have more than 2 blocks. +/// (llama.cpp goes on to 4 SIMD groups of 32 a block, but 128 parts are no faster here: their merge costs what +/// they save.) `vec_attention_merge` then merges the parts. `part` is scratch space from +/// `vec_attention_scratch`. +fn vec_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_heads % kv_heads == 0 && head_dim == 128, "vec_attention: q_heads must be a multiple of kv_heads, and head_dim 128"); + assert(part.extent(0) >= q_heads && part.extent(1) >= 128 && part.extent(2) == 132, "vec_attention: `part` is too small. Make it with vec_attention_scratch"); + let mut nwg = 32; + if 2 * nwg * 32 < pos + 1 { + nwg = nwg * 2; + } + vec_attention_parts(part, q, k_cache, v_cache, pos, q_heads, q_heads / kv_heads, nwg, 1.0 / (head_dim as f32).sqrt()); + vec_attention_merge(out, part, nwg, q_heads); + return; +} + +/// The scratch space of `vec_attention`, on the CPU: up to 128 parts for each head of Q, each the sum of V +/// (128 values), the largest score, and the sum of the weights. A part has 132 values, so that each starts +/// at a multiple of 16 bytes. +fn vec_attention_scratch(q_heads : i32) -> Tensor { + return Tensor([q_heads, 128, 132]); +} + +/// The parts of `vec_attention`, as llama.cpp's kernel_flash_attn_ext_vec. Block (h, w) is a SIMD group for +/// query head h. It does the blocks of 32 positions w, w + nwg, w + 2 nwg, ... up to `pos`, and writes +/// part[h][w]. Lane l owns values 4 l to 4 l + 3 of the head, so that the 32 lanes read a row of K or V in +/// one 256-byte load. For each row, the lanes add up their parts of q . k; then each lane keeps the score +/// of one row, and the lanes take the weights of the rows from each other for the sum of V. A part is the +/// sum of V, not divided, then the largest score and the sum of the weights. +fn vec_attention_parts(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, group : i32, nwg : i32, scale : f32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for w in 0..nwg across blocks { + let g = h / group; + let _d = mlir!( threads : 32, inputs : (%part = part : memref, %q = q : memref, %k3 = k_cache : memref, %v3 = v_cache : memref, %pos = pos : i32, %nwg = nwg : i32, %scale = scale : f32, %h = h : i32, %w = w : i32, %g = g : i32), returns : i32, dialects : ["arith", "memref", "scf", "gpu", "vector", "math"], ensures : [reads_only(q), reads_only(k_cache), reads_only(v_cache), writes_only(part[h][w])]) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %c4 = arith.constant 4 : index + %c32 = arith.constant 32 : index + %c128 = arith.constant 128 : index + %c129 = arith.constant 129 : index + %c32i = arith.constant 32 : i32 + %neg = arith.constant -3.0e38 : f32 + %zero = arith.constant 0.0 : f32 + %vz4 = arith.constant dense<0.0> : vector<4xf32> + %l = gpu.thread_id x + %l4 = arith.muli %l, %c4 : index + %hi = arith.index_cast %h : i32 to index + %wi = arith.index_cast %w : i32 to index + %gi = arith.index_cast %g : i32 to index + %posi = arith.index_cast %pos : i32 to index + %nwgi = arith.index_cast %nwg : i32 to index + %g128 = arith.muli %gi, %c128 : index + %kd = arith.addi %g128, %l4 : index + %P = memref.dim %k3, %c0 : memref + %KH = memref.dim %k3, %c1 : memref + %Wd = arith.muli %KH, %c128 : index + %k = memref.reinterpret_cast %k3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to memref> + %v = memref.reinterpret_cast %v3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to memref> + %qv = vector.load %q[%hi, %l4] {alignment = 16} : memref, vector<4xf32> + %scv = vector.broadcast %scale : f32 to vector<4xf32> + %qs = arith.mulf %qv, %scv : vector<4xf32> + %nkv = arith.addi %posi, %c32 : index + %chunks = arith.divui %nkv, %c32 : index + %st:3 = scf.for %ic = %wi to %chunks step %nwgi iter_args(%M = %neg, %S = %zero, %o = %vz4) -> (f32, f32, vector<4xf32>) { + %r0 = arith.muli %ic, %c32 : index + %my = scf.for %cc = %c0 to %c32 step %c1 iter_args(%m = %neg) -> (f32) { + %row = arith.addi %r0, %cc : index + %rowc = arith.minui %row, %posi : index + %kh = vector.load %k[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> + %kf = arith.extf %kh : vector<4xf16> to vector<4xf32> + %pr = arith.mulf %kf, %qs : vector<4xf32> + %pl = vector.reduction , %pr : vector<4xf32> into f32 + %sc = gpu.subgroup_reduce add %pl : (f32) -> f32 + %live = arith.cmpi ule, %row, %posi : index + %scm = arith.select %live, %sc, %neg : f32 + %mine = arith.cmpi eq, %cc, %l : index + %m2 = arith.select %mine, %scm, %m : f32 + scf.yield %m2 : f32 + } + %bm = gpu.subgroup_reduce maxnumf %my : (f32) -> f32 + %Mn = arith.maxnumf %M, %bm : f32 + %dm = arith.subf %M, %Mn : f32 + %ms = math.exp %dm : f32 + %dp = arith.subf %my, %Mn : f32 + %p = math.exp %dp : f32 + %bs = gpu.subgroup_reduce add %p : (f32) -> f32 + %Ss = arith.mulf %S, %ms : f32 + %Sn = arith.addf %Ss, %bs : f32 + %msv = vector.broadcast %ms : f32 to vector<4xf32> + %o1 = arith.mulf %o, %msv : vector<4xf32> + %o2 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%oa = %o1) -> (vector<4xf32>) { + %row = arith.addi %r0, %cc : index + %rowc = arith.minui %row, %posi : index + %vh = vector.load %v[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> + %vf = arith.extf %vh : vector<4xf16> to vector<4xf32> + %cci = arith.index_cast %cc : index to i32 + %pc, %pv = gpu.shuffle idx %p, %cci, %c32i : f32 + %pcv = vector.broadcast %pc : f32 to vector<4xf32> + %on = vector.fma %vf, %pcv, %oa : vector<4xf32> + scf.yield %on : vector<4xf32> + } + scf.yield %Mn, %Sn, %o2 : f32, f32, vector<4xf32> + } + vector.store %st#2, %part[%hi, %wi, %l4] : memref, vector<4xf32> + %lane0 = arith.cmpi eq, %l, %c0 : index + scf.if %lane0 { + memref.store %st#0, %part[%hi, %wi, %c128] : memref + memref.store %st#1, %part[%hi, %wi, %c129] : memref + } + macro.yield %h : i32 + }; + } + } + } + return; +} + +/// Merges the first `parts` parts of `vec_attention_parts` for each head of Q, as llama.cpp's +/// kernel_flash_attn_ext_vec_reduce. A block of 4 SIMD groups does one head: each lane weighs up to 4 parts, +/// and the SIMD groups add them up for 4 values of the head at a time. +fn vec_attention_merge(out : &mut Tensor, part : &Tensor, parts : i32, q_heads : i32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + let _d = mlir!( threads : 128, inputs : (%out = out : memref, %part diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/context/vx/ctx16384.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/context/vx/ctx16384.txt new file mode 100644 index 0000000..f6748f0 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/context/vx/ctx16384.txt @@ -0,0 +1,902 @@ +//===- model.vx - Qwen app --------------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// One token of a Qwen2 or Qwen3 MoE decoder on the GPU, with the kernels of `std::nn`. `State` +// holds every tensor that a token writes, and the KV cache. It is made once, before the first +// token, so the token loop allocates nothing. +import core::convert; +import core::num; +import std::nn; +import std::vec; +import qwen::attention; +import qwen::products; +import qwen::q6; +import qwen::weights; + +/// The keys and the values of every position so far, for one layer: [max_seq, kv_heads, head_dim]. +/// They are f16, half the memory of f32. The kernels compute in f32, and round only what they +/// store here. +struct Cache { + k : Tensor, + v : Tensor, +} + +/// The tensors of a mixture-of-experts layer: the router's score of each expert, the chosen +/// experts and their weights, and the SwiGLU output of each chosen expert, [experts_per_token, +/// moe_intermediate_size]. +struct Experts { + router_logits : Tensor, + ids : Tensor, + weights : Tensor, + mlp : Tensor, +} + +/// The tensors that a token writes, in GPU memory, and one `Cache` for each layer. `cos` and `sin` +/// are [max_seq, head_dim / 2]. +struct State { + max_seq : i32, + x : Tensor, + xn : Tensor, + q : Tensor, + k : Tensor, + v : Tensor, + q_turned : Tensor, + attended : Tensor, + attention_parts : Tensor, + vec_parts : Tensor, + mlp : Tensor, + experts : Experts, + logits : Tensor, + cos : Tensor, + sin : Tensor, + caches : Vec, +} + +/// The state for up to `max_seq` positions. The angles of RoPE are computed in f64, as in +/// `reference.py`, and rounded to f32 once. +fn new_state(c : &Config, max_seq : i32) -> State { + assert(max_seq > 0 && max_seq <= c.max_positions, "max_seq must be between 1 and the max_positions of the model"); + let half = c.head_dim / 2; + let mut hcos = Tensor([max_seq, half]); + let mut hsin = Tensor([max_seq, half]); + for p in 0..max_seq { + for i in 0..half { + let angle = f64::from(p) / f64::powf(c.rope_theta, f64::from(2 * i) / f64::from(c.head_dim)); + hcos[p][i] = f64::cos(angle) as f32; + hsin[p][i] = f64::sin(angle) as f32; + } + } + // A dense model uses none of the tensors of the experts, so one value each is enough. + let experts = i32::max(c.num_experts, 1); + let chosen = i32::max(c.experts_per_token, 1); + let moe_inter = i32::max(c.moe_intermediate_size, 1); + // The flash attention of a prompt reads the cache in blocks of 64 positions. + let rows = (max_seq + 63) / 64 * 64; + let mut caches = Vec::new(); + for l in 0..c.num_layers { + caches.push(Cache { + k: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + }); + } + return State { + max_seq: max_seq, + x: transfer(Tensor([c.hidden_size]), Memory::HBM), + xn: transfer(Tensor([c.hidden_size]), Memory::HBM), + q: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + k: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + q_turned: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attended: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attention_parts: transfer(split_attention_scratch(max_seq, c.num_q_heads, c.num_kv_heads, c.head_dim), Memory::HBM), + vec_parts: transfer(vec_attention_scratch(c.num_q_heads), Memory::HBM), + mlp: transfer(Tensor([c.intermediate_size]), Memory::HBM), + experts: Experts { + router_logits: transfer(Tensor([experts]), Memory::HBM), + ids: transfer(Tensor([chosen]), Memory::HBM), + weights: transfer(Tensor([chosen]), Memory::HBM), + mlp: transfer(Tensor([chosen, moe_inter]), Memory::HBM), + }, + logits: transfer(Tensor([c.vocab_size]), Memory::HBM), + cos: transfer(hcos, Memory::HBM), + sin: transfer(hsin, Memory::HBM), + caches: caches, + }; +} + +/// y = m x, with the kernel for the dtype of `m`, which has `rows` x `cols` weights. +fn matvec(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U6 { + matvec_q6(y, &m.codes, &m.high, &m.group_scales, x, rows, cols); + } else if m.dtype == U4 { + nn_matvec_q4(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x. +fn matvec_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_matvec_q4_add(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_add(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec_add(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x, for x of [heads, head_dim]. +fn matvec_heads_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, heads : i32, head_dim : i32) -> void { + if m.dtype == U4 { + matvec_q4_heads_add_blocks(y, &m.codes, &m.group_scales, x, rows, heads, head_dim); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_heads_add(y, &m.codes, &m.scales, x, rows, heads, head_dim); + } else { + nn_matvec_heads_add(y, &m.bf16, x, rows, heads, head_dim); + } + return; +} + +/// The Q, K and V of x: m x + b, split by heads. +fn qkv(q : &mut Tensor, k : &mut Tensor, v : &mut Tensor, m : &WeightMatrix, b : &Tensor, x : &Tensor, c : &Config) -> void { + if m.dtype == U4 { + qkv_q4_blocks(q, k, v, &m.codes, &m.group_scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } else if m.dtype == F8E4M3 { + nn_qkv_fp8(q, k, v, &m.codes, &m.scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } else { + nn_qkv(q, k, v, &m.bf16, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } + return; +} + +/// The SwiGLU of a dense MLP, for the gate rows and then the up rows of `m`. +fn swiglu(out : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_swiglu_q4(out, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_swiglu_fp8(out, &m.codes, &m.scales, x, rows, cols); + } else { + nn_swiglu(out, &m.bf16, x, rows, cols); + } + return; +} + +/// The mixture of experts of a layer: the router chooses experts_per_token experts and their +/// weights, and x gets the sum of their outputs for xn, each times its weight. +fn add_experts(e : &mut Experts, x : &mut Tensor, xn : &Tensor, layer : &Layer, c : &Config) -> void { + let k = c.experts_per_token; + let inter = c.moe_intermediate_size; + nn_matvec(&mut e.router_logits, &layer.router, xn, c.num_experts, c.hidden_size); + nn_top_k(&mut e.ids, &mut e.weights, &e.router_logits, c.num_experts, k); + let gate_up = &layer.gate_up; + let down = &layer.down; + if gate_up.dtype == U4 { + moe_swiglu_q4_blocks(&mut e.mlp, &gate_up.codes, &gate_up.group_scales, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + moe_down_q4_add_blocks(x, &down.codes, &down.group_scales, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + } else { + assert(gate_up.dtype == BF16, "the experts of a mixture-of-experts model must be bf16 or Q4_0"); + nn_moe_swiglu(&mut e.mlp, &gate_up.bf16, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + nn_moe_down_add(x, &down.bf16, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + } + return; +} + +/// Runs the token in `token` at position `pos` through every layer. The hidden state of the +/// token is then in `s.x`, and its keys and values are in the caches. +fn run_layers(w : &Weights, s : &mut State, token : &Tensor, pos : i32) -> void { + let c = &w.config; + let eps = c.rms_norm_eps as f32; + assert(pos >= 0 && pos < s.max_seq, "the position is past the end of the KV cache"); + nn_embed(&mut s.x, &w.embed, token, c.hidden_size); + let mut l = 0; + for cache in s.caches.iter_mut() { + let layer = &w.layers[l]; + nn_rms_norm(&mut s.xn, &s.x, &layer.attn_norm, c.hidden_size, eps); + qkv(&mut s.q, &mut s.k, &mut s.v, &layer.qkv, &layer.qkv_bias, &s.xn, c); + if c.qk_norm { + norm_rope_and_store(&mut s.q_turned, &mut cache.k, &mut cache.v, &s.q, &s.k, &s.v, &layer.q_norm, &layer.k_norm, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.head_dim, eps); + } else { + rope_and_store(&mut s.q_turned, &mut cache.k, &mut cache.v, &s.q, &s.k, &s.v, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } + if c.head_dim == 128 { + vec_attention(&mut s.attended, &mut s.vec_parts, &s.q_turned, &cache.k, &cache.v, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } else { + split_attention(&mut s.attended, &mut s.attention_parts, &s.q_turned, &cache.k, &cache.v, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } + matvec_heads_add(&mut s.x, &layer.attn_out, &s.attended, c.hidden_size, c.num_q_heads, c.head_dim); + nn_rms_norm(&mut s.xn, &s.x, &layer.mlp_norm, c.hidden_size, eps); + if c.num_experts > 0 { + add_experts(&mut s.experts, &mut s.x, &s.xn, layer, c); + } else { + swiglu(&mut s.mlp, &layer.gate_up, &s.xn, c.intermediate_size, c.hidden_size); + matvec_add(&mut s.x, &layer.down, &s.mlp, c.hidden_size, c.intermediate_size); + } + l = l + 1; + } + return; +} + +/// The logits of the token whose hidden state is in `s.x`, and in `next` the index of the largest +/// one. Both stay in GPU memory. +fn predict(w : &Weights, s : &mut State, next : &mut Tensor) -> void { + let c = &w.config; + nn_rms_norm(&mut s.xn, &s.x, &w.final_norm, c.hidden_size, c.rms_norm_eps as f32); + if c.tied_embeddings { + nn_matvec(&mut s.logits, &w.embed, &s.xn, c.vocab_size, c.hidden_size); + } else { + matvec(&mut s.logits, &w.lm_head, &s.xn, c.vocab_size, c.hidden_size); + } + nn_argmax(next, &s.logits, c.vocab_size); + return; +} +//===- attention.vx - Qwen app ----------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// The attention of one generated token, with the positions split among blocks. This is a copy of +// `nn_attention` and its kernels from `std::nn` on Vx main (vx-lang/Vx#3216), with `split_` in place +// of `nn_` in their names. Vx v0.0.4 has the older `nn_attention`, which has one block for each head +// of Q, so its time grows with the number of positions. Remove this file, and call `nn_attention` +// of `std::nn`, when a Vx release has the new one (#4). +// +// `vec_attention`, for head_dim 128, has the design of llama.cpp's flash attention for one token +// (kernel_flash_attn_ext_vec and kernel_flash_attn_ext_vec_reduce), MIT License, Copyright (c) 2023-2026 +// The ggml authors. scripts/mlir_kernels/decode_attention.py writes its kernels: change that script, not +// the MLIR. +import core::num; +import std::nn; + +/// Attention of the token at position `pos` over rows 0 to `pos` of the KV cache, with a softmax +/// of the scores q . k / sqrt(head_dim). `part` is scratch space from `split_attention_scratch`. +/// +/// The blocks of the first kernel split the positions, 32 to a block below position 640 and 64 from +/// there on. A block serves the 8 heads of Q that share a head of K and V, so it reads each row of +/// the cache once for all 8. A second kernel merges the parts of the blocks for each head. +fn split_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_heads % kv_heads == 0, "split_attention: q_heads must be a multiple of kv_heads"); + assert(head_dim % 32 == 0 && head_dim <= 128, "split_attention: head_dim must be a multiple of 32, and at most 128"); + let mut n_pos = 32; + if pos >= 640 { + n_pos = 64; + } + assert(part.extent(0) >= kv_heads * ((q_heads / kv_heads + 7) / 8) && part.extent(1) >= (pos + n_pos) / n_pos && part.extent(2) >= 8 && part.extent(3) >= head_dim + 2, "split_attention: `part` is too small for this position. Make it with split_attention_scratch"); + if n_pos == 32 { + split_attention_parts_32(part, q, k_cache, v_cache, pos, q_heads, kv_heads, head_dim); + } else { + split_attention_parts_64(part, q, k_cache, v_cache, pos, q_heads, kv_heads, head_dim); + } + split_attention_merge(out, part, pos, n_pos, q_heads, kv_heads, head_dim); + return; +} + +/// Attention of the token at position `pos`, as `split_attention`, for head_dim 128, with the kernels of +/// llama.cpp's flash attention for one token. `vec_attention_parts` splits the blocks of 32 positions among +/// `nwg` SIMD groups for each head of Q: 32 of them, or 64 when each of 32 would have more than 2 blocks. +/// (llama.cpp goes on to 4 SIMD groups of 32 a block, but 128 parts are no faster here: their merge costs what +/// they save.) `vec_attention_merge` then merges the parts. `part` is scratch space from +/// `vec_attention_scratch`. +fn vec_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_heads % kv_heads == 0 && head_dim == 128, "vec_attention: q_heads must be a multiple of kv_heads, and head_dim 128"); + assert(part.extent(0) >= q_heads && part.extent(1) >= 128 && part.extent(2) == 132, "vec_attention: `part` is too small. Make it with vec_attention_scratch"); + let mut nwg = 32; + if 2 * nwg * 32 < pos + 1 { + nwg = nwg * 2; + } + vec_attention_parts(part, q, k_cache, v_cache, pos, q_heads, q_heads / kv_heads, nwg, 1.0 / (head_dim as f32).sqrt()); + vec_attention_merge(out, part, nwg, q_heads); + return; +} + +/// The scratch space of `vec_attention`, on the CPU: up to 128 parts for each head of Q, each the sum of V +/// (128 values), the largest score, and the sum of the weights. A part has 132 values, so that each starts +/// at a multiple of 16 bytes. +fn vec_attention_scratch(q_heads : i32) -> Tensor { + return Tensor([q_heads, 128, 132]); +} + +/// The parts of `vec_attention`, as llama.cpp's kernel_flash_attn_ext_vec. Block (h, w) is a SIMD group for +/// query head h. It does the blocks of 32 positions w, w + nwg, w + 2 nwg, ... up to `pos`, and writes +/// part[h][w]. Lane l owns values 4 l to 4 l + 3 of the head, so that the 32 lanes read a row of K or V in +/// one 256-byte load. For each row, the lanes add up their parts of q . k; then each lane keeps the score +/// of one row, and the lanes take the weights of the rows from each other for the sum of V. A part is the +/// sum of V, not divided, then the largest score and the sum of the weights. +fn vec_attention_parts(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, group : i32, nwg : i32, scale : f32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for w in 0..nwg across blocks { + let g = h / group; + let _d = mlir!( threads : 32, inputs : (%part = part : memref, %q = q : memref, %k3 = k_cache : memref, %v3 = v_cache : memref, %pos = pos : i32, %nwg = nwg : i32, %scale = scale : f32, %h = h : i32, %w = w : i32, %g = g : i32), returns : i32, dialects : ["arith", "memref", "scf", "gpu", "vector", "math"], ensures : [reads_only(q), reads_only(k_cache), reads_only(v_cache), writes_only(part[h][w])]) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %c4 = arith.constant 4 : index + %c32 = arith.constant 32 : index + %c128 = arith.constant 128 : index + %c129 = arith.constant 129 : index + %c32i = arith.constant 32 : i32 + %neg = arith.constant -3.0e38 : f32 + %zero = arith.constant 0.0 : f32 + %vz4 = arith.constant dense<0.0> : vector<4xf32> + %l = gpu.thread_id x + %l4 = arith.muli %l, %c4 : index + %hi = arith.index_cast %h : i32 to index + %wi = arith.index_cast %w : i32 to index + %gi = arith.index_cast %g : i32 to index + %posi = arith.index_cast %pos : i32 to index + %nwgi = arith.index_cast %nwg : i32 to index + %g128 = arith.muli %gi, %c128 : index + %kd = arith.addi %g128, %l4 : index + %P = memref.dim %k3, %c0 : memref + %KH = memref.dim %k3, %c1 : memref + %Wd = arith.muli %KH, %c128 : index + %k = memref.reinterpret_cast %k3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to memref> + %v = memref.reinterpret_cast %v3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to memref> + %qv = vector.load %q[%hi, %l4] {alignment = 16} : memref, vector<4xf32> + %scv = vector.broadcast %scale : f32 to vector<4xf32> + %qs = arith.mulf %qv, %scv : vector<4xf32> + %nkv = arith.addi %posi, %c32 : index + %chunks = arith.divui %nkv, %c32 : index + %st:3 = scf.for %ic = %wi to %chunks step %nwgi iter_args(%M = %neg, %S = %zero, %o = %vz4) -> (f32, f32, vector<4xf32>) { + %r0 = arith.muli %ic, %c32 : index + %my = scf.for %cc = %c0 to %c32 step %c1 iter_args(%m = %neg) -> (f32) { + %row = arith.addi %r0, %cc : index + %rowc = arith.minui %row, %posi : index + %kh = vector.load %k[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> + %kf = arith.extf %kh : vector<4xf16> to vector<4xf32> + %pr = arith.mulf %kf, %qs : vector<4xf32> + %pl = vector.reduction , %pr : vector<4xf32> into f32 + %sc = gpu.subgroup_reduce add %pl : (f32) -> f32 + %live = arith.cmpi ule, %row, %posi : index + %scm = arith.select %live, %sc, %neg : f32 + %mine = arith.cmpi eq, %cc, %l : index + %m2 = arith.select %mine, %scm, %m : f32 + scf.yield %m2 : f32 + } + %bm = gpu.subgroup_reduce maxnumf %my : (f32) -> f32 + %Mn = arith.maxnumf %M, %bm : f32 + %dm = arith.subf %M, %Mn : f32 + %ms = math.exp %dm : f32 + %dp = arith.subf %my, %Mn : f32 + %p = math.exp %dp : f32 + %bs = gpu.subgroup_reduce add %p : (f32) -> f32 + %Ss = arith.mulf %S, %ms : f32 + %Sn = arith.addf %Ss, %bs : f32 + %msv = vector.broadcast %ms : f32 to vector<4xf32> + %o1 = arith.mulf %o, %msv : vector<4xf32> + %o2 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%oa = %o1) -> (vector<4xf32>) { + %row = arith.addi %r0, %cc : index + %rowc = arith.minui %row, %posi : index + %vh = vector.load %v[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> + %vf = arith.extf %vh : vector<4xf16> to vector<4xf32> + %cci = arith.index_cast %cc : index to i32 + %pc, %pv = gpu.shuffle idx %p, %cci, %c32i : f32 + %pcv = vector.broadcast %pc : f32 to vector<4xf32> + %on = vector.fma %vf, %pcv, %oa : vector<4xf32> + scf.yield %on : vector<4xf32> + } + scf.yield %Mn, %Sn, %o2 : f32, f32, vector<4xf32> + } + vector.store %st#2, %part[%hi, %wi, %l4] : memref, vector<4xf32> + %lane0 = arith.cmpi eq, %l, %c0 : index + scf.if %lane0 { + memref.store %st#0, %part[%hi, %wi, %c128] : memref + memref.store %st#1, %part[%hi, %wi, %c129] : memref + } + macro.yield %h : i32 + }; + } + } + } + return; +} + +/// Merges the first `parts` parts of `vec_attention_parts` for each head of Q, as llama.cpp's +/// kernel_flash_attn_ext_vec_reduce. A block of 4 SIMD groups does one head: each lane weighs up to 4 parts, +/// and the SIMD groups add them up for 4 values of the head at a time. +fn vec_attention_merge(out : &mut Tensor, part : &Tensor, parts : i32, q_heads : i32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + let _d = mlir!( threads : 128, inputs : (%out = out : memref, %part = part : memref, %parts = parts : i32, %h = h : i32), returns : i32, dialects : ["arith", "memref", "scf", "gpu", "vector", "math"], ensures : [reads_only(part), writes_only(out[h])]) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %c2 = arith.constant 2 : index + %c3 = arith.constant 3 : index + %c4 = arith.constant 4 : index + %c16 = arith.constant 16 : index + %c32 = arith.constant 32 : index + %c64 = arith.constant 64 : index + %c96 = arith.constant 96 : index + %c128 = arith.constant 128 : index + %c129 = arith.constant 129 : index + %neg = arith.constant -3.0e38 : f32 + %zero = arith.constant 0.0 : f32 + %one = arith.constant 1.0 : f32 + %tid = gpu.thread_id x + %sg = arith.divui %tid, %c32 : index + %l = arith.remui %tid, %c32 : index + %hi = arith.index_cast %h : i32 to index + %np = arith.index_cast %parts : i32 to index + %last = arith.subi %np, %c1 : index + %p0 = arith.addi %l, %c0 : index + %live0 = arith.cmpi ult, %p0, %np : index + %pc0 = arith.minui %p0, %last : index + %mr0 = memref.load %part[%hi, %pc0, %c128] : memref + %m0 = arith.select %live0, %mr0, %neg : f32 + %p1 = arith.addi %l, %c32 : index + %live1 = arith.cmpi ult, %p1, %np : index + %pc1 = arith.minui %p1, %last : index + %mr1 = memref.load %part[%hi, %pc1, %c128] : memref + %m1 = arith.select %live1, %mr1, %neg : f32 + %p2 = arith.addi %l, %c64 : index + %live2 = arith.cmpi ult, %p2, %np : index + %pc2 = arith.minui %p2, %last : index + %mr2 = memref.load %part[%hi, %pc2, %c128] : memref + %m2 = arith.select %live2, %mr2, %neg : f32 + %p3 = arith.addi %l, %c96 : index + %live3 = arith.cmpi ult, %p3, %np : index + %pc3 = arith.minui %p3, %last : index + %mr3 = memref.load %part[%hi, %pc3, %c128] : memref + %m3 = arith.select %live3, %mr3, %neg : f32 + %m01 = arith.maxnumf %m0, %m1 : f32 + %m23 = arith.maxnumf %m2, %m3 : f32 + %mx = arith.maxnumf %m01, %m23 : f32 + %big = gpu.subgroup_reduce maxnumf %mx : (f32) -> f32 + %dm0 = arith.subf %m0, %big : f32 + %w0 = math.exp %dm0 : f32 + %s0 = memref.load %part[%hi, %pc0, %c129] : memref + %ws0 = arith.mulf %w0, %s0 : f32 + %wv0 = vector.broadcast %w0 : f32 to vector<4xf32> + %dm1 = arith.subf %m1, %big : f32 + %w1 = math.exp %dm1 : f32 + %s1 = memref.load %part[%hi, %pc1, %c129] : memref + %ws1 = arith.mulf %w1, %s1 : f32 + %wv1 = vector.broadcast %w1 : f32 to vector<4xf32> + %dm2 = arith.subf %m2, %big : f32 + %w2 = math.exp %dm2 : f32 + %s2 = memref.load %part[%hi, %pc2, %c129] : memref + %ws2 = arith.mulf %w2, %s2 : f32 + %wv2 = vector.broadcast %w2 : f32 to vector<4xf32> + %dm3 = arith.subf %m3, %big : f32 + %w3 = math.exp %dm3 : f32 + %s3 = memref.load %part[%hi, %pc3, %c129] : memref + %ws3 = arith.mulf %w3, %s3 : f32 + %wv3 = vector.broadcast %w3 : f32 to vector<4xf32> + %t01 = arith.addf %ws0, %ws1 : f32 + %t23 = arith.addf %ws2, %ws3 : f32 + %ts = arith.addf %t01, %t23 : f32 + %total = gpu.subgroup_reduce add %ts : (f32) -> f32 + %inv = arith.divf %one, %total : f32 + %lane0 = arith.cmpi eq, %l, %c0 : index + %sg4 = arith.muli %sg, %c4 : index + %vz4 = arith.constant dense<0.0> : vector<4xf32> + scf.for %n = %c0 to %c128 step %c16 { + %d = arith.addi %n, %sg4 : index + %x0 = vector.load %part[%hi, %pc0, %d] {alignment = 16} : memref, vector<4xf32> + %a0 = vector.fma %x0, %wv0, %vz4 : vector<4xf32> + %x1 = vector.load %part[%hi, %pc1, %d] {alignment = 16} : memref, vector<4xf32> + %a1 = vector.fma %x1, %wv1, %a0 : vector<4xf32> + %x2 = vector.load %part[%hi, %pc2, %d] {alignment = 16} : memref, vector<4xf32> + %a2 = vector.fma %x2, %wv2, %a1 : vector<4xf32> + %x3 = vector.load %part[%hi, %pc3, %d] {alignment = 16} : memref, vector<4xf32> + %a3 = vector.fma %x3, %wv3, %a2 : vector<4xf32> + %e0 = vector.extract %a3[0] : f32 from vector<4xf32> + %r0 = gpu.subgroup_reduce add %e0 : (f32) -> f32 + %o0 = arith.mulf %r0, %inv : f32 + %e1 = vector.extract %a3[1] : f32 from vector<4xf32> + %r1 = gpu.subgroup_reduce add %e1 : (f32) -> f32 + %o1 = arith.mulf %r1, %inv : f32 + %e2 = vector.extract %a3[2] : f32 from vector<4xf32> + %r2 = gpu.subgroup_reduce add %e2 : (f32) -> f32 + %o2 = arith.mulf %r2, %inv : f32 + %e3 = vector.extract %a3[3] : f32 from vector<4xf32> + %r3 = gpu.subgroup_reduce add %e3 : (f32) -> f32 + %o3 = arith.mulf %r3, %inv : f32 + scf.if %lane0 { + %d0 = arith.addi %d, %c0 : index + memref.store %o0, %out[%hi, %d0] : memref + %d1 = arith.addi %d, %c1 : index + memref.store %o1, %out[%hi, %d1] : memref + %d2 = arith.addi %d, %c2 : index + memref.store %o2, %out[%hi, %d2] : memref + %d3 = arith.addi %d, %c3 : index + memref.store %o3, %out[%hi, %d3] : memref + } + } + macro.yield %h : i32 + }; + } + } + return; +} + +/// The scratch space of `split_attention` for positions below `max_seq`, on the CPU. Transfer it to the +/// memory of the other tensors. Each block of positions writes the weighted sum of V for each of its +/// heads, then the largest score and the sum of the weights. +fn split_attention_scratch(max_seq : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> Tensor { + // 20 blocks of 32 positions below position 640, and blocks of 64 positions from there on. + let mut splits = (max_seq + 63) / 64; + if splits < 20 { + splits = 20; + } + return Tensor([kv_heads * ((q_heads / kv_heads + 7) / 8), splits, 8, head_dim + 2]); +} + +/// The parts of `split_attention` for blocks of 32 positions: 4 SIMD groups of 2 heads of Q. +fn split_attention_parts_32(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + let group = q_heads / kv_heads; + let tiles = (group + 7) / 8; + let scale = 1.0 / (head_dim as f32).sqrt(); + spawn on(Topology::Device) { + for gt in 0..kv_heads * tiles across blocks { + for c in 0..(pos + 32) / 32 across blocks { + let mut w = unsafe { Tensor::uninit() }; + let mut top = unsafe { + Tensor::uninit() + }; + let mut sums = unsafe { + Tensor::uninit() + }; + let g = gt / tiles; + let base = g * group + (gt - g * tiles) * 8; + let left = group - (gt - g * tiles) * 8; + for s in 0..4 across subgroups { + let first = base + s * 2; + let mut heads = left - s * 2; + if heads > 2 { + heads = 2; + } + // A head past the last one of the group reads the last one again, and its sums go nowhere. + let mut h0 = first + 0; + if 0 >= heads { + h0 = first + heads - 1; + } + let mut h1 = first + 1; + if 1 >= heads { + h1 = first + heads - 1; + } + for l in 0..32 across lanes(32) { + // The scores of the position of the lane, for each head. A position past `pos` reads row + // `pos`, and its score is -3e38. + let mut t0 = c * 32 + 0 + l; + if t0 > pos { + t0 = pos; + } + let mut dot0_0 : f32 = 0.0; + let mut dot0_1 : f32 = 0.0; + for d in 0..head_dim { + let k0 = k_cache[t0][g][d] as f32; + let q0 = q[h0][d]; + dot0_0 = dot0_0 + q0 * k0; + let q1 = q[h1][d]; + dot0_1 = dot0_1 + q1 * k0; + } + let mut s0_0 : f32 = -3.0e38; + if c * 32 + 0 + l <= pos { + s0_0 = dot0_0 * scale; + } + w[s][0][0 + l] = s0_0; + top[s][0][l] = s0_0; + let mut s0_1 : f32 = -3.0e38; + if c * 32 + 0 + l <= pos { + s0_1 = dot0_1 * scale; + } + w[s][1][0 + l] = s0_1; + top[s][1][l] = s0_1; + } + let big0 = lanes::max(&top[s][0], 32); + let big1 = lanes::max(&top[s][1], 32); + // The weight of each position, as exp(score - the largest score of the block). + for l in 0..32 across lanes(32) { + let e0_0 = (w[s][0][0 + l] - big0).fast_exp(); + w[s][0][0 + l] = e0_0; + sums[s][0][l] = e0_0; + let e0_1 = (w[s][1][0 + l] - big1).fast_exp(); + w[s][1][0 + l] = e0_1; + sums[s][1][l] = e0_1; + } + let total0 = lanes::sum(&sums[s][0], 32); + let total1 = lanes::sum(&sums[s][1], 32); + // The weighted sum of the rows of V. Lane l takes values l, l + 32, l + 64 and l + 96. + for l in 0..32 across lanes(32) { + let mut acc0_0 : f32 = 0.0; + let mut acc0_1 : f32 = 0.0; + let mut acc0_2 : f32 = 0.0; + let mut acc0_3 : f32 = 0.0; + let mut acc1_0 : f32 = 0.0; + let mut acc1_1 : f32 = 0.0; + let mut acc1_2 : f32 = 0.0; + let mut acc1_3 : f32 = 0.0; + // With head_dim below 128, values past it read others again, and their sums go nowhere. + let d0 = (0 + l) % head_dim; + let d1 = (32 + l) % head_dim; + let d2 = (64 + l) % head_dim; + let d3 = (96 + l) % head_dim; + let mut last = pos - c * 32; + if last > 31 { + last = 31; + } + for t in 0..last + 1 { + let row = c * 32 + t; + let v0 = v_cache[row][g][d0] as f32; + let v1 = v_cache[row][g][d1] as f32; + let v2 = v_cache[row][g][d2] as f32; + let v3 = v_cache[row][g][d3] as f32; + let w0 = w[s][0][t]; + acc0_0 = acc0_0 + w0 * v0; + acc0_1 = acc0_1 + w0 * v1; + acc0_2 = acc0_2 + w0 * v2; + acc0_3 = acc0_3 + w0 * v3; + let w1 = w[s][1][t]; + acc1_0 = acc1_0 + w1 * v0; + acc1_1 = acc1_1 + w1 * v1; + acc1_2 = acc1_2 + w1 * v2; + acc1_3 = acc1_3 + w1 * v3; + } + if 0 < heads { + if 0 < head_dim { + part[gt][c][s * 2 + 0][0 + l] = acc0_0; + } + if 32 < head_dim { + part[gt][c][s * 2 + 0][32 + l] = acc0_1; + } + if 64 < head_dim { + part[gt][c][s * 2 + 0][64 + l] = acc0_2; + } + if 96 < head_dim { + part[gt][c][s * 2 + 0][96 + l] = acc0_3; + } + } + if 1 < heads { + if 0 < head_dim { + part[gt][c][s * 2 + 1][0 + l] = acc1_0; + } + if 32 < head_dim { + part[gt][c][s * 2 + 1][32 + l] = acc1_1; + } + if 64 < head_dim { + part[gt][c][s * 2 + 1][64 + l] = acc1_2; + } + if 96 < head_dim { + part[gt][c][s * 2 + 1][96 + l] = acc1_3; + } + } + } + if 0 < heads { + part[gt][c][s * 2 + 0][head_dim] = big0; + part[gt][c][s * 2 + 0][head_dim + 1] = total0; + } + if 1 < heads { + part[gt][c][s * 2 + 1][head_dim] = big1; + part[gt][c][s * 2 + 1][head_dim + 1] = total1; + } + } + } + } + } + return; +} + +/// The parts of `split_attention` for blocks of 64 positions: 2 SIMD groups of 4 heads of Q. +fn split_attention_parts_64(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + let group = q_heads / kv_heads; + let tiles = (group + 7) / 8; + let scale = 1.0 / (head_dim as f32).sqrt(); + spawn on(Topology::Device) { + for gt in 0..kv_heads * tiles across blocks { + for c in 0..(pos + 64) / 64 across blocks { + let mut w = unsafe { Tensor::uninit() }; + let mut top = unsafe { + Tensor::uninit() + }; + let mut sums = unsafe { + Tensor::uninit() + }; + let g = gt / tiles; + let base = g * group + (gt - g * tiles) * 8; + let left = group - (gt - g * tiles) * 8; + for s in 0..2 across subgroups { + let first = base + s * 4; + let mut heads = left - s * 4; + if heads > 4 { + heads = 4; + } + // A head past the last one of the group reads the last one again, and its sums go nowhere. + let mut h0 = first + 0; + if 0 >= heads { + h0 = first + heads - 1; + } + let mut h1 = first + 1; + if 1 >= heads { + h1 = first + heads - 1; + } + let mut h2 = first + 2; + if 2 >= heads { + h2 = first + heads - 1; + } + let mut h3 = first + 3; + if 3 >= heads { + h3 = first + heads - 1; + } + for l in 0..32 across lanes(32) { + // The scores of each of the 2 positions of the lane, for each head. A position past `pos` reads row + // `pos`, and its score is -3e38. + let mut t0 = c * 64 + 0 + l; + if t0 > pos { + t0 = pos; + } + let mut dot0_0 : f32 = 0.0; + let mut dot0_1 : f32 = 0.0; + let mut dot0_2 : f32 = 0.0; + let mut dot0_3 : f32 = 0.0; + let mut t1 = c * 64 + 32 + l; + if t1 > pos { + t1 = pos; + } + let mut dot1_0 : f32 = 0.0; + let mut dot1_1 : f32 = 0.0; + let mut dot1_2 : f32 = 0.0; + let mut dot1_3 : f32 = 0.0; + for d in 0..head_dim { + let k0 = k_cache[t0][g][d] as f32; + let k1 = k_cache[t1][g][d] as f32; + let q0 = q[h0][d]; + dot0_0 = dot0_0 + q0 * k0; + dot1_0 = dot1_0 + q0 * k1; + let q1 = q[h1][d]; + dot0_1 = dot0_1 + q1 * k0; + dot1_1 = dot1_1 + q1 * k1; + let q2 = q[h2][d]; + dot0_2 = dot0_2 + q2 * k0; + dot1_2 = dot1_2 + q2 * k1; + let q3 = q[h3][d]; + dot0_3 = dot0_3 + q3 * k0; + dot1_3 = dot1_3 + q3 * k1; + } + let mut s0_0 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_0 = dot0_0 * scale; + } + w[s][0][0 + l] = s0_0; + let mut s1_0 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_0 = dot1_0 * scale; + } + w[s][0][32 + l] = s1_0; + top[s][0][l] = s0_0.max(s1_0); + let mut s0_1 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_1 = dot0_1 * scale; + } + w[s][1][0 + l] = s0_1; + let mut s1_1 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_1 = dot1_1 * scale; + } + w[s][1][32 + l] = s1_1; + top[s][1][l] = s0_1.max(s1_1); + let mut s0_2 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_2 = dot0_2 * scale; + } + w[s][2][0 + l] = s0_2; + let mut s1_2 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_2 = dot1_2 * scale; + } + w[s][2][32 + l] = s1_2; + top[s][2][l] = s0_2.max(s1_2); + let mut s0_3 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_3 = dot0_3 * scale; + } + w[s][3][0 + l] = s0_3; + let mut s1_3 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_3 = dot1_3 * scale; + } + w[s][3][32 + l] = s1_3; + top[s][3][l] = s0_3.max(s1_3); + } + let big0 = lanes::max(&top[s][0], 32); + let big1 = lanes::max(&top[s][1], 32); + let big2 = lanes::max(&top[s][2], 32); + let big3 = lanes::max(&top[s][3], 32); + // The weight of each position, as exp(score - the largest score of the block). + for l in 0..32 across lanes(32) { + let e0_0 = (w[s][0][0 + l] - big0).fast_exp(); + w[s][0][0 + l] = e0_0; + let e1_0 = (w[s][0][32 + l] - big0).fast_exp(); + w[s][0][32 + l] = e1_0; + sums[s][0][l] = e0_0 + e1_0; + let e0_1 = (w[s][1][0 + l] - big1).fast_exp(); + w[s][1][0 + l] = e0_1; + let e1_1 = (w[s][1][32 + l] - big1).fast_exp(); + w[s][1][32 + l] = e1_1; + sums[s][1][l] = e0_1 + e1_1; + let e0_2 = (w[s][2][0 + l] - big2).fast_exp(); + w[s][2][0 + l] = e0_2; + let e1_2 = (w[s][2][32 + l] - big2).fast_exp(); + w[s][2][32 + l] = e1_2; + sums[s][2][l] = e0_2 + e1_2; + let e0_3 = (w[s][3][0 + l] - big3).fast_exp(); + w[s][3][0 + l] = e0_3; + let e1_3 = (w[s][3][32 + l] - big3).fast_exp(); + w[s][3][32 + l] = e1_3; + sums[s][3][l] = e0_3 + e1_3; + } + let total0 = lanes::sum(&sums[s][0], 32); + let total1 = lanes::sum(&sums[s][1], 32); + let total2 = lanes::sum(&sums[s][2], 32); + let total3 = lanes::sum(&sums[s][3], 32); + // The weighted sum of the rows of V. Lane l takes values l, l + 32, l + 64 and l + 96. + for l in 0..32 across lanes(32) { + let mut acc0_0 : f32 = 0.0; + let mut acc0_1 : f32 = 0.0; + let mut acc0_2 : f32 = 0.0; + let mut acc0_3 : f32 = 0.0; + let mut acc1_0 : f32 = 0.0; + let mut acc1_1 : f32 = 0.0; + let mut acc1_2 : f32 = 0.0; + let mut acc1_3 : f32 = 0.0; + let mut acc2_0 : f32 = 0.0; + let mut acc2_1 : f32 = 0.0; + let mut acc2_2 : f32 = 0.0; + let mut acc2_3 : f32 = 0.0; + let mut acc3_0 : f32 = 0.0; + let mut acc3_1 : f32 = 0.0; + let mut acc3_2 : f32 = 0.0; + let mut acc3_3 : f32 = 0.0; + // With head_dim below 128, values past it read others again, and their sums go nowhere. + let d0 = (0 + l) % head_dim; + let d1 = (32 + l) % head_dim; + let d2 = (64 + l) % head_dim; + let d3 = (96 + l) % head_dim; + let mut last = pos - c * 64; + if last > 63 { + last = 63; + } + for t in 0..last + 1 { + let row = c * 64 + t; + let v0 = v_cache[row][g][d0] as f32; + let v1 = v_cache[row][g][d1] as f32; + let v2 = v_cache[row][g][d2] as f32; + let v3 = v_cache[row][g][d3] as f32; + let w0 = w[s][0][t]; + acc0_0 = acc0_0 + w0 * v0; + acc0_1 = acc0_1 + w0 * v1; + acc0_2 = acc0_2 + w0 * v2; + acc0_3 = acc0_3 + w0 * v3; + let w1 = w[s][1][t]; + acc1_0 = acc1_0 + w1 * v0; + acc1_1 = acc1_1 + w1 * v1; + acc1_2 = acc1_2 + w1 * v2; + acc1_3 = acc1_3 + w1 * v3; + let w2 = w[s][2][t]; + acc2_0 = acc2_0 + w2 * v0; + acc2_1 = acc2_1 + w2 * v1; + acc2_2 = acc2_2 + w2 * v2; + acc2_3 = acc2_3 + w2 * v3; + let w3 = w[s][3][t]; + acc3_0 = acc3_0 + w3 * v0; + acc3_1 = acc3_1 + w3 * v1; + acc3_2 = acc3_2 + w3 * v2; + acc3_3 = acc3_3 + w3 * v3 \ No newline at end of file diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/context/vx/ctx2048.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/context/vx/ctx2048.txt new file mode 100644 index 0000000..dd56539 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/context/vx/ctx2048.txt @@ -0,0 +1,138 @@ +//===- model.vx - Qwen app --------------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// One token of a Qwen2 or Qwen3 MoE decoder on the GPU, with the kernels of `std::nn`. `State` +// holds every tensor that a token writes, and the KV cache. It is made once, before the first +// token, so the token loop allocates nothing. +import core::convert; +import core::num; +import std::nn; +import std::vec; +import qwen::attention; +import qwen::products; +import qwen::q6; +import qwen::weights; + +/// The keys and the values of every position so far, for one layer: [max_seq, kv_heads, head_dim]. +/// They are f16, half the memory of f32. The kernels compute in f32, and round only what they +/// store here. +struct Cache { + k : Tensor, + v : Tensor, +} + +/// The tensors of a mixture-of-experts layer: the router's score of each expert, the chosen +/// experts and their weights, and the SwiGLU output of each chosen expert, [experts_per_token, +/// moe_intermediate_size]. +struct Experts { + router_logits : Tensor, + ids : Tensor, + weights : Tensor, + mlp : Tensor, +} + +/// The tensors that a token writes, in GPU memory, and one `Cache` for each layer. `cos` and `sin` +/// are [max_seq, head_dim / 2]. +struct State { + max_seq : i32, + x : Tensor, + xn : Tensor, + q : Tensor, + k : Tensor, + v : Tensor, + q_turned : Tensor, + attended : Tensor, + attention_parts : Tensor, + vec_parts : Tensor, + mlp : Tensor, + experts : Experts, + logits : Tensor, + cos : Tensor, + sin : Tensor, + caches : Vec, +} + +/// The state for up to `max_seq` positions. The angles of RoPE are computed in f64, as in +/// `reference.py`, and rounded to f32 once. +fn new_state(c : &Config, max_seq : i32) -> State { + assert(max_seq > 0 && max_seq <= c.max_positions, "max_seq must be between 1 and the max_positions of the model"); + let half = c.head_dim / 2; + let mut hcos = Tensor([max_seq, half]); + let mut hsin = Tensor([max_seq, half]); + for p in 0..max_seq { + for i in 0..half { + let angle = f64::from(p) / f64::powf(c.rope_theta, f64::from(2 * i) / f64::from(c.head_dim)); + hcos[p][i] = f64::cos(angle) as f32; + hsin[p][i] = f64::sin(angle) as f32; + } + } + // A dense model uses none of the tensors of the experts, so one value each is enough. + let experts = i32::max(c.num_experts, 1); + let chosen = i32::max(c.experts_per_token, 1); + let moe_inter = i32::max(c.moe_intermediate_size, 1); + // The flash attention of a prompt reads the cache in blocks of 64 positions. + let rows = (max_seq + 63) / 64 * 64; + let mut caches = Vec::new(); + for l in 0..c.num_layers { + caches.push(Cache { + k: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + }); + } + return State { + max_seq: max_seq, + x: transfer(Tensor([c.hidden_size]), Memory::HBM), + xn: transfer(Tensor([c.hidden_size]), Memory::HBM), + q: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + k: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + q_turned: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attended: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attention_parts: transfer(split_attention_scratch(max_seq, c.num_q_heads, c.num_kv_heads, c.head_dim), Memory::HBM), + vec_parts: transfer(vec_attention_scratch(c.num_q_heads), Memory::HBM), + mlp: transfer(Tensor([c.intermediate_size]), Memory::HBM), + experts: Experts { + router_logits: transfer(Tensor([experts]), Memory::HBM), + ids: transfer(Tensor([chosen]), Memory::HBM), + weights: transfer(Tensor([chosen]), Memory::HBM), + mlp: transfer(Tensor([chosen, moe_inter]), Memory::HBM), + }, + logits: transfer(Tensor([c.vocab_size]), Memory::HBM), + cos: transfer(hcos, Memory::HBM), + sin: transfer(hsin, Memory::HBM), + caches: caches, + }; +} + +/// y = m x, with the kernel for the dtype of `m`, which has `rows` x `cols` weights. +fn matvec(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U6 { + matvec_q6(y, &m.codes, &m.high, &m.group_scales, x, rows, cols); + } else if m.dtype == U4 { + nn_matvec_q4(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x. +fn matvec_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_matvec_q4_add(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_add(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec_add(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x, for x of [heads, head_dim]. +fn matvec_heads_add(y : \ No newline at end of file diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/context/vx/ctx32768.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/context/vx/ctx32768.txt new file mode 100644 index 0000000..68a31d9 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/context/vx/ctx32768.txt @@ -0,0 +1,1975 @@ +//===- model.vx - Qwen app --------------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// One token of a Qwen2 or Qwen3 MoE decoder on the GPU, with the kernels of `std::nn`. `State` +// holds every tensor that a token writes, and the KV cache. It is made once, before the first +// token, so the token loop allocates nothing. +import core::convert; +import core::num; +import std::nn; +import std::vec; +import qwen::attention; +import qwen::products; +import qwen::q6; +import qwen::weights; + +/// The keys and the values of every position so far, for one layer: [max_seq, kv_heads, head_dim]. +/// They are f16, half the memory of f32. The kernels compute in f32, and round only what they +/// store here. +struct Cache { + k : Tensor, + v : Tensor, +} + +/// The tensors of a mixture-of-experts layer: the router's score of each expert, the chosen +/// experts and their weights, and the SwiGLU output of each chosen expert, [experts_per_token, +/// moe_intermediate_size]. +struct Experts { + router_logits : Tensor, + ids : Tensor, + weights : Tensor, + mlp : Tensor, +} + +/// The tensors that a token writes, in GPU memory, and one `Cache` for each layer. `cos` and `sin` +/// are [max_seq, head_dim / 2]. +struct State { + max_seq : i32, + x : Tensor, + xn : Tensor, + q : Tensor, + k : Tensor, + v : Tensor, + q_turned : Tensor, + attended : Tensor, + attention_parts : Tensor, + vec_parts : Tensor, + mlp : Tensor, + experts : Experts, + logits : Tensor, + cos : Tensor, + sin : Tensor, + caches : Vec, +} + +/// The state for up to `max_seq` positions. The angles of RoPE are computed in f64, as in +/// `reference.py`, and rounded to f32 once. +fn new_state(c : &Config, max_seq : i32) -> State { + assert(max_seq > 0 && max_seq <= c.max_positions, "max_seq must be between 1 and the max_positions of the model"); + let half = c.head_dim / 2; + let mut hcos = Tensor([max_seq, half]); + let mut hsin = Tensor([max_seq, half]); + for p in 0..max_seq { + for i in 0..half { + let angle = f64::from(p) / f64::powf(c.rope_theta, f64::from(2 * i) / f64::from(c.head_dim)); + hcos[p][i] = f64::cos(angle) as f32; + hsin[p][i] = f64::sin(angle) as f32; + } + } + // A dense model uses none of the tensors of the experts, so one value each is enough. + let experts = i32::max(c.num_experts, 1); + let chosen = i32::max(c.experts_per_token, 1); + let moe_inter = i32::max(c.moe_intermediate_size, 1); + // The flash attention of a prompt reads the cache in blocks of 64 positions. + let rows = (max_seq + 63) / 64 * 64; + let mut caches = Vec::new(); + for l in 0..c.num_layers { + caches.push(Cache { + k: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + }); + } + return State { + max_seq: max_seq, + x: transfer(Tensor([c.hidden_size]), Memory::HBM), + xn: transfer(Tensor([c.hidden_size]), Memory::HBM), + q: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + k: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + q_turned: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attended: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attention_parts: transfer(split_attention_scratch(max_seq, c.num_q_heads, c.num_kv_heads, c.head_dim), Memory::HBM), + vec_parts: transfer(vec_attention_scratch(c.num_q_heads), Memory::HBM), + mlp: transfer(Tensor([c.intermediate_size]), Memory::HBM), + experts: Experts { + router_logits: transfer(Tensor([experts]), Memory::HBM), + ids: transfer(Tensor([chosen]), Memory::HBM), + weights: transfer(Tensor([chosen]), Memory::HBM), + mlp: transfer(Tensor([chosen, moe_inter]), Memory::HBM), + }, + logits: transfer(Tensor([c.vocab_size]), Memory::HBM), + cos: transfer(hcos, Memory::HBM), + sin: transfer(hsin, Memory::HBM), + caches: caches, + }; +} + +/// y = m x, with the kernel for the dtype of `m`, which has `rows` x `cols` weights. +fn matvec(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U6 { + matvec_q6(y, &m.codes, &m.high, &m.group_scales, x, rows, cols); + } else if m.dtype == U4 { + nn_matvec_q4(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x. +fn matvec_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_matvec_q4_add(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_add(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec_add(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x, for x of [heads, head_dim]. +fn matvec_heads_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, heads : i32, head_dim : i32) -> void { + if m.dtype == U4 { + matvec_q4_heads_add_blocks(y, &m.codes, &m.group_scales, x, rows, heads, head_dim); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_heads_add(y, &m.codes, &m.scales, x, rows, heads, head_dim); + } else { + nn_matvec_heads_add(y, &m.bf16, x, rows, heads, head_dim); + } + return; +} + +/// The Q, K and V of x: m x + b, split by heads. +fn qkv(q : &mut Tensor, k : &mut Tensor, v : &mut Tensor, m : &WeightMatrix, b : &Tensor, x : &Tensor, c : &Config) -> void { + if m.dtype == U4 { + qkv_q4_blocks(q, k, v, &m.codes, &m.group_scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } else if m.dtype == F8E4M3 { + nn_qkv_fp8(q, k, v, &m.codes, &m.scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } else { + nn_qkv(q, k, v, &m.bf16, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } + return; +} + +/// The SwiGLU of a dense MLP, for the gate rows and then the up rows of `m`. +fn swiglu(out : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_swiglu_q4(out, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_swiglu_fp8(out, &m.codes, &m.scales, x, rows, cols); + } else { + nn_swiglu(out, &m.bf16, x, rows, cols); + } + return; +} + +/// The mixture of experts of a layer: the router chooses experts_per_token experts and their +/// weights, and x gets the sum of their outputs for xn, each times its weight. +fn add_experts(e : &mut Experts, x : &mut Tensor, xn : &Tensor, layer : &Layer, c : &Config) -> void { + let k = c.experts_per_token; + let inter = c.moe_intermediate_size; + nn_matvec(&mut e.router_logits, &layer.router, xn, c.num_experts, c.hidden_size); + nn_top_k(&mut e.ids, &mut e.weights, &e.router_logits, c.num_experts, k); + let gate_up = &layer.gate_up; + let down = &layer.down; + if gate_up.dtype == U4 { + moe_swiglu_q4_blocks(&mut e.mlp, &gate_up.codes, &gate_up.group_scales, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + moe_down_q4_add_blocks(x, &down.codes, &down.group_scales, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + } else { + assert(gate_up.dtype == BF16, "the experts of a mixture-of-experts model must be bf16 or Q4_0"); + nn_moe_swiglu(&mut e.mlp, &gate_up.bf16, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + nn_moe_down_add(x, &down.bf16, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + } + return; +} + +/// Runs the token in `token` at position `pos` through every layer. The hidden state of the +/// token is then in `s.x`, and its keys and values are in the caches. +fn run_layers(w : &Weights, s : &mut State, token : &Tensor, pos : i32) -> void { + let c = &w.config; + let eps = c.rms_norm_eps as f32; + assert(pos >= 0 && pos < s.max_seq, "the position is past the end of the KV cache"); + nn_embed(&mut s.x, &w.embed, token, c.hidden_size); + let mut l = 0; + for cache in s.caches.iter_mut() { + let layer = &w.layers[l]; + nn_rms_norm(&mut s.xn, &s.x, &layer.attn_norm, c.hidden_size, eps); + qkv(&mut s.q, &mut s.k, &mut s.v, &layer.qkv, &layer.qkv_bias, &s.xn, c); + if c.qk_norm { + norm_rope_and_store(&mut s.q_turned, &mut cache.k, &mut cache.v, &s.q, &s.k, &s.v, &layer.q_norm, &layer.k_norm, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.head_dim, eps); + } else { + rope_and_store(&mut s.q_turned, &mut cache.k, &mut cache.v, &s.q, &s.k, &s.v, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } + if c.head_dim == 128 { + vec_attention(&mut s.attended, &mut s.vec_parts, &s.q_turned, &cache.k, &cache.v, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } else { + split_attention(&mut s.attended, &mut s.attention_parts, &s.q_turned, &cache.k, &cache.v, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } + matvec_heads_add(&mut s.x, &layer.attn_out, &s.attended, c.hidden_size, c.num_q_heads, c.head_dim); + nn_rms_norm(&mut s.xn, &s.x, &layer.mlp_norm, c.hidden_size, eps); + if c.num_experts > 0 { + add_experts(&mut s.experts, &mut s.x, &s.xn, layer, c); + } else { + swiglu(&mut s.mlp, &layer.gate_up, &s.xn, c.intermediate_size, c.hidden_size); + matvec_add(&mut s.x, &layer.down, &s.mlp, c.hidden_size, c.intermediate_size); + } + l = l + 1; + } + return; +} + +/// The logits of the token whose hidden state is in `s.x`, and in `next` the index of the largest +/// one. Both stay in GPU memory. +fn predict(w : &Weights, s : &mut State, next : &mut Tensor) -> void { + let c = &w.config; + nn_rms_norm(&mut s.xn, &s.x, &w.final_norm, c.hidden_size, c.rms_norm_eps as f32); + if c.tied_embeddings { + nn_matvec(&mut s.logits, &w.embed, &s.xn, c.vocab_size, c.hidden_size); + } else { + matvec(&mut s.logits, &w.lm_head, &s.xn, c.vocab_size, c.hidden_size); + } + nn_argmax(next, &s.logits, c.vocab_size); + return; +} +//===- attention.vx - Qwen app ----------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// The attention of one generated token, with the positions split among blocks. This is a copy of +// `nn_attention` and its kernels from `std::nn` on Vx main (vx-lang/Vx#3216), with `split_` in place +// of `nn_` in their names. Vx v0.0.4 has the older `nn_attention`, which has one block for each head +// of Q, so its time grows with the number of positions. Remove this file, and call `nn_attention` +// of `std::nn`, when a Vx release has the new one (#4). +// +// `vec_attention`, for head_dim 128, has the design of llama.cpp's flash attention for one token +// (kernel_flash_attn_ext_vec and kernel_flash_attn_ext_vec_reduce), MIT License, Copyright (c) 2023-2026 +// The ggml authors. scripts/mlir_kernels/decode_attention.py writes its kernels: change that script, not +// the MLIR. +import core::num; +import std::nn; + +/// Attention of the token at position `pos` over rows 0 to `pos` of the KV cache, with a softmax +/// of the scores q . k / sqrt(head_dim). `part` is scratch space from `split_attention_scratch`. +/// +/// The blocks of the first kernel split the positions, 32 to a block below position 640 and 64 from +/// there on. A block serves the 8 heads of Q that share a head of K and V, so it reads each row of +/// the cache once for all 8. A second kernel merges the parts of the blocks for each head. +fn split_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_heads % kv_heads == 0, "split_attention: q_heads must be a multiple of kv_heads"); + assert(head_dim % 32 == 0 && head_dim <= 128, "split_attention: head_dim must be a multiple of 32, and at most 128"); + let mut n_pos = 32; + if pos >= 640 { + n_pos = 64; + } + assert(part.extent(0) >= kv_heads * ((q_heads / kv_heads + 7) / 8) && part.extent(1) >= (pos + n_pos) / n_pos && part.extent(2) >= 8 && part.extent(3) >= head_dim + 2, "split_attention: `part` is too small for this position. Make it with split_attention_scratch"); + if n_pos == 32 { + split_attention_parts_32(part, q, k_cache, v_cache, pos, q_heads, kv_heads, head_dim); + } else { + split_attention_parts_64(part, q, k_cache, v_cache, pos, q_heads, kv_heads, head_dim); + } + split_attention_merge(out, part, pos, n_pos, q_heads, kv_heads, head_dim); + return; +} + +/// Attention of the token at position `pos`, as `split_attention`, for head_dim 128, with the kernels of +/// llama.cpp's flash attention for one token. `vec_attention_parts` splits the blocks of 32 positions among +/// `nwg` SIMD groups for each head of Q: 32 of them, or 64 when each of 32 would have more than 2 blocks. +/// (llama.cpp goes on to 4 SIMD groups of 32 a block, but 128 parts are no faster here: their merge costs what +/// they save.) `vec_attention_merge` then merges the parts. `part` is scratch space from +/// `vec_attention_scratch`. +fn vec_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_heads % kv_heads == 0 && head_dim == 128, "vec_attention: q_heads must be a multiple of kv_heads, and head_dim 128"); + assert(part.extent(0) >= q_heads && part.extent(1) >= 128 && part.extent(2) == 132, "vec_attention: `part` is too small. Make it with vec_attention_scratch"); + let mut nwg = 32; + if 2 * nwg * 32 < pos + 1 { + nwg = nwg * 2; + } + vec_attention_parts(part, q, k_cache, v_cache, pos, q_heads, q_heads / kv_heads, nwg, 1.0 / (head_dim as f32).sqrt()); + vec_attention_merge(out, part, nwg, q_heads); + return; +} + +/// The scratch space of `vec_attention`, on the CPU: up to 128 parts for each head of Q, each the sum of V +/// (128 values), the largest score, and the sum of the weights. A part has 132 values, so that each starts +/// at a multiple of 16 bytes. +fn vec_attention_scratch(q_heads : i32) -> Tensor { + return Tensor([q_heads, 128, 132]); +} + +/// The parts of `vec_attention`, as llama.cpp's kernel_flash_attn_ext_vec. Block (h, w) is a SIMD group for +/// query head h. It does the blocks of 32 positions w, w + nwg, w + 2 nwg, ... up to `pos`, and writes +/// part[h][w]. Lane l owns values 4 l to 4 l + 3 of the head, so that the 32 lanes read a row of K or V in +/// one 256-byte load. For each row, the lanes add up their parts of q . k; then each lane keeps the score +/// of one row, and the lanes take the weights of the rows from each other for the sum of V. A part is the +/// sum of V, not divided, then the largest score and the sum of the weights. +fn vec_attention_parts(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, group : i32, nwg : i32, scale : f32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for w in 0..nwg across blocks { + let g = h / group; + let _d = mlir!( threads : 32, inputs : (%part = part : memref, %q = q : memref, %k3 = k_cache : memref, %v3 = v_cache : memref, %pos = pos : i32, %nwg = nwg : i32, %scale = scale : f32, %h = h : i32, %w = w : i32, %g = g : i32), returns : i32, dialects : ["arith", "memref", "scf", "gpu", "vector", "math"], ensures : [reads_only(q), reads_only(k_cache), reads_only(v_cache), writes_only(part[h][w])]) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %c4 = arith.constant 4 : index + %c32 = arith.constant 32 : index + %c128 = arith.constant 128 : index + %c129 = arith.constant 129 : index + %c32i = arith.constant 32 : i32 + %neg = arith.constant -3.0e38 : f32 + %zero = arith.constant 0.0 : f32 + %vz4 = arith.constant dense<0.0> : vector<4xf32> + %l = gpu.thread_id x + %l4 = arith.muli %l, %c4 : index + %hi = arith.index_cast %h : i32 to index + %wi = arith.index_cast %w : i32 to index + %gi = arith.index_cast %g : i32 to index + %posi = arith.index_cast %pos : i32 to index + %nwgi = arith.index_cast %nwg : i32 to index + %g128 = arith.muli %gi, %c128 : index + %kd = arith.addi %g128, %l4 : index + %P = memref.dim %k3, %c0 : memref + %KH = memref.dim %k3, %c1 : memref + %Wd = arith.muli %KH, %c128 : index + %k = memref.reinterpret_cast %k3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to memref> + %v = memref.reinterpret_cast %v3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to memref> + %qv = vector.load %q[%hi, %l4] {alignment = 16} : memref, vector<4xf32> + %scv = vector.broadcast %scale : f32 to vector<4xf32> + %qs = arith.mulf %qv, %scv : vector<4xf32> + %nkv = arith.addi %posi, %c32 : index + %chunks = arith.divui %nkv, %c32 : index + %st:3 = scf.for %ic = %wi to %chunks step %nwgi iter_args(%M = %neg, %S = %zero, %o = %vz4) -> (f32, f32, vector<4xf32>) { + %r0 = arith.muli %ic, %c32 : index + %my = scf.for %cc = %c0 to %c32 step %c1 iter_args(%m = %neg) -> (f32) { + %row = arith.addi %r0, %cc : index + %rowc = arith.minui %row, %posi : index + %kh = vector.load %k[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> + %kf = arith.extf %kh : vector<4xf16> to vector<4xf32> + %pr = arith.mulf %kf, %qs : vector<4xf32> + %pl = vector.reduction , %pr : vector<4xf32> into f32 + %sc = gpu.subgroup_reduce add %pl : (f32) -> f32 + %live = arith.cmpi ule, %row, %posi : index + %scm = arith.select %live, %sc, %neg : f32 + %mine = arith.cmpi eq, %cc, %l : index + %m2 = arith.select %mine, %scm, %m : f32 + scf.yield %m2 : f32 + } + %bm = gpu.subgroup_reduce maxnumf %my : (f32) -> f32 + %Mn = arith.maxnumf %M, %bm : f32 + %dm = arith.subf %M, %Mn : f32 + %ms = math.exp %dm : f32 + %dp = arith.subf %my, %Mn : f32 + %p = math.exp %dp : f32 + %bs = gpu.subgroup_reduce add %p : (f32) -> f32 + %Ss = arith.mulf %S, %ms : f32 + %Sn = arith.addf %Ss, %bs : f32 + %msv = vector.broadcast %ms : f32 to vector<4xf32> + %o1 = arith.mulf %o, %msv : vector<4xf32> + %o2 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%oa = %o1) -> (vector<4xf32>) { + %row = arith.addi %r0, %cc : index + %rowc = arith.minui %row, %posi : index + %vh = vector.load %v[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> + %vf = arith.extf %vh : vector<4xf16> to vector<4xf32> + %cci = arith.index_cast %cc : index to i32 + %pc, %pv = gpu.shuffle idx %p, %cci, %c32i : f32 + %pcv = vector.broadcast %pc : f32 to vector<4xf32> + %on = vector.fma %vf, %pcv, %oa : vector<4xf32> + scf.yield %on : vector<4xf32> + } + scf.yield %Mn, %Sn, %o2 : f32, f32, vector<4xf32> + } + vector.store %st#2, %part[%hi, %wi, %l4] : memref, vector<4xf32> + %lane0 = arith.cmpi eq, %l, %c0 : index + scf.if %lane0 { + memref.store %st#0, %part[%hi, %wi, %c128] : memref + memref.store %st#1, %part[%hi, %wi, %c129] : memref + } + macro.yield %h : i32 + }; + } + } + } + return; +} + +/// Merges the first `parts` parts of `vec_attention_parts` for each head of Q, as llama.cpp's +/// kernel_flash_attn_ext_vec_reduce. A block of 4 SIMD groups does one head: each lane weighs up to 4 parts, +/// and the SIMD groups add them up for 4 values of the head at a time. +fn vec_attention_merge(out : &mut Tensor, part : &Tensor, parts : i32, q_heads : i32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + let _d = mlir!( threads : 128, inputs : (%out = out : memref, %part = part : memref, %parts = parts : i32, %h = h : i32), returns : i32, dialects : ["arith", "memref", "scf", "gpu", "vector", "math"], ensures : [reads_only(part), writes_only(out[h])]) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %c2 = arith.constant 2 : index + %c3 = arith.constant 3 : index + %c4 = arith.constant 4 : index + %c16 = arith.constant 16 : index + %c32 = arith.constant 32 : index + %c64 = arith.constant 64 : index + %c96 = arith.constant 96 : index + %c128 = arith.constant 128 : index + %c129 = arith.constant 129 : index + %neg = arith.constant -3.0e38 : f32 + %zero = arith.constant 0.0 : f32 + %one = arith.constant 1.0 : f32 + %tid = gpu.thread_id x + %sg = arith.divui %tid, %c32 : index + %l = arith.remui %tid, %c32 : index + %hi = arith.index_cast %h : i32 to index + %np = arith.index_cast %parts : i32 to index + %last = arith.subi %np, %c1 : index + %p0 = arith.addi %l, %c0 : index + %live0 = arith.cmpi ult, %p0, %np : index + %pc0 = arith.minui %p0, %last : index + %mr0 = memref.load %part[%hi, %pc0, %c128] : memref + %m0 = arith.select %live0, %mr0, %neg : f32 + %p1 = arith.addi %l, %c32 : index + %live1 = arith.cmpi ult, %p1, %np : index + %pc1 = arith.minui %p1, %last : index + %mr1 = memref.load %part[%hi, %pc1, %c128] : memref + %m1 = arith.select %live1, %mr1, %neg : f32 + %p2 = arith.addi %l, %c64 : index + %live2 = arith.cmpi ult, %p2, %np : index + %pc2 = arith.minui %p2, %last : index + %mr2 = memref.load %part[%hi, %pc2, %c128] : memref + %m2 = arith.select %live2, %mr2, %neg : f32 + %p3 = arith.addi %l, %c96 : index + %live3 = arith.cmpi ult, %p3, %np : index + %pc3 = arith.minui %p3, %last : index + %mr3 = memref.load %part[%hi, %pc3, %c128] : memref + %m3 = arith.select %live3, %mr3, %neg : f32 + %m01 = arith.maxnumf %m0, %m1 : f32 + %m23 = arith.maxnumf %m2, %m3 : f32 + %mx = arith.maxnumf %m01, %m23 : f32 + %big = gpu.subgroup_reduce maxnumf %mx : (f32) -> f32 + %dm0 = arith.subf %m0, %big : f32 + %w0 = math.exp %dm0 : f32 + %s0 = memref.load %part[%hi, %pc0, %c129] : memref + %ws0 = arith.mulf %w0, %s0 : f32 + %wv0 = vector.broadcast %w0 : f32 to vector<4xf32> + %dm1 = arith.subf %m1, %big : f32 + %w1 = math.exp %dm1 : f32 + %s1 = memref.load %part[%hi, %pc1, %c129] : memref + %ws1 = arith.mulf %w1, %s1 : f32 + %wv1 = vector.broadcast %w1 : f32 to vector<4xf32> + %dm2 = arith.subf %m2, %big : f32 + %w2 = math.exp %dm2 : f32 + %s2 = memref.load %part[%hi, %pc2, %c129] : memref + %ws2 = arith.mulf %w2, %s2 : f32 + %wv2 = vector.broadcast %w2 : f32 to vector<4xf32> + %dm3 = arith.subf %m3, %big : f32 + %w3 = math.exp %dm3 : f32 + %s3 = memref.load %part[%hi, %pc3, %c129] : memref + %ws3 = arith.mulf %w3, %s3 : f32 + %wv3 = vector.broadcast %w3 : f32 to vector<4xf32> + %t01 = arith.addf %ws0, %ws1 : f32 + %t23 = arith.addf %ws2, %ws3 : f32 + %ts = arith.addf %t01, %t23 : f32 + %total = gpu.subgroup_reduce add %ts : (f32) -> f32 + %inv = arith.divf %one, %total : f32 + %lane0 = arith.cmpi eq, %l, %c0 : index + %sg4 = arith.muli %sg, %c4 : index + %vz4 = arith.constant dense<0.0> : vector<4xf32> + scf.for %n = %c0 to %c128 step %c16 { + %d = arith.addi %n, %sg4 : index + %x0 = vector.load %part[%hi, %pc0, %d] {alignment = 16} : memref, vector<4xf32> + %a0 = vector.fma %x0, %wv0, %vz4 : vector<4xf32> + %x1 = vector.load %part[%hi, %pc1, %d] {alignment = 16} : memref, vector<4xf32> + %a1 = vector.fma %x1, %wv1, %a0 : vector<4xf32> + %x2 = vector.load %part[%hi, %pc2, %d] {alignment = 16} : memref, vector<4xf32> + %a2 = vector.fma %x2, %wv2, %a1 : vector<4xf32> + %x3 = vector.load %part[%hi, %pc3, %d] {alignment = 16} : memref, vector<4xf32> + %a3 = vector.fma %x3, %wv3, %a2 : vector<4xf32> + %e0 = vector.extract %a3[0] : f32 from vector<4xf32> + %r0 = gpu.subgroup_reduce add %e0 : (f32) -> f32 + %o0 = arith.mulf %r0, %inv : f32 + %e1 = vector.extract %a3[1] : f32 from vector<4xf32> + %r1 = gpu.subgroup_reduce add %e1 : (f32) -> f32 + %o1 = arith.mulf %r1, %inv : f32 + %e2 = vector.extract %a3[2] : f32 from vector<4xf32> + %r2 = gpu.subgroup_reduce add %e2 : (f32) -> f32 + %o2 = arith.mulf %r2, %inv : f32 + %e3 = vector.extract %a3[3] : f32 from vector<4xf32> + %r3 = gpu.subgroup_reduce add %e3 : (f32) -> f32 + %o3 = arith.mulf %r3, %inv : f32 + scf.if %lane0 { + %d0 = arith.addi %d, %c0 : index + memref.store %o0, %out[%hi, %d0] : memref + %d1 = arith.addi %d, %c1 : index + memref.store %o1, %out[%hi, %d1] : memref + %d2 = arith.addi %d, %c2 : index + memref.store %o2, %out[%hi, %d2] : memref + %d3 = arith.addi %d, %c3 : index + memref.store %o3, %out[%hi, %d3] : memref + } + } + macro.yield %h : i32 + }; + } + } + return; +} + +/// The scratch space of `split_attention` for positions below `max_seq`, on the CPU. Transfer it to the +/// memory of the other tensors. Each block of positions writes the weighted sum of V for each of its +/// heads, then the largest score and the sum of the weights. +fn split_attention_scratch(max_seq : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> Tensor { + // 20 blocks of 32 positions below position 640, and blocks of 64 positions from there on. + let mut splits = (max_seq + 63) / 64; + if splits < 20 { + splits = 20; + } + return Tensor([kv_heads * ((q_heads / kv_heads + 7) / 8), splits, 8, head_dim + 2]); +} + +/// The parts of `split_attention` for blocks of 32 positions: 4 SIMD groups of 2 heads of Q. +fn split_attention_parts_32(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + let group = q_heads / kv_heads; + let tiles = (group + 7) / 8; + let scale = 1.0 / (head_dim as f32).sqrt(); + spawn on(Topology::Device) { + for gt in 0..kv_heads * tiles across blocks { + for c in 0..(pos + 32) / 32 across blocks { + let mut w = unsafe { Tensor::uninit() }; + let mut top = unsafe { + Tensor::uninit() + }; + let mut sums = unsafe { + Tensor::uninit() + }; + let g = gt / tiles; + let base = g * group + (gt - g * tiles) * 8; + let left = group - (gt - g * tiles) * 8; + for s in 0..4 across subgroups { + let first = base + s * 2; + let mut heads = left - s * 2; + if heads > 2 { + heads = 2; + } + // A head past the last one of the group reads the last one again, and its sums go nowhere. + let mut h0 = first + 0; + if 0 >= heads { + h0 = first + heads - 1; + } + let mut h1 = first + 1; + if 1 >= heads { + h1 = first + heads - 1; + } + for l in 0..32 across lanes(32) { + // The scores of the position of the lane, for each head. A position past `pos` reads row + // `pos`, and its score is -3e38. + let mut t0 = c * 32 + 0 + l; + if t0 > pos { + t0 = pos; + } + let mut dot0_0 : f32 = 0.0; + let mut dot0_1 : f32 = 0.0; + for d in 0..head_dim { + let k0 = k_cache[t0][g][d] as f32; + let q0 = q[h0][d]; + dot0_0 = dot0_0 + q0 * k0; + let q1 = q[h1][d]; + dot0_1 = dot0_1 + q1 * k0; + } + let mut s0_0 : f32 = -3.0e38; + if c * 32 + 0 + l <= pos { + s0_0 = dot0_0 * scale; + } + w[s][0][0 + l] = s0_0; + top[s][0][l] = s0_0; + let mut s0_1 : f32 = -3.0e38; + if c * 32 + 0 + l <= pos { + s0_1 = dot0_1 * scale; + } + w[s][1][0 + l] = s0_1; + top[s][1][l] = s0_1; + } + let big0 = lanes::max(&top[s][0], 32); + let big1 = lanes::max(&top[s][1], 32); + // The weight of each position, as exp(score - the largest score of the block). + for l in 0..32 across lanes(32) { + let e0_0 = (w[s][0][0 + l] - big0).fast_exp(); + w[s][0][0 + l] = e0_0; + sums[s][0][l] = e0_0; + let e0_1 = (w[s][1][0 + l] - big1).fast_exp(); + w[s][1][0 + l] = e0_1; + sums[s][1][l] = e0_1; + } + let total0 = lanes::sum(&sums[s][0], 32); + let total1 = lanes::sum(&sums[s][1], 32); + // The weighted sum of the rows of V. Lane l takes values l, l + 32, l + 64 and l + 96. + for l in 0..32 across lanes(32) { + let mut acc0_0 : f32 = 0.0; + let mut acc0_1 : f32 = 0.0; + let mut acc0_2 : f32 = 0.0; + let mut acc0_3 : f32 = 0.0; + let mut acc1_0 : f32 = 0.0; + let mut acc1_1 : f32 = 0.0; + let mut acc1_2 : f32 = 0.0; + let mut acc1_3 : f32 = 0.0; + // With head_dim below 128, values past it read others again, and their sums go nowhere. + let d0 = (0 + l) % head_dim; + let d1 = (32 + l) % head_dim; + let d2 = (64 + l) % head_dim; + let d3 = (96 + l) % head_dim; + let mut last = pos - c * 32; + if last > 31 { + last = 31; + } + for t in 0..last + 1 { + let row = c * 32 + t; + let v0 = v_cache[row][g][d0] as f32; + let v1 = v_cache[row][g][d1] as f32; + let v2 = v_cache[row][g][d2] as f32; + let v3 = v_cache[row][g][d3] as f32; + let w0 = w[s][0][t]; + acc0_0 = acc0_0 + w0 * v0; + acc0_1 = acc0_1 + w0 * v1; + acc0_2 = acc0_2 + w0 * v2; + acc0_3 = acc0_3 + w0 * v3; + let w1 = w[s][1][t]; + acc1_0 = acc1_0 + w1 * v0; + acc1_1 = acc1_1 + w1 * v1; + acc1_2 = acc1_2 + w1 * v2; + acc1_3 = acc1_3 + w1 * v3; + } + if 0 < heads { + if 0 < head_dim { + part[gt][c][s * 2 + 0][0 + l] = acc0_0; + } + if 32 < head_dim { + part[gt][c][s * 2 + 0][32 + l] = acc0_1; + } + if 64 < head_dim { + part[gt][c][s * 2 + 0][64 + l] = acc0_2; + } + if 96 < head_dim { + part[gt][c][s * 2 + 0][96 + l] = acc0_3; + } + } + if 1 < heads { + if 0 < head_dim { + part[gt][c][s * 2 + 1][0 + l] = acc1_0; + } + if 32 < head_dim { + part[gt][c][s * 2 + 1][32 + l] = acc1_1; + } + if 64 < head_dim { + part[gt][c][s * 2 + 1][64 + l] = acc1_2; + } + if 96 < head_dim { + part[gt][c][s * 2 + 1][96 + l] = acc1_3; + } + } + } + if 0 < heads { + part[gt][c][s * 2 + 0][head_dim] = big0; + part[gt][c][s * 2 + 0][head_dim + 1] = total0; + } + if 1 < heads { + part[gt][c][s * 2 + 1][head_dim] = big1; + part[gt][c][s * 2 + 1][head_dim + 1] = total1; + } + } + } + } + } + return; +} + +/// The parts of `split_attention` for blocks of 64 positions: 2 SIMD groups of 4 heads of Q. +fn split_attention_parts_64(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + let group = q_heads / kv_heads; + let tiles = (group + 7) / 8; + let scale = 1.0 / (head_dim as f32).sqrt(); + spawn on(Topology::Device) { + for gt in 0..kv_heads * tiles across blocks { + for c in 0..(pos + 64) / 64 across blocks { + let mut w = unsafe { Tensor::uninit() }; + let mut top = unsafe { + Tensor::uninit() + }; + let mut sums = unsafe { + Tensor::uninit() + }; + let g = gt / tiles; + let base = g * group + (gt - g * tiles) * 8; + let left = group - (gt - g * tiles) * 8; + for s in 0..2 across subgroups { + let first = base + s * 4; + let mut heads = left - s * 4; + if heads > 4 { + heads = 4; + } + // A head past the last one of the group reads the last one again, and its sums go nowhere. + let mut h0 = first + 0; + if 0 >= heads { + h0 = first + heads - 1; + } + let mut h1 = first + 1; + if 1 >= heads { + h1 = first + heads - 1; + } + let mut h2 = first + 2; + if 2 >= heads { + h2 = first + heads - 1; + } + let mut h3 = first + 3; + if 3 >= heads { + h3 = first + heads - 1; + } + for l in 0..32 across lanes(32) { + // The scores of each of the 2 positions of the lane, for each head. A position past `pos` reads row + // `pos`, and its score is -3e38. + let mut t0 = c * 64 + 0 + l; + if t0 > pos { + t0 = pos; + } + let mut dot0_0 : f32 = 0.0; + let mut dot0_1 : f32 = 0.0; + let mut dot0_2 : f32 = 0.0; + let mut dot0_3 : f32 = 0.0; + let mut t1 = c * 64 + 32 + l; + if t1 > pos { + t1 = pos; + } + let mut dot1_0 : f32 = 0.0; + let mut dot1_1 : f32 = 0.0; + let mut dot1_2 : f32 = 0.0; + let mut dot1_3 : f32 = 0.0; + for d in 0..head_dim { + let k0 = k_cache[t0][g][d] as f32; + let k1 = k_cache[t1][g][d] as f32; + let q0 = q[h0][d]; + dot0_0 = dot0_0 + q0 * k0; + dot1_0 = dot1_0 + q0 * k1; + let q1 = q[h1][d]; + dot0_1 = dot0_1 + q1 * k0; + dot1_1 = dot1_1 + q1 * k1; + let q2 = q[h2][d]; + dot0_2 = dot0_2 + q2 * k0; + dot1_2 = dot1_2 + q2 * k1; + let q3 = q[h3][d]; + dot0_3 = dot0_3 + q3 * k0; + dot1_3 = dot1_3 + q3 * k1; + } + let mut s0_0 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_0 = dot0_0 * scale; + } + w[s][0][0 + l] = s0_0; + let mut s1_0 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_0 = dot1_0 * scale; + } + w[s][0][32 + l] = s1_0; + top[s][0][l] = s0_0.max(s1_0); + let mut s0_1 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_1 = dot0_1 * scale; + } + w[s][1][0 + l] = s0_1; + let mut s1_1 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_1 = dot1_1 * scale; + } + w[s][1][32 + l] = s1_1; + top[s][1][l] = s0_1.max(s1_1); + let mut s0_2 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_2 = dot0_2 * scale; + } + w[s][2][0 + l] = s0_2; + let mut s1_2 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_2 = dot1_2 * scale; + } + w[s][2][32 + l] = s1_2; + top[s][2][l] = s0_2.max(s1_2); + let mut s0_3 : f32 = -3.0e38; + if c * 64 + 0 + l <= pos { + s0_3 = dot0_3 * scale; + } + w[s][3][0 + l] = s0_3; + let mut s1_3 : f32 = -3.0e38; + if c * 64 + 32 + l <= pos { + s1_3 = dot1_3 * scale; + } + w[s][3][32 + l] = s1_3; + top[s][3][l] = s0_3.max(s1_3); + } + let big0 = lanes::max(&top[s][0], 32); + let big1 = lanes::max(&top[s][1], 32); + let big2 = lanes::max(&top[s][2], 32); + let big3 = lanes::max(&top[s][3], 32); + // The weight of each position, as exp(score - the largest score of the block). + for l in 0..32 across lanes(32) { + let e0_0 = (w[s][0][0 + l] - big0).fast_exp(); + w[s][0][0 + l] = e0_0; + let e1_0 = (w[s][0][32 + l] - big0).fast_exp(); + w[s][0][32 + l] = e1_0; + sums[s][0][l] = e0_0 + e1_0; + let e0_1 = (w[s][1][0 + l] - big1).fast_exp(); + w[s][1][0 + l] = e0_1; + let e1_1 = (w[s][1][32 + l] - big1).fast_exp(); + w[s][1][32 + l] = e1_1; + sums[s][1][l] = e0_1 + e1_1; + let e0_2 = (w[s][2][0 + l] - big2).fast_exp(); + w[s][2][0 + l] = e0_2; + let e1_2 = (w[s][2][32 + l] - big2).fast_exp(); + w[s][2][32 + l] = e1_2; + sums[s][2][l] = e0_2 + e1_2; + let e0_3 = (w[s][3][0 + l] - big3).fast_exp(); + w[s][3][0 + l] = e0_3; + let e1_3 = (w[s][3][32 + l] - big3).fast_exp(); + w[s][3][32 + l] = e1_3; + sums[s][3][l] = e0_3 + e1_3; + } + let total0 = lanes::sum(&sums[s][0], 32); + let total1 = lanes::sum(&sums[s][1], 32); + let total2 = lanes::sum(&sums[s][2], 32); + let total3 = lanes::sum(&sums[s][3], 32); + // The weighted sum of the rows of V. Lane l takes values l, l + 32, l + 64 and l + 96. + for l in 0..32 across lanes(32) { + let mut acc0_0 : f32 = 0.0; + let mut acc0_1 : f32 = 0.0; + let mut acc0_2 : f32 = 0.0; + let mut acc0_3 : f32 = 0.0; + let mut acc1_0 : f32 = 0.0; + let mut acc1_1 : f32 = 0.0; + let mut acc1_2 : f32 = 0.0; + let mut acc1_3 : f32 = 0.0; + let mut acc2_0 : f32 = 0.0; + let mut acc2_1 : f32 = 0.0; + let mut acc2_2 : f32 = 0.0; + let mut acc2_3 : f32 = 0.0; + let mut acc3_0 : f32 = 0.0; + let mut acc3_1 : f32 = 0.0; + let mut acc3_2 : f32 = 0.0; + let mut acc3_3 : f32 = 0.0; + // With head_dim below 128, values past it read others again, and their sums go nowhere. + let d0 = (0 + l) % head_dim; + let d1 = (32 + l) % head_dim; + let d2 = (64 + l) % head_dim; + let d3 = (96 + l) % head_dim; + let mut last = pos - c * 64; + if last > 63 { + last = 63; + } + for t in 0..last + 1 { + let row = c * 64 + t; + let v0 = v_cache[row][g][d0] as f32; + let v1 = v_cache[row][g][d1] as f32; + let v2 = v_cache[row][g][d2] as f32; + let v3 = v_cache[row][g][d3] as f32; + let w0 = w[s][0][t]; + acc0_0 = acc0_0 + w0 * v0; + acc0_1 = acc0_1 + w0 * v1; + acc0_2 = acc0_2 + w0 * v2; + acc0_3 = acc0_3 + w0 * v3; + let w1 = w[s][1][t]; + acc1_0 = acc1_0 + w1 * v0; + acc1_1 = acc1_1 + w1 * v1; + acc1_2 = acc1_2 + w1 * v2; + acc1_3 = acc1_3 + w1 * v3; + let w2 = w[s][2][t]; + acc2_0 = acc2_0 + w2 * v0; + acc2_1 = acc2_1 + w2 * v1; + acc2_2 = acc2_2 + w2 * v2; + acc2_3 = acc2_3 + w2 * v3; + let w3 = w[s][3][t]; + acc3_0 = acc3_0 + w3 * v0; + acc3_1 = acc3_1 + w3 * v1; + acc3_2 = acc3_2 + w3 * v2; + acc3_3 = acc3_3 + w3 * v3; + } + if 0 < heads { + if 0 < head_dim { + part[gt][c][s * 4 + 0][0 + l] = acc0_0; + } + if 32 < head_dim { + part[gt][c][s * 4 + 0][32 + l] = acc0_1; + } + if 64 < head_dim { + part[gt][c][s * 4 + 0][64 + l] = acc0_2; + } + if 96 < head_dim { + part[gt][c][s * 4 + 0][96 + l] = acc0_3; + } + } + if 1 < heads { + if 0 < head_dim { + part[gt][c][s * 4 + 1][0 + l] = acc1_0; + } + if 32 < head_dim { + part[gt][c][s * 4 + 1][32 + l] = acc1_1; + } + if 64 < head_dim { + part[gt][c][s * 4 + 1][64 + l] = acc1_2; + } + if 96 < head_dim { + part[gt][c][s * 4 + 1][96 + l] = acc1_3; + } + } + if 2 < heads { + if 0 < head_dim { + part[gt][c][s * 4 + 2][0 + l] = acc2_0; + } + if 32 < head_dim { + part[gt][c][s * 4 + 2][32 + l] = acc2_1; + } + if 64 < head_dim { + part[gt][c][s * 4 + 2][64 + l] = acc2_2; + } + if 96 < head_dim { + part[gt][c][s * 4 + 2][96 + l] = acc2_3; + } + } + if 3 < heads { + if 0 < head_dim { + part[gt][c][s * 4 + 3][0 + l] = acc3_0; + } + if 32 < head_dim { + part[gt][c][s * 4 + 3][32 + l] = acc3_1; + } + if 64 < head_dim { + part[gt][c][s * 4 + 3][64 + l] = acc3_2; + } + if 96 < head_dim { + part[gt][c][s * 4 + 3][96 + l] = acc3_3; + } + } + } + if 0 < heads { + part[gt][c][s * 4 + 0][head_dim] = big0; + part[gt][c][s * 4 + 0][head_dim + 1] = total0; + } + if 1 < heads { + part[gt][c][s * 4 + 1][head_dim] = big1; + part[gt][c][s * 4 + 1][head_dim + 1] = total1; + } + if 2 < heads { + part[gt][c][s * 4 + 2][head_dim] = big2; + part[gt][c][s * 4 + 2][head_dim + 1] = total2; + } + if 3 < heads { + part[gt][c][s * 4 + 3][head_dim] = big3; + part[gt][c][s * 4 + 3][head_dim + 1] = total3; + } + } + } + } + } + return; +} + +/// Merges the parts of `split_attention` of blocks of `n_pos` positions. A block does 32 values of one +/// head of Q, a value for each lane. +fn split_attention_merge(out : &mut Tensor, part : &Tensor, pos : i32, n_pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + let group = q_heads / kv_heads; + let tiles = (group + 7) / 8; + let splits = (pos + n_pos) / n_pos; + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for dq in 0..head_dim / 32 across blocks { + let mut top = unsafe { + Tensor::uninit() + }; + let g = h / group; + let tile = (h - g * group) / 8; + let gt = g * tiles + tile; + let at = h - g * group - tile * 8; + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let mut m : f32 = -3.0e38; + let mut c = l; + while c < splits { + m = m.max(part[gt][c][at][head_dim]); + c = c + 32; + } + top[s][0][l] = m; + } + let big = lanes::max(&top[s][0], 32); + for l in 0..32 across lanes(32) { + let d = dq * 32 + l; + let mut total : f32 = 0.0; + let mut acc : f32 = 0.0; + for c in 0..splits { + let w = (part[gt][c][at][head_dim] - big).fast_exp(); + total = total + w * part[gt][c][at][head_dim + 1]; + acc = acc + w * part[gt][c][at][d]; + } + out[h][d] = acc / total; + } + } + } + } + } + return; +} + +// The kernels that store the K and V of a generated token: copies of `nn_rope_and_store` and +// `nn_norm_rope_and_store` of `std::nn`, with a KV cache of f16. They compute in f32 and round +// what they store. + +/// RoPE for the token at position `pos`, and its K and V into the KV cache. Writes each head of +/// q, turned, to `q_out`, and each head of k, turned, and of v to row `pos` of the cache. Value i +/// of a head pairs with value i + head_dim / 2, as in the Llama and Qwen models of Hugging Face. +/// Both turn by the angle whose cosine and sine are cos[pos][i] and sin[pos][i]. +fn rope_and_store(q_out : &mut Tensor, k_cache : &mut Tensor, v_cache : &mut Tensor, q : &Tensor, k : &Tensor, v : &Tensor, cos : &Tensor, sin : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + let half = head_dim / 2; + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(q_out.extent(0), q_out.extent(1), q_heads, head_dim); + nn_check_heads(k.extent(0), k.extent(1), kv_heads, head_dim); + nn_check_heads(v.extent(0), v.extent(1), kv_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(pos < cos.extent(0) && pos < sin.extent(0) && half <= cos.extent(1) && half <= sin.extent(1), "rope_and_store: `cos` and `sin` need a row for `pos` with head_dim / 2 values"); + spawn on(Topology::Device) { + for h in 0..q_heads + kv_heads across blocks { + for i in 0..128 across lanes { + if i < head_dim { + // Value i of the head, its partner, and the angle that they share. + let mut j = i; + let mut sign : f32 = -1.0; + let mut partner = i + half; + if i >= half { + j = i - half; + sign = 1.0; + partner = i - half; + } + let c = cos[pos][j]; + let s = sin[pos][j]; + if h < q_heads { + q_out[h][i] = q[h][i] * c + sign * q[h][partner] * s; + } else { + k_cache[pos][h - q_heads][i] = (k[h - q_heads][i] * c + sign * k[h - q_heads][partner] * s) as f16; + v_cache[pos][h - q_heads][i] = v[h - q_heads][i] as f16; + } + } + } + } + } + return; +} + +/// As `rope_and_store`, after an RMSNorm over each head of q and of k: value i of a head x +/// becomes x[i] / sqrt(mean(x^2) + eps) * norm[i], where `norm` is `q_norm` for q and `k_norm` +/// for k. Qwen3 has these norms. +fn norm_rope_and_store(q_out : &mut Tensor, k_cache : &mut Tensor, v_cache : &mut Tensor, q : &Tensor, k : &Tensor, v : &Tensor, q_norm : &Tensor, k_norm : &Tensor, cos : &Tensor, sin : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32, eps : f32) -> void { + let half = head_dim / 2; + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(q_out.extent(0), q_out.extent(1), q_heads, head_dim); + nn_check_heads(k.extent(0), k.extent(1), kv_heads, head_dim); + nn_check_heads(v.extent(0), v.extent(1), kv_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_norm.len() >= head_dim && k_norm.len() >= head_dim, "norm_rope_and_store: `q_norm` and `k_norm` need head_dim values"); + assert(pos < cos.extent(0) && pos < sin.extent(0) && half <= cos.extent(1) && half <= sin.extent(1), "norm_rope_and_store: `cos` and `sin` need a row for `pos` with head_dim / 2 values"); + spawn on(Topology::Device) { + for h in 0..q_heads + kv_heads across blocks { + let mut x = unsafe { Tensor::uninit() }; + let mut part = unsafe { Tensor::uninit() }; + for i in 0..128 across lanes { + let mut a : f32 = 0.0; + if i < head_dim { + if h < q_heads { + a = q[h][i]; + } else { + a = k[h - q_heads][i]; + } + } + x[i] = a; + part[i] = a * a; + } + let ss = lanes::sum(&part, 128); + let inv = 1.0 / (ss / (head_dim as f32) + eps).sqrt(); + for i in 0..128 across lanes { + if i < head_dim { + // Value i of the head, its partner, and the angle that they share. + let mut j = i; + let mut sign : f32 = -1.0; + let mut partner = i + half; + if i >= half { + j = i - half; + sign = 1.0; + partner = i - half; + } + let c = cos[pos][j]; + let s = sin[pos][j]; + if h < q_heads { + let a = x[i] * inv * (q_norm[i] as f32); + let b = x[partner] * inv * (q_norm[partner] as f32); + q_out[h][i] = a * c + sign * b * s; + } else { + let a = x[i] * inv * (k_norm[i] as f32); + let b = x[partner] * inv * (k_norm[partner] as f32); + k_cache[pos][h - q_heads][i] = (a * c + sign * b * s) as f16; + v_cache[pos][h - q_heads][i] = v[h - q_heads][i] as f16; + } + } + } + } + } + return; +} +//===- deltanet.vx - Qwen app -----------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// One generated token through the Gated DeltaNet of a linear attention layer of Qwen3.5 and +// Qwen3.6 (#89), after the product `linear_in` and before the product `linear_out`. The math is +// that of `modeling_qwen3_5_moe.py` of transformers: +// +// - `proj`, the output of `linear_in`, has q (k_heads x 128), k (k_heads x 128), v (v_heads x 128), +// z (v_heads x 128), then b and a (v_heads each), at the offsets that the caller gives. +// - q, k and v go through a causal depthwise convolution of width 4 and a SiLU. q and k then get an +// L2 norm for each head (eps 1e-6 inside the square root), and q is multiplied by 1/sqrt(128). +// - beta = sigmoid(b), and the decay exp(g) with g = -exp(A_log) softplus(a + dt_bias). The weight +// file stores -exp(A_log) as `neg_a`. +// - Head h of v uses head h / (v_heads / k_heads) of q and k. Its state S[k][v] decays, then +// S += k (beta (v - k . S)), and the output is q . S. +// - The output gets an RMS norm for each head, times the norm weight, times silu(z). +// +// All the heads have 128 values. The state of a layer is `conv_state` [2 k_heads + v_heads, 128, 3], +// the last 3 inputs of each channel of the convolution, oldest first, and `state` [v_heads, 128, 128] +// as S[v][k]: the 128 values of k for one value of v are next to each other, so that the 32 lanes of +// a SIMD group read them in one load. Both start at zero. +import core::num; +import std::nn; +import qwen::simd; + +/// The scratch tensors of one token, in GPU memory: q and k after the convolution and the norm +/// [k_heads, 128], v after the convolution [v_heads, 128], beta and the decay exp(g) of each head of +/// v, and q . S [v_heads, 128]. +struct DeltaNetScratch { + q : Tensor, + k : Tensor, + v : Tensor, + beta : Tensor, + decay : Tensor, + o : Tensor, +} + +fn deltanet_scratch(k_heads : i32, v_heads : i32) -> DeltaNetScratch { + return DeltaNetScratch { + q : transfer(Tensor([k_heads, 128]), Memory::HBM), + k : transfer(Tensor([k_heads, 128]), Memory::HBM), + v : transfer(Tensor([v_heads, 128]), Memory::HBM), + beta : transfer(Tensor([v_heads]), Memory::HBM), + decay : transfer(Tensor([v_heads]), Memory::HBM), + o : transfer(Tensor([v_heads, 128]), Memory::HBM), + }; +} + +/// A tensor of zeros in GPU memory. +fn dn_zeros(a : i32, b : i32, c : i32) -> Tensor { + let mut x = Tensor([a, b, c]); + for i in 0..a { + for j in 0..b { + for k in 0..c { + x[i][j][k] = 0.0; + } + } + } + return transfer(x, Memory::HBM); +} + +/// The state of one layer at the start: zero. +fn deltanet_conv_state(k_heads : i32, v_heads : i32) -> Tensor { + return dn_zeros(2 * k_heads + v_heads, 128, 3); +} + +fn deltanet_state(v_heads : i32) -> Tensor { + return dn_zeros(v_heads, 128, 128); +} + +/// The Gated DeltaNet of one token: `y` (v_heads x 128 values, the input of `linear_out`) from `proj` +/// (the output of `linear_in`). z starts at `z_at` of `proj`, b at `b_at` and a at `a_at`. `conv` has +/// 4 taps for each of the (2 k_heads + v_heads) x 128 channels, channel c at 4 c, oldest tap +/// first. `neg_a` and `dt_bias` have v_heads values, and `norm` 128. +fn deltanet_step(y : &mut Tensor, conv_state : &mut Tensor, state : &mut Tensor, t : &mut DeltaNetScratch, proj : &Tensor, conv : &Tensor, neg_a : &Tensor, dt_bias : &Tensor, norm : &Tensor, z_at : i32, b_at : i32, a_at : i32, k_heads : i32, v_heads : i32, eps : f32) -> void { + let channels = (2 * k_heads + v_heads) * 128; + assert(k_heads > 0 && v_heads % k_heads == 0 && v_heads <= 64, "deltanet_step: v_heads must be a multiple of k_heads, and at most 64"); + assert(conv_state.extent(0) == 2 * k_heads + v_heads && conv_state.extent(1) == 128 && conv_state.extent(2) == 3, "deltanet_step: conv_state must be [2 k_heads + v_heads, 128, 3]"); + assert(state.extent(0) == v_heads && state.extent(1) == 128 && state.extent(2) == 128, "deltanet_step: state must be [v_heads, 128, 128]"); + assert(conv.len() == channels * 4, "deltanet_step: conv must have 4 taps for each channel"); + assert(proj.len() >= channels && proj.len() >= z_at + v_heads * 128 && proj.len() >= b_at + v_heads && proj.len() >= a_at + v_heads, "deltanet_step: proj is too short for its offsets"); + assert(neg_a.len() >= v_heads && dt_bias.len() >= v_heads && norm.len() >= 128 && y.len() >= v_heads * 128, "deltanet_step: a tensor is too short"); + deltanet_conv(&mut t.q, &mut t.k, &mut t.v, conv_state, proj, conv, k_heads, v_heads); + deltanet_gates(&mut t.beta, &mut t.decay, proj, neg_a, dt_bias, b_at, a_at, v_heads); + deltanet_recur(&mut t.o, state, &t.q, &t.k, &t.v, &t.beta, &t.decay, v_heads / k_heads, v_heads); + deltanet_gated_norm(y, &t.o, proj, norm, z_at, v_heads, eps); + return; +} + +/// The convolution and the SiLU of q, k and v, and the L2 norms of q and k. Block h does the 128 +/// channels of one head: heads 0 to k_heads - 1 of q, then those of k, then those of v. The channels +/// of `proj` are in the same order, so channel i of block h is h * 128 + i. +fn deltanet_conv(qn : &mut Tensor, kn : &mut Tensor, vv : &mut Tensor, conv_state : &mut Tensor, proj : &Tensor, conv : &Tensor, k_heads : i32, v_heads : i32) -> void { + spawn on(Topology::Device) { + for h in 0..2 * k_heads + v_heads across blocks { + let mut y = unsafe { Tensor::uninit() }; + let mut part = unsafe { Tensor::uninit() }; + for i in 0..128 across lanes { + let c = h * 128 + i; + let x0 = conv_state[h][i][0]; + let x1 = conv_state[h][i][1]; + let x2 = conv_state[h][i][2]; + let x3 = proj[c]; + let a = conv[c * 4] * x0 + conv[c * 4 + 1] * x1 + conv[c * 4 + 2] * x2 + conv[c * 4 + 3] * x3; + let s = a / (1.0 + (0.0 - a).fast_exp()); + conv_state[h][i][0] = x1; + conv_state[h][i][1] = x2; + conv_state[h][i][2] = x3; + y[i] = s; + part[i] = s * s; + } + let ss = lanes::sum(&part, 128); + let inv = 1.0 / (ss + 0.000001).sqrt(); + for i in 0..128 across lanes { + if h < k_heads { + qn[h][i] = y[i] * inv * 0.08838834764831845; + } else if h < 2 * k_heads { + kn[h - k_heads][i] = y[i] * inv; + } else { + vv[h - 2 * k_heads][i] = y[i]; + } + } + } + } + return; +} + +/// beta = sigmoid(b) and the decay exp(neg_a softplus(a + dt_bias)) of each head of v. softplus(x) +/// is x above 20, as in torch. +fn deltanet_gates(beta : &mut Tensor, decay : &mut Tensor, proj : &Tensor, neg_a : &Tensor, dt_bias : &Tensor, b_at : i32, a_at : i32, v_heads : i32) -> void { + spawn on(Topology::Device) { + for blk in 0..1 across blocks { + for j in 0..64 across lanes { + if j < v_heads { + let b = proj[b_at + j]; + beta[j] = 1.0 / (1.0 + (0.0 - b).fast_exp()); + let x = proj[a_at + j] + dt_bias[j]; + let mut sp = x; + if x <= 20.0 { + sp = simd_log(1.0 + x.fast_exp()); + } + decay[j] = (neg_a[j] * sp).fast_exp(); + } + } + } + } + return; +} + +/// The update of the state and the output q . S, for each head h of v. Block (h, vq) is one SIMD +/// group for values vq * 32 to vq * 32 + 31 of v. Lane l owns values 4 l to 4 l + 3 of k. For each +/// value of v, the lanes add up k . S, then each lane updates its 4 values of S and the lanes add up +/// q . S. Lane m keeps the output of value m. +fn deltanet_recur(o : &mut Tensor, state : &mut Tensor, qn : &Tensor, kn : &Tensor, vv : &Tensor, beta : &Tensor, decay : &Tensor, group : i32, v_heads : i32) -> void { + spawn on(Topology::Device) { + for h in 0..v_heads across blocks { + for vq in 0..4 across blocks { + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let g = h / group; + let d = 4 * l; + let q0 = qn[g][d]; + let q1 = qn[g][d + 1]; + let q2 = qn[g][d + 2]; + let q3 = qn[g][d + 3]; + let k0 = kn[g][d]; + let k1 = kn[g][d + 1]; + let k2 = kn[g][d + 2]; + let k3 = kn[g][d + 3]; + let b = beta[h]; + let dec = decay[h]; + let mut mine : f32 = 0.0; + for m in 0..32 { + let v = vq * 32 + m; + let s0 = state[h][v][d] * dec; + let s1 = state[h][v][d + 1] * dec; + let s2 = state[h][v][d + 2] * dec; + let s3 = state[h][v][d + 3] * dec; + let kv = simd_sum(s0 * k0 + s1 * k1 + s2 * k2 + s3 * k3); + let delta = (vv[h][v] - kv) * b; + let n0 = s0 + k0 * delta; + let n1 = s1 + k1 * delta; + let n2 = s2 + k2 * delta; + let n3 = s3 + k3 * delta; + state[h][v][d] = n0; + state[h][v][d + 1] = n1; + state[h][v][d + 2] = n2; + state[h][v][d + 3] = n3; + let out = simd_sum(n0 * q0 + n1 * q1 + n2 * q2 + n3 * q3); + if m == l { + mine = out; + } + } + o[h][vq * 32 + l] = mine; + } + } + } + } + } + return; +} + +/// y = rms_norm(o) * norm * silu(z), for each head of v. Block h does one head. +fn deltanet_gated_norm(y : &mut Tensor, o : &Tensor, proj : &Tensor, norm : &Tensor, z_at : i32, v_heads : i32, eps : f32) -> void { + spawn on(Topology::Device) { + for h in 0..v_heads across blocks { + let mut part = unsafe { Tensor::uninit() }; + for i in 0..128 across lanes { + let a = o[h][i]; + part[i] = a * a; + } + let ss = lanes::sum(&part, 128); + let inv = 1.0 / (ss / 128.0 + eps).sqrt(); + for i in 0..128 across lanes { + let z = proj[z_at + h * 128 + i]; + y[h * 128 + i] = o[h][i] * inv * norm[i] * (z / (1.0 + (0.0 - z).fast_exp())); + } + } + } + return; +} +//===- gated_attention.vx - Qwen app ----------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// The full attention of one token in a layer of Qwen3.5 and Qwen3.6 (#89), between the product +// `qkv` and the product `attn_out`, with the math of `modeling_qwen3_5_moe.py` of transformers: +// +// - `qkvg`, the output of `qkv`, has q (q_heads x 256), k (kv_heads x 256), v (kv_heads x 256), +// then the gate (q_heads x 256). +// - q and k get an RMS norm for each head, times their norm weights, which the weight file stores +// as 1 + w. RoPE then turns the first `rot` values of each head (rotate_half inside those +// values), and leaves the others. +// - Attention with the scale 1/sqrt(256) over the KV cache, which is f16 [position, kv_head, 256]. +// - The output is multiplied by sigmoid(gate). +// +// The attention has the design of `vec_attention` (llama.cpp's kernel_flash_attn_ext_vec, MIT +// License, Copyright (c) 2023-2026 The ggml authors), for 256 values a head: each block is a SIMD +// group of one head of q, and lane l owns values 8 l to 8 l + 7. +import core::num; +import std::nn; +import qwen::simd; + +/// The norms and RoPE of q and k at position `pos`, and the store of k and v into the caches. Block h +/// does head h of q, then the heads of k. `cos` and `sin` have rot / 2 values for each position. +fn gated_norm_rope_and_store(q_out : &mut Tensor, k_cache : &mut Tensor, v_cache : &mut Tensor, qkvg : &Tensor, q_norm : &Tensor, k_norm : &Tensor, cos : &Tensor, sin : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, rot : i32, eps : f32) -> void { + let half = rot / 2; + assert(q_out.extent(0) == q_heads && q_out.extent(1) == 256, "gated_norm_rope_and_store: q_out must be [q_heads, 256]"); + assert(k_cache.extent(0) > pos && k_cache.extent(1) == kv_heads && k_cache.extent(2) == 256 && v_cache.extent(0) > pos && v_cache.extent(1) == kv_heads && v_cache.extent(2) == 256, "gated_norm_rope_and_store: the caches must be [positions, kv_heads, 256] with a row for pos"); + assert(qkvg.len() >= (2 * q_heads + 2 * kv_heads) * 256 && q_norm.len() >= 256 && k_norm.len() >= 256, "gated_norm_rope_and_store: a tensor is too short"); + assert(rot % 2 == 0 && rot <= 256 && pos < cos.extent(0) && pos < sin.extent(0) && half <= cos.extent(1) && half <= sin.extent(1), "gated_norm_rope_and_store: `cos` and `sin` need a row for `pos` with rot / 2 values"); + spawn on(Topology::Device) { + for h in 0..q_heads + kv_heads across blocks { + let mut x = unsafe { Tensor::uninit() }; + let mut part = unsafe { Tensor::uninit() }; + for i in 0..256 across lanes { + let a = qkvg[h * 256 + i]; + x[i] = a; + part[i] = a * a; + } + let ss = lanes::sum(&part, 256); + let inv = 1.0 / (ss / 256.0 + eps).sqrt(); + for i in 0..256 across lanes { + let mut w = q_norm[i]; + if h >= q_heads { + w = k_norm[i]; + } + let a = x[i] * inv * w; + let mut r = a; + if i < rot { + // Value i, its partner, and the angle that they share. + let mut j = i; + let mut sign : f32 = -1.0; + let mut partner = i + half; + if i >= half { + j = i - half; + sign = 1.0; + partner = i - half; + } + let mut wp = q_norm[partner]; + if h >= q_heads { + wp = k_norm[partner]; + } + let b = x[partner] * inv * wp; + r = a * cos[pos][j] + sign * b * sin[pos][j]; + } + if h < q_heads { + q_out[h][i] = r; + } else { + k_cache[pos][h - q_heads][i] = r as f16; + v_cache[pos][h - q_heads][i] = qkvg[(q_heads + kv_heads + h - q_heads) * 256 + i] as f16; + } + } + } + } + return; +} + +/// The attention of the token at position `pos`, times sigmoid(gate): y[h * 256 + d] for each head +/// h of q. `part` is scratch space from `gated_attention_scratch`. +fn gated_attention(y : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, qkvg : &Tensor, pos : i32, q_heads : i32, kv_heads : i32) -> void { + assert(q.extent(0) == q_heads && q.extent(1) == 256 && q_heads % kv_heads == 0, "gated_attention: q must be [q_heads, 256], and q_heads a multiple of kv_heads"); + assert(k_cache.extent(0) > pos && k_cache.extent(1) == kv_heads && k_cache.extent(2) == 256 && v_cache.extent(0) > pos && v_cache.extent(1) == kv_heads && v_cache.extent(2) == 256, "gated_attention: the caches must be [positions, kv_heads, 256] with a row for pos"); + assert(part.extent(0) >= q_heads && part.extent(1) >= 64 && part.extent(2) == 260, "gated_attention: `part` is too small. Make it with gated_attention_scratch"); + assert(y.len() >= q_heads * 256 && qkvg.len() >= (2 * q_heads + 2 * kv_heads) * 256, "gated_attention: a tensor is too short"); + let mut nwg = 32; + if 2 * nwg * 32 < pos + 1 { + nwg = nwg * 2; + } + gated_attention_parts(part, q, k_cache, v_cache, pos, q_heads, q_heads / kv_heads, nwg, 0.0625); + gated_attention_merge(y, part, qkvg, nwg, q_heads, (q_heads + 2 * kv_heads) * 256); + return; +} + +/// The scratch space of `gated_attention`, on the CPU: up to 64 parts for each head of q, each the sum +/// of V (256 values), the largest score, and the sum of the weights. +fn gated_attention_scratch(q_heads : i32) -> Tensor { + return Tensor([q_heads, 64, 260]); +} + +/// The parts of `gated_attention`. Block (h, w) is a SIMD group for head h of q. It does the blocks of +/// 32 positions w, w + nwg, w + 2 nwg, ... up to `pos`, and writes part[h][w]: the sum of V, not +/// divided, then the largest score and the sum of the weights. For each row, the lanes add up their +/// parts of q . k, and lane r keeps the score of row r. Each lane then takes the weight of each row +/// from the lane that keeps it, for the sum of V. +fn gated_attention_parts(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, group : i32, nwg : i32, scale : f32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for w in 0..nwg across blocks { + let mut stats = unsafe { Tensor::uninit() }; + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let g = h / group; + let d = 8 * l; + let q0 = q[h][d] * scale; + let q1 = q[h][d + 1] * scale; + let q2 = q[h][d + 2] * scale; + let q3 = q[h][d + 3] * scale; + let q4 = q[h][d + 4] * scale; + let q5 = q[h][d + 5] * scale; + let q6 = q[h][d + 6] * scale; + let q7 = q[h][d + 7] * scale; + let mut big : f32 = -3.0e38; + let mut total : f32 = 0.0; + let mut o0 : f32 = 0.0; + let mut o1 : f32 = 0.0; + let mut o2 : f32 = 0.0; + let mut o3 : f32 = 0.0; + let mut o4 : f32 = 0.0; + let mut o5 : f32 = 0.0; + let mut o6 : f32 = 0.0; + let mut o7 : f32 = 0.0; + let chunks = (pos + 32) / 32; + let mut c = w; + while c < chunks { + let r0 = c * 32; + let mut mine : f32 = -3.0e38; + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > pos { + kept = pos; + } + let k0 = half4_at(k_cache, kept, g, d, 0); + let k1 = half4_at(k_cache, kept, g, d, 1); + let k2 = half4_at(k_cache, kept, g, d, 2); + let k3 = half4_at(k_cache, kept, g, d, 3); + let k4 = half4_at(k_cache, kept, g, d + 4, 0); + let k5 = half4_at(k_cache, kept, g, d + 4, 1); + let k6 = half4_at(k_cache, kept, g, d + 4, 2); + let k7 = half4_at(k_cache, kept, g, d + 4, 3); + let mut score = simd_sum(((k0 * q0 + k1 * q1) + (k2 * q2 + k3 * q3)) + ((k4 * q4 + k5 * q5) + (k6 * q6 + k7 * q7))); + if row > pos { + score = -3.0e38; + } + if r == l { + mine = score; + } + } + let top = big.max(simd_max(mine)); + let shrink = (big - top).fast_exp(); + let p = (mine - top).fast_exp(); + total = total * shrink + simd_sum(p); + o0 = o0 * shrink; + o1 = o1 * shrink; + o2 = o2 * shrink; + o3 = o3 * shrink; + o4 = o4 * shrink; + o5 = o5 * shrink; + o6 = o6 * shrink; + o7 = o7 * shrink; + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > pos { + kept = pos; + } + let pr = simd_value(p, r); + o0 = o0 + half4_at(v_cache, kept, g, d, 0) * pr; + o1 = o1 + half4_at(v_cache, kept, g, d, 1) * pr; + o2 = o2 + half4_at(v_cache, kept, g, d, 2) * pr; + o3 = o3 + half4_at(v_cache, kept, g, d, 3) * pr; + o4 = o4 + half4_at(v_cache, kept, g, d + 4, 0) * pr; + o5 = o5 + half4_at(v_cache, kept, g, d + 4, 1) * pr; + o6 = o6 + half4_at(v_cache, kept, g, d + 4, 2) * pr; + o7 = o7 + half4_at(v_cache, kept, g, d + 4, 3) * pr; + } + big = top; + c = c + nwg; + } + part[h][w][d] = o0; + part[h][w][d + 1] = o1; + part[h][w][d + 2] = o2; + part[h][w][d + 3] = o3; + part[h][w][d + 4] = o4; + part[h][w][d + 5] = o5; + part[h][w][d + 6] = o6; + part[h][w][d + 7] = o7; + // Every lane has the same largest score and sum of the weights. Lanes 0 and 1 keep them for + // the next loop. + if l < 2 { + let mut x = big; + if l == 1 { + x = total; + } + stats[s][l] = x; + } + } + for l in 0..2 across lanes(32) { + part[h][w][256 + l] = stats[s][l]; + } + } + } + } + } + return; +} + +/// Merges the first `parts` parts of `gated_attention_parts` for each head of q, and multiplies by +/// sigmoid of the gate, which starts at `gate_at` of `qkvg`. A block of 32 lanes does 32 values of one +/// head, a value for each lane. +fn gated_attention_merge(y : &mut Tensor, part : &Tensor, qkvg : &Tensor, parts : i32, q_heads : i32, gate_at : i32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for dq in 0..8 across blocks { + let mut top = unsafe { Tensor::uninit() }; + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let mut m : f32 = -3.0e38; + let mut c = l; + while c < parts { + m = m.max(part[h][c][256]); + c = c + 32; + } + top[s][l] = m; + } + let big = lanes::max(&top[s], 32); + for l in 0..32 across lanes(32) { + let d = dq * 32 + l; + let mut total : f32 = 0.0; + let mut acc : f32 = 0.0; + for c in 0..parts { + let w = (part[h][c][256] - big).fast_exp(); + total = total + w * part[h][c][257]; + acc = acc + w * part[h][c][d]; + } + let gate = qkvg[gate_at + h * 256 + d]; + y[h * 256 + d] = acc / total / (1.0 + (0.0 - gate).fast_exp()); + } + } + } + } + } + return; +} +//===- main.vx - Qwen app ---------------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// Generates tokens with greedy decoding, on the GPU: +// +// vxc src/main.vx --package qwen=src --host default \ +// --machine ~/.vx/current/fleet/m4-uma.vx -- WEIGHTS --tokens 750,75698,1445 --steps 16 +// vxc src/main.vx ... -- WEIGHTS --tokenizer TOKENIZER --prompt "def fibonacci(n):" --steps 64 +// vxc src/main.vx ... -- WEIGHTS --tokenizer TOKENIZER --chat --prompt-file FILE --steps 512 +// +// With --tokens, it prints the lines that `scripts/reference.py` prints, without the margin, and +// then the time of a token. `scripts/compare.py` compares the two outputs. +// +// With --tokenizer, a file of `scripts/convert_tokenizer.py`, the prompt is text: --prompt TEXT or +// --prompt-file FILE. The program prints the prompt and the text that it generates. It stops at a +// special token, such as <|im_end|>, or after --steps tokens. --chat puts the prompt in the chat +// format of the Instruct models and prints only the reply. --lines prints the lines of --tokens +// in place of the text. +import core::convert; +import std::time; +import std::vec; +import qwen::weights; +import qwen::model; +import qwen::qwen35; +import qwen::prefill35; +import qwen::prefill; +import qwen::session; +import qwen::speculate; +import qwen::round; +import qwen::tokenizer; + +/// The options of the command line. +struct Options { + weights : *const i8, + tokens : *const i8, + tokenizer : *const i8, + prompt : *const i8, + prompt_file : *const i8, + steps : *const i8, + has_tokens : bool, + has_tokenizer : bool, + has_prompt : bool, + has_prompt_file : bool, + has_steps : bool, + context : *const i8, + has_context : bool, + requests : *const i8, + has_requests : bool, + replies : *const i8, + has_replies : bool, + session : bool, + chat : bool, + lines : bool, + draft : *const i8, + has_draft : bool, +} + +/// The options of `argv`. Asserts that they are complete and that they fit together. +fn parse_options(argc : i32, argv : *mut *mut i8) -> Options { + assert(argc >= 4, "give: WEIGHTS --tokens 1,2,3 --steps N, or WEIGHTS --tokenizer FILE (--prompt TEXT | --prompt-file FILE) [--chat] [--lines] --steps N"); + let empty : *const i8 = ""; + let mut o = Options { + weights: unsafe { argv[1] }, tokens: empty, tokenizer: empty, prompt: empty, prompt_file: empty, + steps: empty, has_tokens: false, has_tokenizer: false, has_prompt: false, has_prompt_file: false, + has_steps: false, context: empty, has_context: false, requests: empty, has_requests: false, replies: empty, has_replies: false, session: false, chat: false, lines: false, draft: empty, has_draft: false, + }; + let mut i = 2; + while i < argc { + let name = unsafe { argv[i] }; + if same(name, "--chat") { + o.chat = true; + i = i + 1; + } else if same(name, "--session") { + o.session = true; + i = i + 1; + } else if same(name, "--lines") { + o.lines = true; + i = i + 1; + } else { + assert(i + 1 < argc, "give: WEIGHTS --tokens 1,2,3 --steps N, or WEIGHTS --tokenizer FILE (--prompt TEXT | --prompt-file FILE) [--chat] [--lines] --steps N"); + let value = unsafe { argv[i + 1] }; + if same(name, "--tokens") { + o.tokens = value; + o.has_tokens = true; + } else if same(name, "--tokenizer") { + o.tokenizer = value; + o.has_tokenizer = true; + } else if same(name, "--prompt") { + o.prompt = value; + o.has_prompt = true; + } else if same(name, "--prompt-file") { + o.prompt_file = value; + o.has_prompt_file = true; + } else if same(name, "--context") { + o.context = value; + o.has_context = true; + } else if same(name, "--requests") { + o.requests = value; + o.has_requests = true; + } else if same(name, "--replies") { + o.replies = value; + o.has_replies = true; + } else if same(name, "--draft") { + o.draft = value; + o.has_draft = true; + } else { + assert(same(name, "--steps"), "give: WEIGHTS --tokens 1,2,3 --steps N, or WEIGHTS --tokenizer FILE (--prompt TEXT | --prompt-file FILE) [--chat] [--lines] --steps N"); + o.steps = value; + o.has_steps = true; + } + i = i + 2; + } + } + if o.session { + assert(o.has_tokenizer && o.has_context && o.has_requests && o.has_replies && !o.has_tokens && !o.has_prompt && !o.has_prompt_file && !o.has_steps, "give: WEIGHTS --tokenizer FILE --session --context N --requests FILE --replies FILE"); + return o; + } + assert(o.has_steps, "give: WEIGHTS --tokens 1,2,3 --steps N, or WEIGHTS --tokenizer FILE (--prompt TEXT | --prompt-file FILE) [--chat] [--lines] --steps N"); + let one_text = o.has_prompt != o.has_prompt_file; + let no_text = !o.has_prompt && !o.has_prompt_file; + assert((o.has_tokens && no_text) || (o.has_tokenizer && !o.has_tokens && one_text), "give: WEIGHTS --tokens 1,2,3 --steps N, or WEIGHTS --tokenizer FILE (--prompt TEXT | --prompt-file FILE) [--chat] [--lines] --steps N"); + assert(o.has_tokenizer || (!o.chat && !o.lines), "--chat and --lines need --tokenizer"); + return o; +} + +/// The comma-separated numbers of `text`. Asserts that it has only digits and commas, and no empty +/// number. +fn parse_numbers(text : *const i8) -> Vec { + let mut numbers = Vec::new(); + let mut value : i32 = 0; + let mut digits = 0; + let mut empty = false; + let mut i : i64 = 0; + let mut ch = i32::from(unsafe { text[0] }); + while ch != 0 { + if ch == 44 { + empty = empty || digits == 0; + numbers.push(value); + value = 0; + digits = 0; + } else { + assert(ch >= 48 && ch <= 57, "a list of numbers can have only digits and commas"); + value = value * 10 + (ch - 48); + digits = digits + 1; + } + i = i + 1; + ch = i32::from(unsafe { text[i] }); + } + assert(!empty && digits > 0, "an empty number in a comma-separated list"); + numbers.push(value); + return numbers; +} + +/// The number of tokens that text mode runs through the model before it reads them. A read waits +/// for all the work that the GPU was given, and then the GPU has nothing to do until the CPU gives +/// it the next token: about 0.37 ms of a 21.9 ms token on the M4. The input of a token is the +/// argmax of the token before it, in GPU memory, so the GPU can run several tokens without the +/// CPU. Then the GPU waits only once for each AHEAD tokens. Up to AHEAD - 1 tokens after the end +/// of the text are run and thrown away. +const AHEAD : i32 = 8; + +/// The GPU tensor of one token. +struct Slot { + next : Tensor, +} + +/// The token in `t`. Reading it waits for the GPU to finish the work before it. +fn read_token(t : &Tensor) -> i32 { + let h = transfer(t, Memory::CPU_DRAM); + return h[0]; +} + +/// The logit `token` of `logits`. +fn read_logit(logits : &Tensor, token : i32) -> f32 { + let h = transfer(logits, Memory::CPU_DRAM); + return h[token]; +} + +/// Whether the C string `a` is `b`. +fn same(a : *const i8, b : *const i8) -> bool { + return unsafe { strcmp(a, b) } == 0; +} + +/// The token ids of the prompt: the numbers of --tokens, or the tokens of the text. +fn prompt_ids(o : &Options, t : &Tokenizer) -> Vec { + if o.has_tokens { + return parse_numbers(o.tokens); + } + let text = if o.has_prompt { + c_text(o.prompt) + } else { + read_text_file(o.prompt_file) + }; + let full = if o.chat { + chat_text(&text) + } else { + text + }; + let ids = encode(t, full.bytes, full.length); + assert(ids.len() > 0, "the prompt has no tokens"); + return ids; +} + +/// Shows token number `step`, as the loop of `main` does: its text, or a line with its logit. +/// Gives false at the end of the text, where the loop stops. +fn show(t : &Tokenizer, w : &Weights, text_mode : bool, step : i32, token : i32, logit : f32) -> bool { + if text_mode { + if is_special(t, token) || token == w.config.eos_token_id { + return false; + } + write_token(t, token); + } else { + println!("step={} token={} logit={};", step, token, logit); + } + return true; +} + +/// The logit `token` of position j of a round. +fn round_logit(r : &Round, j : i32, token : i32) -> f32 { + let h = transfer(&r.logits, Memory::CPU_DRAM); + return h[j][token]; +} + +/// The loop of `main` with speculative decoding (src/speculate.vx). Each step is a round of the +/// last token and a draft from the context, or a plain step when the draft would not pay: when the +/// longest earlier match of the end of the context is shorter than 6 tokens, or after 2 rounds in a +/// row that accepted nothing, until a longer match than theirs appears. A draft has up to `max` +/// tokens. `first` is the first generated token, from the logits in `s.logits`. Shows the same +/// `steps` tokens as the loop of `main`, and gives the number of tokens after the first. +fn generate_with_drafts(w : &Weights, s : &mut State, t : &Tokenizer, text_mode : bool, prompt : &Vec, first : i32, steps : i32, max : i32, start : &mut Instant) -> i32 { + assert(can_round(w), "--draft needs a model of Q4_0 experts with QK norms, head_dim 128 and a 6-bit lm_head"); + assert(max >= 1 && max < ROUND_MAX, "--draft must be 1 to ROUND_MAX - 1"); + assert(steps >= ROUND_MAX, "--draft needs --steps of at least ROUND_MAX"); + let mut r = new_round(&w.config); + // One run of the round kernels for each n to 8, so that their compile time is not in the time + // of a token: it restarts the clock. Larger rounds use the same kernels. The rounds write rows of + // the KV cache that the steps write again before they read them. + let mut warm = Vec::new(); + for n in 1..9 { + warm.push(first); + run_round(w, s, &mut r, &warm, prompt.len(), n); + } + let _ready = transfer(&r.next, Memory::CPU_DRAM); + *start = Instant::now(); + // The tokens of a run of plain steps: token j is in ring[j]. + let mut ring = Vec::new(); + for j in 0..AHEAD { + ring.push(Slot { + next: transfer(Tensor([1]), Memory::HBM), + }); + } + // The length of the next run of plain steps: 1 after a round, then 2, 4 and up to AHEAD while + // no draft comes up. The GPU runs the tokens of a run before the CPU reads them. Lines mode + // prints the logit of each token, so it reads each one. + let mut run = 1; + let mut context = Vec::new(); + for i in 0..prompt.len() { + context.push(prompt[i]); + } + let mut token = first; + context.push(token); + // The position of `token`, which is not in the KV cache yet. + let mut pos = prompt.len(); + let mut step = 0; + let mut rounds = 0; + let mut drafted = 0; + let mut accepted = 0; + // Rounds in a row that accepted nothing, and the length of the match of the last of them. + let mut misses = 0; + let mut missed_length = 0; + let mut going = show(t, w, text_mode, 0, token, read_logit(&s.logits, token)); + while going && step + 1 < steps { + let room = steps - step - 1; + let m = longest_match(&context); + if misses >= 2 && m.length > missed_length { + misses = 0; + } + let mut k = i32::min(i32::min(draft_length(m.length), max), room - 1); + if misses >= 2 { + k = 0; + } + let draft = tokens_after(&context, m.end, k); + k = draft.len(); + if k == 0 { + // Plain steps, with the kernels of one token each. + let mut n = 1; + if text_mode { + n = i32::min(run, room); + } + let mut h = Tensor([1]); + h[0] = token; + let input = transfer(h, Memory::HBM); + run_layers(w, s, &input, pos); + predict(w, s, &mut ring[0].next); + for j in 1..n { + run_layers(w, s, &ring[j - 1].next, pos + j); + predict(w, s, &mut ring[j].next); + } + let mut j = 0; + while j < n && going { + token = read_token(&ring[j].next); + context.push(token); + step = step + 1; + pos = pos + 1; + let mut logit : f32 = 0.0; + if !text_mode { + logit = read_logit(&s.logits, token); + } + going = show(t, w, text_mode, step, token, logit); + j = j + 1; + } + run = i32::min(run * 2, AHEAD); + } else { + run = 1; + let mut inputs = Vec::new(); + inputs.push(token); + for i in 0..k { + inputs.push(draft[i]); + } + run_round(w, s, &mut r, &inputs, pos, k + 1); + let choice = transfer(&r.next, Memory::CPU_DRAM); + rounds = rounds + 1; + drafted = drafted + k; + // c0 is the next token; each draft token that equals the choice before it adds the next one. + let mut j = 0; + let mut more = true; + while more && going { + token = choice[j]; + context.push(token); + step = step + 1; + let mut logit : f32 = 0.0; + if !text_mode { + logit = round_logit(&r, j, token); + } + going = show(t, w, text_mode, step, token, logit); + more = j < k && draft[j] == token; + if more { + accepted = accepted + 1; + j = j + 1; + } + } + pos = pos + j + 1; + if j == 0 { + misses = misses + 1; + missed_length = m.length; + } else { + misses = 0; + } + } + } + println!("rounds={} drafted={} accepted={};", rounds, drafted, accepted); + return step; +} + +/// `main` for a Qwen3.5 or Qwen3.6 model (weight file v2, arch 1). The prompt runs in chunks +/// (src/prefill35.vx). There are no drafts yet (#89). Prints the same lines \ No newline at end of file diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/context/vx/ctx512.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/context/vx/ctx512.txt new file mode 100644 index 0000000..f266cda --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/context/vx/ctx512.txt @@ -0,0 +1,43 @@ +//===- model.vx - Qwen app --------------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// One token of a Qwen2 or Qwen3 MoE decoder on the GPU, with the kernels of `std::nn`. `State` +// holds every tensor that a token writes, and the KV cache. It is made once, before the first +// token, so the token loop allocates nothing. +import core::convert; +import core::num; +import std::nn; +import std::vec; +import qwen::attention; +import qwen::products; +import qwen::q6; +import qwen::weights; + +/// The keys and the values of every position so far, for one layer: [max_seq, kv_heads, head_dim]. +/// They are f16, half the memory of f32. The kernels compute in f32, and round only what they +/// store here. +struct Cache { + k : Tensor, + v : Tensor, +} + +/// The tensors of a mixture-of-experts layer: the router's score of each expert, the chosen +/// experts and their weights, and the SwiGLU output of each chosen expert, [experts_per_token, +/// moe_intermediate_size]. +struct Experts { + router_logits : Tensor, + ids : Tensor, + weights : Tensor, + mlp : Tensor, +} + +/// The tensors that a token writes, in GPU memory, and one `Cache` for each layer. `cos` and `sin` +/// are [max_seq, head_dim / 2]. +struct State { + max_seq : i32, + x : Tensor, + xn : Tensor, + v : Tensor, +} + +/// The tensors of a mixture-of-experts layer: the router's score of each expert, the chosen +/// experts and their weights, and the SwiGLU output of each chosen expert, [experts_per_token, +/// moe_intermediate_size]. +struct Experts { + router_logits : Tensor, + ids : Tensor, + weights : Tensor, + mlp : Tensor, +} + +/// The tensors that a token writes, in GPU memory, and one `Cache` for each layer. `cos` and `sin` +/// are [max_seq, head_dim / 2]. +struct State { + max_seq : i32, + x : Tensor, + xn : Tensor, + q : Tensor, + k : Tensor, + v : Tensor, + q_turned : Tensor, + attended : Tensor, + attention_parts : Tensor, + vec_parts : Tensor, + mlp : Tensor, + experts : Experts, + logits : Tensor, + cos : Tensor, + sin : Tensor, + caches : Vec, +} + +/// The state for up to `max_seq` positions. The angles of RoPE are computed in f64, as in +/// `reference.py`, and rounded to f32 once. +fn new_state(c : &Config, max_seq : i32) -> State { + assert(max_seq > 0 && max_seq <= c.max_positions, "max_seq must be between 1 and the max_positions of the model"); + let half = c.head_dim / 2; + let mut hcos = Tensor([max_seq, half]); + let mut hsin = Tensor([max_seq, half]); + for p in 0..max_seq { + for i in 0..half { + let angle = f64::from(p) / f64::powf(c.rope_theta, f64::from(2 * i) / f64::from(c.head_dim)); + hcos[p][i] = f64::cos(angle) as f32; + hsin[p][i] = f64::sin(angle) as f32; + } + } + // A dense model uses none of the tensors of the experts, so one value each is enough. + let experts = i32::max(c.num_experts, 1); + let chosen = i32::max(c.experts_per_token, 1); + let moe_inter = i32::max(c.moe_intermediate_size, 1); + // The flash attention of a prompt reads the cache in blocks of 64 positions. + let rows = (max_seq + 63) / 64 * 64; + let mut caches = Vec::new(); + for l in 0..c.num_layers { + caches.push(Cache { + k: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([rows, c.num_kv_heads, c.head_dim]), Memory::HBM), + }); + } + return State { + max_seq: max_seq, + x: transfer(Tensor([c.hidden_size]), Memory::HBM), + xn: transfer(Tensor([c.hidden_size]), Memory::HBM), + q: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + k: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + v: transfer(Tensor([c.num_kv_heads, c.head_dim]), Memory::HBM), + q_turned: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attended: transfer(Tensor([c.num_q_heads, c.head_dim]), Memory::HBM), + attention_parts: transfer(split_attention_scratch(max_seq, c.num_q_heads, c.num_kv_heads, c.head_dim), Memory::HBM), + vec_parts: transfer(vec_attention_scratch(c.num_q_heads), Memory::HBM), + mlp: transfer(Tensor([c.intermediate_size]), Memory::HBM), + experts: Experts { + router_logits: transfer(Tensor([experts]), Memory::HBM), + ids: transfer(Tensor([chosen]), Memory::HBM), + weights: transfer(Tensor([chosen]), Memory::HBM), + mlp: transfer(Tensor([chosen, moe_inter]), Memory::HBM), + }, + logits: transfer(Tensor([c.vocab_size]), Memory::HBM), + cos: transfer(hcos, Memory::HBM), + sin: transfer(hsin, Memory::HBM), + caches: caches, + }; +} + +/// y = m x, with the kernel for the dtype of `m`, which has `rows` x `cols` weights. +fn matvec(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U6 { + matvec_q6(y, &m.codes, &m.high, &m.group_scales, x, rows, cols); + } else if m.dtype == U4 { + nn_matvec_q4(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x. +fn matvec_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_matvec_q4_add(y, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_add(y, &m.codes, &m.scales, x, rows, cols); + } else { + nn_matvec_add(y, &m.bf16, x, rows, cols); + } + return; +} + +/// y += m x, for x of [heads, head_dim]. +fn matvec_heads_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, heads : i32, head_dim : i32) -> void { + if m.dtype == U4 { + matvec_q4_heads_add_blocks(y, &m.codes, &m.group_scales, x, rows, heads, head_dim); + } else if m.dtype == F8E4M3 { + nn_matvec_fp8_heads_add(y, &m.codes, &m.scales, x, rows, heads, head_dim); + } else { + nn_matvec_heads_add(y, &m.bf16, x, rows, heads, head_dim); + } + return; +} + +/// The Q, K and V of x: m x + b, split by heads. +fn qkv(q : &mut Tensor, k : &mut Tensor, v : &mut Tensor, m : &WeightMatrix, b : &Tensor, x : &Tensor, c : &Config) -> void { + if m.dtype == U4 { + qkv_q4_blocks(q, k, v, &m.codes, &m.group_scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } else if m.dtype == F8E4M3 { + nn_qkv_fp8(q, k, v, &m.codes, &m.scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } else { + nn_qkv(q, k, v, &m.bf16, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); + } + return; +} + +/// The SwiGLU of a dense MLP, for the gate rows and then the up rows of `m`. +fn swiglu(out : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { + if m.dtype == U4 { + nn_swiglu_q4(out, &m.codes, &m.group_scales, x, rows, cols); + } else if m.dtype == F8E4M3 { + nn_swiglu_fp8(out, &m.codes, &m.scales, x, rows, cols); + } else { + nn_swiglu(out, &m.bf16, x, rows, cols); + } + return; +} + +/// The mixture of experts of a layer: the router chooses experts_per_token experts and their +/// weights, and x gets the sum of their outputs for xn, each times its weight. +fn add_experts(e : &mut Experts, x : &mut Tensor, xn : &Tensor, layer : &Layer, c : &Config) -> void { + let k = c.experts_per_token; + let inter = c.moe_intermediate_size; + nn_matvec(&mut e.router_logits, &layer.router, xn, c.num_experts, c.hidden_size); + nn_top_k(&mut e.ids, &mut e.weights, &e.router_logits, c.num_experts, k); + let gate_up = &layer.gate_up; + let down = &layer.down; + if gate_up.dtype == U4 { + moe_swiglu_q4_blocks(&mut e.mlp, &gate_up.codes, &gate_up.group_scales, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + moe_down_q4_add_blocks(x, &down.codes, &down.group_scales, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + } else { + assert(gate_up.dtype == BF16, "the experts of a mixture-of-experts model must be bf16 or Q4_0"); + nn_moe_swiglu(&mut e.mlp, &gate_up.bf16, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + nn_moe_down_add(x, &down.bf16, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + } + return; +} + +/// Runs the token in `token` at position `pos` through every layer. The hidden state of the +/// token is then in `s.x`, and its keys and values are in the caches. +fn run_layers(w : &Weights, s : &mut State, token : &Tensor, pos : i32) -> void { + let c = &w.config; + let eps = c.rms_norm_eps as f32; + assert(pos >= 0 && pos < s.max_seq, "the position is past the end of the KV cache"); + nn_embed(&mut s.x, &w.embed, token, c.hidden_size); + let mut l = 0; + for cache in s.caches.iter_mut() { + let layer = &w.layers[l]; + nn_rms_norm(&mut s.xn, &s.x, &layer.attn_norm, c.hidden_size, eps); + qkv(&mut s.q, &mut s.k, &mut s.v, &layer.qkv, &layer.qkv_bias, &s.xn, c); + if c.qk_norm { + norm_rope_and_store(&mut s.q_turned, &mut cache.k, &mut cache.v, &s.q, &s.k, &s.v, &layer.q_norm, &layer.k_norm, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.head_dim, eps); + } else { + rope_and_store(&mut s.q_turned, &mut cache.k, &mut cache.v, &s.q, &s.k, &s.v, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } + if c.head_dim == 128 { + vec_attention(&mut s.attended, &mut s.vec_parts, &s.q_turned, &cache.k, &cache.v, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } else { + split_attention(&mut s.attended, &mut s.attention_parts, &s.q_turned, &cache.k, &cache.v, pos, c.num_q_heads, c.num_kv_heads, c.head_dim); + } + matvec_heads_add(&mut s.x, &layer.attn_out, &s.attended, c.hidden_size, c.num_q_heads, c.head_dim); + nn_rms_norm(&mut s.xn, &s.x, &layer.mlp_norm, c.hidden_size, eps); + if c.num_experts > 0 { + add_experts(&mut s.experts, &mut s.x, &s.xn, layer, c); + } else { + swiglu(&mut s.mlp, &layer.gate_up, &s.xn, c.intermediate_size, c.hidden_size); + matvec_add(&mut s.x, &layer.down, &s.mlp, c.hidden_size, c.intermediate_size); + } + l = l + 1; + } + return; +} + +/// The logits of the token whose hidden state is in `s.x`, and in `next` the index of the largest +/// one. Both stay in GPU memory. +fn predict(w : &Weights, s : &mut State, next : &mut Tensor) -> void { + let c = &w.config; + nn_rms_norm(&mut s.xn, &s.x, &w.final_norm, c.hidden_size, c.rms_norm_eps as f32); + if c.tied_embeddings { + nn_matvec(&mut s.logits, &w.embed, &s.xn, c.vocab_size, c.hidden_size); + } else { + matvec(&mut s.logits, &w.lm_head, &s.xn, c.vocab_size, c.hidden_size); + } + nn_argmax(next, &s.logits, c.vocab_size); + return; +} +//===- attention.vx - Qwen app ----------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// The attention of one generated token, with the positions split among blocks. This is a copy of +// `nn_attention` and its kernels from `std::nn` on Vx main (vx-lang/Vx#3216), with `split_` in place +// of `nn_` in their names. Vx v0.0.4 has the older `nn_attention`, which has one block for each head +// of Q, so its time grows with the number of positions. Remove this file, and call `nn_attention` +// of `std::nn`, when a Vx release has the new one (#4). +// +// `vec_attention`, for head_dim 128, has the design of llama.cpp's flash attention for one token +// (kernel_flash_attn_ext_vec and kernel_flash_attn_ext_vec_reduce), MIT License, Copyright (c) 2023-2026 +// The ggml authors. scripts/mlir_kernels/decode_attention.py writes its kernels: change that script, not +// the MLIR. +import core::num; +import std::nn; + +/// Attention of the token at position `pos` over rows 0 to `pos` of the KV cache, with a softmax +/// of the scores q . k / sqrt(head_dim). `part` is scratch space from `split_attention_scratch`. +/// +/// The blocks of the first kernel split the positions, 32 to a block below position 640 and 64 from +/// there on. A block serves the 8 heads of Q that share a head of K and V, so it reads each row of +/// the cache once for all 8. A second kernel merges the parts of the blocks for each head. +fn split_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_heads % kv_heads == 0, "split_attention: q_heads must be a multiple of kv_heads"); + assert(head_dim % 32 == 0 && head_dim <= 128, "split_attention: head_dim must be a multiple of 32, and at most 128"); + let mut n_pos = 32; + if pos >= 640 { + n_pos = 64; + } + assert(part.extent(0) >= kv_heads * ((q_heads / kv_heads + 7) / 8) && part.extent(1) >= (pos + n_pos) / n_pos && part.extent(2) >= 8 && part.extent(3) >= head_dim + 2, "split_attention: `part` is too small for this position. Make it with split_attention_scratch"); + if n_pos == 32 { + split_attention_parts_32(part, q, k_cache, v_cache, pos, q_heads, kv_heads, head_dim); + } else { + split_attention_parts_64(part, q, k_cache, v_cache, pos, q_heads, kv_heads, head_dim); + } + split_attention_merge(out, part, pos, n_pos, q_heads, kv_heads, head_dim); + return; +} + +/// Attention of the token at position `pos`, as `split_attention`, for head_dim 128, with the kernels of +/// llama.cpp's flash attention for one token. `vec_attention_parts` splits the blocks of 32 positions among +/// `nwg` SIMD groups for each head of Q: 32 of them, or 64 when each of 32 would have more than 2 blocks. +/// (llama.cpp goes on to 4 SIMD groups of 32 a block, but 128 parts are no faster here: their merge costs what +/// they save.) `vec_attention_merge` then merges the parts. `part` is scratch space from +/// `vec_attention_scratch`. +fn vec_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { + nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); + nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); + nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); + nn_check_cache(v_cache.extent(0), v_cache.extent(1), v_cache.extent(2), pos, kv_heads, head_dim); + assert(q_heads % kv_heads == 0 && head_dim == 128, "vec_attention: q_heads must be a multiple of kv_heads, and head_dim 128"); + assert(part.extent(0) >= q_heads && part.extent(1) >= 128 && part.extent(2) == 132, "vec_attention: `part` is too small. Make it with vec_attention_scratch"); + let mut nwg = 32; + if 2 * nwg * 32 < pos + 1 { + nwg = nwg * 2; + } + vec_attention_parts(part, q, k_cache, v_cache, pos, q_heads, q_heads / kv_heads, nwg, 1.0 / (head_dim as f32).sqrt()); + vec_attention_merge(out, part, nwg, q_heads); + return; +} + +/// The scratch space of `vec_attention`, on the CPU: up to 128 parts for each head of Q, each the sum of V +/// (128 values), the largest score, and the sum of the weights. A part has 132 values, so that each starts +/// at a multiple of 16 bytes. +fn vec_attention_scratch(q_heads : i32) -> Tensor { + return Tensor([q_heads, 128, 132]); +} + +/// The parts of `vec_attention`, as llama.cpp's kernel_flash_attn_ext_vec. Block (h, w) is a SIMD group for +/// query head h. It does the blocks of 32 positions w, w + nwg, w + 2 nwg, ... up to `pos`, and writes +/// part[h][w]. Lane l owns values 4 l to 4 l + 3 of the head, so that the 32 lanes read a row of K or V in +/// one 256-byte load. For each row, the lanes add up their parts of q . k; then each lane keeps the score +/// of one row, and the lanes take the weights of the rows from each other for the sum of V. A part is the +/// sum of V, not divided, then the largest score and the sum of the weights. +fn vec_attention_parts(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, group : i32, nwg : i32, scale : f32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for w in 0..nwg across blocks { + let g = h / group; + let _d = mlir!( threads : 32, inputs : (%part = part : memref, %q = q : memref, %k3 = k_cache : memref, %v3 = v_cache : memref, %pos = pos : i32, %nwg = nwg : i32, %scale = scale : f32, %h = h : i32, %w = w : i32, %g = g : i32), returns : i32, dialects : ["arith", "memref", "scf", "gpu", "vector", "math"], ensures : [reads_only(q), reads_only(k_cache), reads_only(v_cache), writes_only(part[h][w])]) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %c4 = arith.constant 4 : index + %c32 = arith.constant 32 : index + %c128 = arith.constant 128 : index + %c129 = arith.constant 129 : index + %c32i = arith.constant 32 : i32 + %neg = arith.constant -3.0e38 : f32 + %zero = arith.constant 0.0 : f32 + %vz4 = arith.constant dense<0.0> : vector<4xf32> + %l = gpu.thread_id x + %l4 = arith.muli %l, %c4 : index + %hi = arith.index_cast %h : i32 to index + %wi = arith.index_cast %w : i32 to index + %gi = arith.index_cast %g : i32 to index + %posi = arith.index_cast %pos : i32 to index + %nwgi = arith.index_cast %nwg : i32 to index + %g128 = arith.muli %gi, %c128 : index + %kd = arith.addi %g128, %l4 : index + %P = memref.dim %k3, %c0 : memref + %KH = memref.dim %k3, %c1 : memref + %Wd = arith.muli %KH, %c128 : index + %k = memref.reinterpret_cast %k3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to memref> + %v = memref.reinterpret_cast %v3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to memref> + %qv = vector.load %q[%hi, %l4] {alignment = 16} : memref, vector<4xf32> + %scv = vector.broadcast %scale : f32 to vector<4xf32> + %qs = arith.mulf %qv, %scv : vector<4xf32> + %nkv = arith.addi %posi, %c32 : index + %chunks = arith.divui %nkv, %c32 : index + %st:3 = scf.for %ic = %wi to %chunks step %nwgi iter_args(%M = %neg, %S = %zero, %o = %vz4) -> (f32, f32, vector<4xf32>) { + %r0 = arith.muli %ic, %c32 : index + %my = scf.for %cc = %c0 to %c32 step %c1 iter_args(%m = %neg) -> (f32) { + %row = arith.addi %r0, %cc : index + %rowc = arith.minui %row, %posi : index + %kh = vector.load %k[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> + %kf = arith.extf %kh : vector<4xf16> to vector<4xf32> + %pr = arith.mulf %kf, %qs : vector<4xf32> + %pl = vector.reduction , %pr : vector<4xf32> into f32 + %sc = gpu.subgroup_reduce add %pl : (f32) -> f32 + %live = arith.cmpi ule, %row, %posi : index + %scm = arith.select %live, %sc, %neg : f32 + %mine = arith.cmpi eq, %cc, %l : index + %m2 = arith.select %mine, %scm, %m : f32 + scf.yield %m2 : f32 + } + %bm = gpu.subgroup_reduce maxnumf %my : (f32) -> f32 + %Mn = arith.maxnumf %M, %bm : f32 + %dm = arith.subf %M, %Mn : f32 + %ms = math.exp %dm : f32 + %dp = arith.subf %my, %Mn : f32 + %p = math.exp %dp : f32 + %bs = gpu.subgroup_reduce add %p : (f32) -> f32 + %Ss = arith.mulf %S, %ms : f32 + %Sn = arith.addf %Ss, %bs : f32 + %msv = vector.broadcast %ms : f32 to vector<4xf32> + %o1 = arith.mulf %o, %msv : vector<4xf32> + %o2 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%oa = %o1) -> (vector<4xf32>) { + %row = arith.addi %r0, %cc : index + %rowc = arith.minui %row, %posi : index + %vh = vector.load %v[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> + %vf = arith.extf %vh : vector<4xf16> to vector<4xf32> + %cci = arith.index_cast %cc : index to i32 + %pc, %pv = gpu.shuffle idx %p, %cci, %c32i : f32 + %pcv = vector.broadcast %pc : f32 to vector<4xf32> + %on = vector.fma %vf, %pcv, %oa : vector<4xf32> + scf.yield %on : vector<4xf32> + } + scf.yield %Mn, %Sn, %o2 : f32, f32, vector<4xf32> + } + vector.store %st#2, %part[%hi, %wi, %l4] : memref, vector<4xf32> + %lane0 = arith.cmpi eq, %l, %c0 : index + scf.if %lane0 { + memref.store %st#0, %part[%hi, %wi, %c128] : memref + memref.store %st#1, %part[%hi, %wi, %c129] : memref + } + macro.yield %h : i32 + }; + } + } + } + return; +} + +/// Merges the first `parts` parts of `vec_attention_parts` for each head of Q, as llama.cpp's +/// kernel_flash_attn_ext_vec_reduce. A block of 4 SIMD groups does one head: each lane weighs up to 4 parts, +/// and the SIMD groups add them up for 4 values of the head at a time. +fn vec_attention_merge(out : &mut Tensor, part : &Tensor, parts : i32, q_heads : i32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + let _d = mlir!( threads : 128, inputs : (%out = out : memref, %part \ No newline at end of file diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/complete1.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/complete1.txt new file mode 100644 index 0000000..12241e6 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/complete1.txt @@ -0,0 +1,102 @@ +<|im_start|>user +`src/hir/flatten/affine.rs`: + +```rust +//===- affine.rs - Vx Compiler --------------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Counted loops that the code generator writes as `affine.for`, so that the affine passes can +// fuse and tile them. docs/discussions/loop_optimizations_in_the_frontend_and_in_mlir.md has the +// rules. +// +//===----------------------------------------------------------------------===// + +use super::*; +use crate::bytecode::AFFINE_FOR_BRANCHES; + +/// Whether the body of a loop can be the body of an `affine.for`: nothing in it leaves the loop, +/// and it holds no region that the MLIR passes lower by splitting its block. +pub(super) fn affine_body(body: &[Statement]) -> bool { + stays_in(body, false) +} + +/// Whether nothing in `stmts` leaves the loop. In a nested loop, `in_loop` is set, and a +/// `break` or `continue` stays in that loop. +fn stays_in(stmts: &[Statement], in_loop: bool) -> bool { + stmts.iter().all(|s| match s { + Statement::Return(_) => false, + Statement::Break(_) | Statement::Continue(_) => in_loop, + Statement::ForLoop(f) => { + exprs_stay_in(std::slice::from_ref(s), in_loop) && stays_in(&f.body, true) + } + Statement::Loop(l) => { + exprs_stay_in(std::slice::from_ref(s), in_loop) && stays_in(&l.body, true) + } + // An unexpanded macro may hold anything. + Statement::MacroCall(_) | Statement::Error(_) => false, + _ => exprs_stay_in(std::slice::from_ref(s), in_loop), + }) +} + +/// Whether the expressions of `stmts`, and the blocks in them, stay in the loop. +fn exprs_stay_in(stmts: &[Statement], in_loop: bool) -> bool { + let mut ok = true; + let mut check = |e: &Expr| { + ok &= match e { + Expr::If(i) => { + stays_in(&i.then_block, in_loop) + && i.else_block.as_ref().is_none_or(|b| stays_in(b, in_loop)) + } + Expr::Match(m) => m.arms.iter().all(|a| stays_in(&a.body, in_loop)), + // The checker makes a `tasks` block and a task body an `UnsafeBlock` with a `task` + // mark, and the lowering of a task splits its block. + Expr::UnsafeBlock(b) => b.task.is_none() && stays_in(&b.stmts, in_loop), + Expr::ComptimeBlock(b) => stays_in(&b.stmts, in_loop), + Expr::SpawnOn(_) + | Expr::TaskBlock(_) + | Expr::InlineMlir(_) + | Expr::Closure(_) + | Expr::MacroCall(_) => false, + _ => true, + } + }; + for s in stmts { + // A nested loop's body is checked by `stays_in`. Only its own expressions are here. + match s { + Statement::ForLoop(f) => { + crate::syntax::visit_expr(&f.iterable, &mut check); + f.invariants + .iter() + .for_each(|e| crate::syntax::visit_expr(e, &mut check)); + } + Statement::Loop(l) => l + .invariants + .iter() + .for_each(|e| crate::syntax::visit_expr(e, &mut check)), + _ => crate::syntax::visit_exprs(std::slice::from_ref(s), &mut check), + } + } + ok +} + +impl Lowerer<'_> { + /// Whether `v` can be a bound of an `affine.for` here: a constant, a value from before the + /// outermost open affine loop, or the variable of an open affine loop. + fn affine_bound(&self, v: &Val) -> bool { + let r = v.reg.0 as usize; + match self.affine_open.first() { + None => true, +``` + +This file stops in the middle. Continue it from exactly where it stops. Output only the rest of the file.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/complete2.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/complete2.txt new file mode 100644 index 0000000..1a872a5 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/complete2.txt @@ -0,0 +1,112 @@ +<|im_start|>user +`utils/memalg/shakedown.py`: + +```python +#!/usr/bin/env python3 +"""Predict -> measure -> compare, end to end. + +The dry run. Its output is an error table for one memory link on the machine we already +own, and its purpose is to find bugs in OUR harness -- a wrong formula, a mislabeled column, a +unit mismatch -- before any GPU time is paid for. The MLSys admission matrix was dry-run the same +way and it caught an 8x arithmetic error before any money was spent. + +Three steps, each of which can fail loudly: + + predict generate a Vx program that transfers a tile of each swept size, compile it against the + machine file, and harvest `--diagnostics-json` -> predicted picoseconds per hop. + measure run the C benchmark -> achieved copy time per size. + compare join on byte count, report signed relative error. + +The join is on `bytes`, which is why the extractor had to emit it: without a byte +count in the prediction record there is nothing to join on and the two halves cannot be related at +all. +""" + +import argparse +import csv +import json +import os +import subprocess +import sys +import tempfile + +# The tile shapes swept. Square f32 tiles, so bytes = 4*d*d; chosen so the byte counts line up +# with the measurement's powers of two. +DIMS = [32, 64, 128, 256, 512, 1024, 2048, 4096] + + +def tile_bytes(d): + return 4 * d * d + + +def predict(vxc, machine, workdir): + """Compile one probe program per size and harvest its predicted hop costs. + + One program per size rather than one program with every size: the resident-set check would + reject a program holding every tile at once, and a rejected compile emits no routes. + """ + out = {} + for d in DIMS: + src = os.path.join(workdir, f"probe_{d}.vx") + with open(src, "w") as f: + f.write( + "fn main() -> i32 {\n" + f" let tile : Tensor = Tensor([{d}, {d}]);\n" + " let _h = transfer(tile, Memory::HBM);\n" + " return 0;\n" + "}\n" + ) + js = os.path.join(workdir, f"probe_{d}.json") + proc = subprocess.run( + [vxc, "--machine", machine, src, "--diagnostics-json", js, "--emit-mlir"], + capture_output=True, + text=True, + ) + if not os.path.exists(js): + print(f" !! no diagnostics for {d}x{d}: {proc.stderr.strip()[:200]}", file=sys.stderr) + continue + rec = json.load(open(js)) + for r in rec.get("routes", []): + if r["path"] == ["CPU_DRAM", "HBM"] and r.get("derived_cost") is not None: + if r.get("derived_unit") != "ps": + # A cycle-denominated cost cannot be compared against a wall-clock measurement + # without a declared clock. Refusing beats silently treating cycles as ps. + print( + f" !! {d}x{d}: predicted unit is {r['derived_unit']}, not ps -- " + "cannot compare against wall-clock without a clock figure", + file=sys.stderr, + ) + continue + out[r["bytes"]] = r["derived_cost"] + return out + + +def measure(binary): + proc = subprocess.run([binary], capture_output=True, text=True, check=True) + rows = {} + for row in csv.DictReader(proc.stdout.splitlines()): + rows[int(row["bytes"])] = { + "ns": float(row["median_ns"]), + "q1": float(row["q1_ns"]), + "q3": float(row["q3_ns"]), + "copy_gbps": float(row["copy_GBps"]), + "traffic_gbps": float(row["traffic_GBps"]), + } + return rows + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--vxc", default="target/release/vxc") + ap.add_argument("--machine", default="fleet/m4-uma.vx") + ap.add_argument("--bench", default="utils/memalg/measure_link") + ap.add_argument("--out", default=None, help="write the error table here as CSV") +``` + +This file stops in the middle. Continue it from exactly where it stops. Output only the rest of the file.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/complete3.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/complete3.txt new file mode 100644 index 0000000..8ba9deb --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/complete3.txt @@ -0,0 +1,134 @@ +<|im_start|>user +`stdlib/rust_core/src/io.rs`: + +```rust +//===- io.rs - Vx Compiler -------------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file implements the standard library I/O primitives. +// It contains the Rust-side FFI implementations for file system operations, +// console printing, and basic input/output functionality exposed to Vx programs. +// +//===----------------------------------------------------------------------===// +//! FFI bindings for `std::fs::File`. + +use crate::{instantiate_file_ffi, instantiate_stdio_ffi}; + +instantiate_file_ffi!(crate::ffi::io::off_the_worker); +instantiate_stdio_ffi!(); + +/// While a task runs, each thread keeps what it prints until a newline, and then writes the +/// whole line at once. So the lines of tasks that print at the same time do not mix. With no +/// task running, each piece is written at once, as before, so its order with output from C is +/// the order of the calls. +pub(crate) mod lines { + use std::cell::RefCell; + use std::io::Write; + use std::sync::atomic::{AtomicUsize, Ordering}; + + static RUNNING_TASKS: AtomicUsize = AtomicUsize::new(0); + + thread_local! { + static LINE: RefCell> = const { RefCell::new(Vec::new()) }; + /// Set between the two `vx_print_to_stderr` calls around an `eprint!` or a `panic`. + static TO_STDERR: std::cell::Cell = const { std::cell::Cell::new(false) }; + } + + pub(crate) fn set_stderr(on: bool) { + TO_STDERR.with(|flag| flag.set(on)); + } + + /// Swaps the line and the stderr flag of this thread with these. The shared runtime gives + /// each fiber its own, so that the lines of two fibers on one thread do not mix. + pub(crate) fn swap_with_thread(line: &mut Vec, to_stderr: &mut bool) { + LINE.with(|l| std::mem::swap(&mut *l.borrow_mut(), line)); + TO_STDERR.with(|flag| *to_stderr = flag.replace(*to_stderr)); + } + + /// Takes what this thread keeps of its line. + #[cfg(test)] + pub(crate) fn take_line() -> Vec { + LINE.with(|l| std::mem::take(&mut *l.borrow_mut())) + } + + pub(crate) fn task_started() { + RUNNING_TASKS.fetch_add(1, Ordering::SeqCst); + } + + /// At the end of a task on its own thread: writes what is left of its line. + pub(crate) fn task_ended() { + flush(); + RUNNING_TASKS.fetch_sub(1, Ordering::SeqCst); + } + + /// Writes what is left of this thread's line. + pub(crate) fn flush() { + LINE.with(|line| { + let mut line = line.borrow_mut(); + if !line.is_empty() { + let mut out = std::io::stdout().lock(); + let _ = out.write_all(&line); + let _ = out.flush(); + line.clear(); + } + }); + } + + pub(crate) fn print(text: &str) { + // Standard error is not buffered, and a task's line on it is not kept apart. + if TO_STDERR.with(|flag| flag.get()) { + let _ = std::io::stderr().lock().write_all(text.as_bytes()); + return; + } + LINE.with(|line| { + let mut line = line.borrow_mut(); + if RUNNING_TASKS.load(Ordering::SeqCst) == 0 && line.is_empty() { + let mut out = std::io::stdout().lock(); + let _ = out.write_all(text.as_bytes()); + let _ = out.flush(); + return; + } + line.extend_from_slice(text.as_bytes()); + if let Some(end) = line.iter().rposition(|&b| b == b'\n') { + let mut out = std::io::stdout().lock(); + let _ = out.write_all(&line[..=end]); + let _ = out.flush(); + line.drain(..=end); + } + }); + } +} + +#[no_mangle] +pub extern "C" fn print_i32(val: i32) -> i32 { + lines::print(&format!("{}", val)); + 0 +} + +#[no_mangle] +pub extern "C" fn print_i64(val: i64) -> i32 { + lines::print(&format!("{}", val)); + 0 +} + +/// The unsigned counterparts of `print_i32`/`print_i64`. MLIR's integer types are signless, +/// so a Vx `u64` and `i64` reach codegen as the same `i64` and only the element type says +/// which is which; without these every value above the signed range printed as a negative +/// number. One per width, so the element type alone decides the call. +#[no_mangle] +pub extern "C" fn print_u8(val: u8) -> i32 { + lines::print(&format!("{}", val)); +``` + +This file stops in the middle. Continue it from exactly where it stops. Output only the rest of the file.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/edit1.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/edit1.txt new file mode 100644 index 0000000..5874050 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/edit1.txt @@ -0,0 +1,128 @@ +<|im_start|>user +`scripts/tools/differential_fuzz/generators/tensors.py`: + +```python +"""Functions that build tensors in nested blocks and return one, often early. + +`g(n, k)` makes tensors of length `n` in nested `if`s and `for` loops, adds to them, and +returns one, possibly from inside a block. `main` calls it for four values of `k` and prints +every element. The Rust twin uses `Vec`. Aimed at the freeing of heap buffers: an early +return from nested blocks is where #993 and #1014 were. + +Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +See LICENSE for license information. +SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +""" + +import random + +from fuzzlib import Program + +class Gen: + def __init__(self, rng): + self.rng = rng + self.count = 0 + + def fresh(self): + self.count += 1 + return f"v{self.count}" + + def val(self, ints): + r = self.rng.random() + if r < 0.3 or not ints: + return str(self.rng.randint(0, 9)) + a = self.rng.choice(ints) + if r < 0.7: + return f"({a} + {self.rng.choice(ints + ['1', '2'])})" + return a + + def body(self, tensors, ints, depth): + out = [] + for _ in range(self.rng.randint(1, 4)): + k = self.rng.random() + if k < 0.25 or not tensors: + t = self.fresh() + out.append(("new", t)) + tensors = tensors + [t] + elif k < 0.5: + out.append(("fill", self.rng.choice(tensors), self.val(ints))) + elif k < 0.65 and depth < 3: + out.append(("if", self.val(ints), self.body(tensors, ints, depth + 1), + self.body(tensors, ints, depth + 1) if self.rng.random() < 0.5 else None)) + elif k < 0.8 and depth < 3: + iv = f"i{depth}" + out.append(("for", iv, self.rng.randint(0, 3), self.body(tensors, ints + [iv], depth + 1))) + elif k < 0.9 and depth > 0: + out.append(("ret", self.val(ints), self.rng.choice(tensors))) + else: + a, b = self.rng.choice(tensors), self.rng.choice(tensors) + out.append(("add", a, b)) + return out + +def render(stmts, lang, ind): + pad = " " * ind + L = [] + for s in stmts: + if s[0] == "new": + if lang == "vx": + L += [f"{pad}let mut {s[1]} = Tensor([n]);", f"{pad}for j in 0..n {{", f"{pad} {s[1]}[j] = 0;", f"{pad}}}"] + else: + L += [f"{pad}let mut {s[1]}: Vec = vec![0; n as usize];"] + elif s[0] == "fill": + idx = "j" if lang == "vx" else "j as usize" + L += [f"{pad}for j in 0..n {{", f"{pad} {s[1]}[{idx}] = {s[1]}[{idx}] + j + {s[2]};", f"{pad}}}"] + elif s[0] == "add": + idx = "j" if lang == "vx" else "j as usize" + L += [f"{pad}for j in 0..n {{", f"{pad} {s[1]}[{idx}] = {s[1]}[{idx}] + {s[2]}[{idx}];", f"{pad}}}"] + elif s[0] == "if": + L.append(f"{pad}if ({s[1]}) % 2 == 0 {{") + L += render(s[2], lang, ind + 1) + if s[3] is not None: + L.append(f"{pad}}} else {{") + L += render(s[3], lang, ind + 1) + L.append(f"{pad}}}") + elif s[0] == "for": + L.append(f"{pad}for {s[1]} in 0..{s[2]} {{") + L += render(s[3], lang, ind + 1) + L.append(f"{pad}}}") + elif s[0] == "ret": + L.append(f"{pad}if ({s[1]}) % 3 == 0 {{") + L.append(f"{pad} return {s[2]};") + L.append(f"{pad}}}") + return L + + +def generate(seed): + rng = random.Random(seed) + g = Gen(rng) + tree = g.body([], ["k"], 0) + last = rng.choice([s[1] for s in tree if s[0] == "new"] or ["NONE"]) + if last == "NONE": + tree.insert(0, ("new", "v0")) + last = "v0" + returned = next(s for s in tree if s[0] == "new" and s[1] == last) + + def source(stmts, lang): + if lang == "vx": + return "\n".join( + ["fn g(n : i32, k : i32) -> Tensor {"] + render(stmts, "vx", 1) + + [f" return {last};", "}", "", "fn main() -> i32 {", " for k in 0..4 {", + " let r = g(3, k);", " for j in 0..3 {", " print(r[j]);", + " print!(\" \");", " }", " }", " return 0;", "}", ""]) + return "\n".join( + ["#![allow(unused, unused_mut, unused_variables, unreachable_code)]", + "fn g(n: i32, k: i32) -> Vec {"] + render(stmts, "rs", 1) + + [f" return {last};", "}", "fn main() {", " let mut s = String::new();", + " for k in 0..4 { let r = g(3, k); for j in 0..3 { s += &format!(\"{} \", r[j]); } }", + " print!(\"{}\", s);", "}", ""]) + + return Program(tree, source, keep=lambda stmt, block: stmt is returned) +``` + +Add a type hint to every function parameter and return value. Output the whole file, and change nothing else.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/edit2.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/edit2.txt new file mode 100644 index 0000000..e1dfddf --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/edit2.txt @@ -0,0 +1,132 @@ +<|im_start|>user +`src/hir/check/host_waits.rs`: + +```rust +//===- check submodule - Vx Compiler ----------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// A channel end or a lock stays on the host (M6 in +// docs/discussions/waiting_tasks_channels_and_task_errors.md). A GPU does not promise that a +// block of threads makes progress, so a kernel that waits for the host while the host waits for +// the kernel never ends. A `spawn on` body for a device that names one gets E6038. +// +//===----------------------------------------------------------------------===// + +use super::super::*; + +impl TypeChecker<'_> { + /// Whether code on `top` runs on a device, not on the host. A GPU that shares the memory of + /// the host still runs on the device. + pub(crate) fn runs_on_a_device(&self, top: &Topology) -> bool { + match top { + Topology::CPU + | Topology::CpuAvx512 + | Topology::CpuNeon + | Topology::AMX + | Topology::Current => false, + Topology::GPU(_) | Topology::NPU(_) | Topology::AccCore(_) | Topology::ANE => true, + Topology::Slice(inner, ..) => self.runs_on_a_device(inner), + Topology::Custom(..) => { + self.transfer_cost_graph.default_memory_for(top) + != self.transfer_cost_graph.default_memory_for(&Topology::CPU) + } + } + } + + /// E6038 when the device body being checked names `name`, of type `ty`, and `ty` holds a + /// channel end or a lock. True when it reported the error. + pub(crate) fn report_host_only_on_a_device( + &mut self, + name: &str, + ty: &Type, + span: &Span, + ) -> bool { + let Some(spawn) = self.device_spawn else { + return false; + }; + // A generic function that the body calls is checked with the topology of the host. + if self.speculating || !self.runs_on_a_device(&self.active_topology) { + return false; + } + let Some(why) = self.host_only_part(ty, &mut Vec::new()) else { + return false; + }; + self.unreadable_reported.insert(*span); + self.errors.error_with_code( + crate::diagnostic::DiagnosticCode::E6038, + format!( + "the body of the `spawn on` at line {} runs on {}, and it uses '{name}': {why}. A \ + channel end and a lock stay on the host, because a wait on the device for the \ + host can wait forever. Use '{name}' before the `spawn on`, or after it", + spawn.line, + self.active_topology.display_name() + ), + Some(crate::diagnostic::SourceSpan::from_ast_span(span)), + ); + true + } + + /// The chain of fields from `ty` to a channel end or a lock in it, or `None` when it holds + /// none. + fn host_only_part(&mut self, ty: &Type, visiting: &mut Vec) -> Option { + match ty { + Type::Borrow { inner, .. } + | Type::Ref(inner, _) + | Type::Verified(inner) + | Type::Distinct(inner) + | Type::DisjointRanges(inner) + | Type::Pinned(inner, _) => self.host_only_part(inner, visiting), + Type::Struct(..) | Type::Enum(..) | Type::GenericInstance(..) => { + if self.implements_host_only(ty) { + return Some(format!("'{ty}' can wait for the host")); + } + let (name, args) = match ty { + Type::GenericInstance(base, args) => match base.as_ref() { + Type::Struct(n, _) | Type::Enum(n, _) => (n.clone(), args.clone()), + _ => return None, + }, + Type::Struct(n, _) | Type::Enum(n, _) => (n.clone(), Vec::new()), + _ => return None, + }; + if visiting.contains(ty) { + return None; + } + visiting.push(ty.clone()); + let why = self + .held_types(&name, &args) + .into_iter() + .find_map(|(field, held)| { + self.host_only_part(&held, visiting).map(|inner| { + format!("{field} of '{ty}' has type '{held}', and {inner}") + }) + }); + visiting.pop(); + why + } + _ => None, + } + } + + /// Whether the standard library marks `ty` with `impl HostOnly`, as it does for a channel end + /// and a lock. + fn implements_host_only(&mut self, ty: &Type) -> bool { + let blocks = self.env.impls.get("HostOnly").cloned().unwrap_or_default(); + blocks + .iter() + .any(|ib| self.unify_types(&ib.target_type, ty, &mut std::collections::HashMap::new())) + } +} +``` + +Add a `///` doc comment above every function that has none. Output the whole file, and change nothing else.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/edit3.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/edit3.txt new file mode 100644 index 0000000..9ba76fa --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/edit3.txt @@ -0,0 +1,134 @@ +<|im_start|>user +`utils/memalg/measure_link.c`: + +```c +// measure_link.c -- achieved copy bandwidth across a size sweep (the per-seam protocol). +// +// The measurement half of the shakedown. Emits one CSV row per (size, rep-median) so the compare +// step joins it against the compiler's predictions by byte count. +// +// Protocol, mirroring what the M-series will do on rented hardware, so that the *protocol* is what +// gets debugged here rather than on a metered box: +// +// * log-spaced sizes from 4 KiB to 256 MiB, both to catch a latency floor at the small end and +// to get past every cache at the large end; +// * >= 9 reps, median reported with IQR, because a mean over a noisy laptop is not a measurement; +// * a warm-up rep per size, discarded -- the first touch pays page faults, and on a lazily-mapped +// allocation that is a first-touch cost, not a bandwidth; +// * buffers re-touched between reps so the copy is not reading from a cache it just filled; +// * `clock_gettime(CLOCK_MONOTONIC)`, never wall time. +// +// Reports BOTH the copy rate (bytes copied / time) and the traffic rate (2x that, since a memcpy +// reads a byte and writes a byte). Which of the two a declared "memory bandwidth" figure should be +// compared against is exactly the sort of question a dry run is supposed to force into the open -- +// so the harness reports both rather than picking one and hiding the choice. +// +// cc -O2 measure_link.c -o measure_link && ./measure_link > raw.csv +#include +#include +#include +#include + +#ifndef REPS +#define REPS 11 +#endif + +static double now_sec(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (double)ts.tv_sec + (double)ts.tv_nsec * 1e-9; +} + +static int cmp_double(const void *a, const void *b) { + double x = *(const double *)a, y = *(const double *)b; + return (x > y) - (x < y); +} + +int main(void) { + // 4 KiB .. 256 MiB, log-spaced (x2). The small end is where a bandwidth-only model is expected + // to under-predict cost because a latency floor dominates; measuring that crossover IS a result. + size_t sizes[64]; + int n = 0; + for (size_t s = 4096; s <= (256ul << 20); s *= 2) sizes[n++] = s; + + printf("bytes,median_ns,q1_ns,q3_ns,copy_GBps,traffic_GBps,reps\n"); + + for (int i = 0; i < n; ++i) { + size_t bytes = sizes[i]; + char *src = malloc(bytes); + char *dst = malloc(bytes); + if (!src || !dst) { + fprintf(stderr, "alloc failed at %zu bytes\n", bytes); + free(src); free(dst); + continue; + } + // First touch every page so the timed region measures copying, not faulting. + memset(src, 0x5a, bytes); + memset(dst, 0x00, bytes); + + memcpy(dst, src, bytes); // warm-up, discarded + + // How many copies per timed region. `CLOCK_MONOTONIC` on this machine has ~1 us granularity, + // so a single 4 KiB copy times as either 0 or 1000 ns -- which yields an infinite bandwidth + // and, worse, looks like a number. Timing a calibrated batch and dividing is the fix, and + // finding this on the laptop instead of on a rented box is the whole point of the dry run. + // + // The batch is grown until the timed region is >= TARGET_NS, so the clock's granularity is a + // negligible fraction of what is being measured at every size. + const double TARGET_NS = 5e6; // 5 ms + long iters = 1; + for (;;) { + double t0 = now_sec(); + for (long k = 0; k < iters; ++k) memcpy(dst, src, bytes); + double elapsed = (now_sec() - t0) * 1e9; + if (elapsed >= TARGET_NS || iters >= (1L << 30)) break; + // Scale straight to the target rather than doubling, with a floor so a zero reading (the + // very case this loop exists for) still makes progress. + long next = elapsed > 0 ? (long)(iters * TARGET_NS / elapsed) + 1 : iters * 8; + iters = next > iters ? next : iters * 2; + } + + double samples[REPS]; + for (int r = 0; r < REPS; ++r) { + double t0 = now_sec(); + for (long k = 0; k < iters; ++k) memcpy(dst, src, bytes); + double t1 = now_sec(); + samples[r] = (t1 - t0) * 1e9 / (double)iters; // ns per copy + } + // Keep the result observable so the copy cannot be optimised away. + volatile char sink = dst[bytes - 1]; + (void)sink; + + qsort(samples, REPS, sizeof(double), cmp_double); + double med = samples[REPS / 2]; + double q1 = samples[REPS / 4]; + double q3 = samples[(3 * REPS) / 4]; + if (med <= 0.0) { + // Still unmeasurable. Report it as missing rather than as an infinite bandwidth: a row that + // says nothing is recoverable, a row that says `inf` gets averaged into a result. + fprintf(stderr, "%zu bytes: unmeasurable even at %ld iters/rep -- row skipped\n", bytes, + iters); + free(src); + free(dst); + continue; + } + double copy_gbps = (double)bytes / med; // bytes/ns == GB/s + double traffic_gbps = 2.0 * copy_gbps; // a memcpy reads AND writes + + printf("%zu,%.1f,%.1f,%.1f,%.2f,%.2f,%d\n", bytes, med, q1, q3, copy_gbps, traffic_gbps, REPS); + fflush(stdout); + + free(src); + free(dst); + } + return 0; +} +``` + +Add a one-line comment above every function that says what it does. Output the whole file, and change nothing else.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/explain1.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/explain1.txt new file mode 100644 index 0000000..273f2a3 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/explain1.txt @@ -0,0 +1,126 @@ +<|im_start|>user +`src/hir/places.rs`: + +```rust +//===- places.rs - Vx Compiler ---------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +//! Shared "place" helpers — one derivation of *which memory an lvalue names* and *whether two paths +//! overlap*, used by both the borrow checker (conflict detection, `expr.rs`) and the flat lowerer +//! (alias-scope disjointness, `flatten.rs`). +//! +//! These facts used to be computed twice -- the checker's `extract_base_and_path` and its three +//! inline overlap loops, and the lowerer's `place_base_path` / `paths_may_alias`. Both were sound +//! but duplicated; this module is the single source both now call. The borrow checker keeps its +//! `Vec` representation (its `BorrowRecord` stores string paths) by adapting +//! `base_and_path` at the boundary; the overlap predicate is generic over the path element, so +//! `Vec` and `Vec` share it without conversion. +use crate::symbol::Symbol; +use crate::syntax::Expr; + +/// The path element for an index: `[3]` for an integer literal, and [`ANY_INDEX`] for anything +/// else, which may be any element. So `q[0]` and `q[1]` are different places, and `q[i]` may be +/// either of them. +pub fn index_element(index: &Expr) -> String { + match index { + Expr::Range(_) => RANGE_INDEX.to_string(), + Expr::Number(n) => match n.value.parse::() { + Ok(k) => format!("[{k}]"), + Err(_) => ANY_INDEX.to_string(), + }, + _ => ANY_INDEX.to_string(), + } +} + +/// The path element of an index whose value is not known: it may name any element. +pub const ANY_INDEX: &str = "[?]"; + +/// The path element of a range index, `q[1..3]`: some rows of `q`. The result keeps its first +/// dimension, so an index after it, `q[1..3][1]`, picks a row of `q` again, not a column. +pub const RANGE_INDEX: &str = "[..]"; + +/// Add `elem` to the end of `path`. An index after a range is a row of the same dimension, so +/// it joins the range into [`ANY_INDEX`], and a range after a range stays a range. +pub fn push_path_element + From>(path: &mut Vec, elem: String) { + if let Some(last) = path.last_mut() { + if last.as_ref() == RANGE_INDEX && elem.starts_with('[') { + if elem != RANGE_INDEX { + *last = T::from(ANY_INDEX.to_string()); + } + return; + } + } + path.push(T::from(elem)); +} + +/// The root local and projection path of an lvalue: `o.x.y` -> `(o, [x, y])`, `q[0].x` -> +/// `(q, [[0], x])`, a bare local -> `(o, [])`. An index is a path element, written by +/// [`index_element`]. `None` for a base with no nameable root (`&5`, a call result). +pub fn base_and_path(e: &Expr) -> Option<(Symbol, Vec)> { + match e { + Expr::Identifier(id) => Some((id.name.clone(), Vec::new())), + Expr::MemberAccess(m) => { + let (root, mut path) = base_and_path(&m.base)?; + path.push(m.member.clone()); + Some((root, path)) + } + Expr::IndexAccess(ix) => { + let (root, mut path) = base_and_path(&ix.base)?; + push_path_element(&mut path, index_element(&ix.index)); + Some((root, path)) + } + _ => None, + } +} + +/// Whether two projection paths under the **same** root may name overlapping memory: true when +/// one is a prefix of the other (`[inner]` vs `[inner, v]`) or they match at every shared level. +/// Distinct fields (`[x]` vs `[y]`) and distinct constant indices (`[[0]]` vs `[[1]]`) are +/// disjoint; [`ANY_INDEX`] matches any element. Generic over the path element so the checker's +/// `[String]` and the lowerer's [`Symbol`] paths share it. Returning `true` for paths that are in +/// fact disjoint is always the safe direction: it withholds a `noalias` or reports a conflict. +pub fn paths_may_alias>(a: &[T], b: &[T]) -> bool { + a.iter().zip(b).all(|(x, y)| { + let (x, y) = (x.as_ref(), y.as_ref()); + x == y || [ANY_INDEX, RANGE_INDEX].contains(&x) || [ANY_INDEX, RANGE_INDEX].contains(&y) + }) +} + +/// How a place reads in a message: `q[0].x`, with a dot before each field and none before an +/// index. A tuple's fields, which the parser names `_0`, `_1`, .., read as the program writes +/// them: `t.0`. +pub fn display_place>(root: &str, path: &[T]) -> String { + let mut out = root.to_string(); + for p in path { + let p = p.as_ref(); + if !p.starts_with('[') { + out.push('.'); + } + match p.strip_prefix('_') { + Some(n) if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => out.push_str(n), + _ => out.push_str(p), + } + } + out +} + +/// A moved place as the checker records it, `p.a` or `t._0`, as it reads in a message. +pub fn display_dotted(place: &str) -> String { + let mut parts = place.split('.'); + let root = parts.next().unwrap_or_default(); + let path: Vec<&str> = parts.collect(); + display_place(root, &path) +} +``` + +Explain what this code does, function by function.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/explain2.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/explain2.txt new file mode 100644 index 0000000..4118f9c --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/explain2.txt @@ -0,0 +1,129 @@ +<|im_start|>user +`src/hir/check/drop_waits.rs`: + +```rust +//===- check submodule - Vx Compiler ----------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// A `drop` runs with cancellation off, so a cancel cannot stop a wait in it. A `send` or `recv` +// there waits until the time limit of the `drop` when the other end never acts. W1036 warns +// about such a call, and the fix is `send_for` or `recv_for`, or a call of `within` (F6 and F6a +// in docs/discussions/waiting_tasks_channels_and_task_errors.md). A wait in a closure literal +// written as the body of `within` has the limit of the call, so it gets no warning. A closure in +// a variable gets the warning, because the check cannot see that the variable goes to `within`. `wait_limit` runs before cancellation is off, +// and it should return a time and not wait, so W1036 warns about a wait in it too. +// It is a warning, not an error, because the check does not look into the functions that the +// `drop` calls. +// +//===----------------------------------------------------------------------===// + +use super::super::*; + +impl TypeChecker<'_> { + /// Whether `func` is the `drop` of a `Drop` impl: the `drop` that its receiver type uses. + pub(crate) fn is_drop_impl(&mut self, func: &Function) -> bool { + if !func.name.ends_with("drop") && !func.name.contains("$drop$") { + return false; + } + self.is_drop_impl_method(func, "drop") + } + + /// Whether `func` is the `wait_limit` of a `Drop` impl. + pub(crate) fn is_wait_limit_impl(&mut self, func: &Function) -> bool { + if !func.name.contains("wait_limit") { + return false; + } + self.is_drop_impl_method(func, "wait_limit") + } + + /// Whether `func` is the method `method` of the `Drop` impl of its receiver type. + fn is_drop_impl_method(&mut self, func: &Function, method: &str) -> bool { + let Some((_, receiver)) = func.params.first() else { + return false; + }; + let ty = match receiver { + Type::Borrow { inner, .. } | Type::Ref(inner, _) => inner.as_ref().clone(), + ty => ty.clone(), + }; + self.drops_impl_method(&ty, method) + .is_some_and(|name| name.as_ref() == func.name.as_ref()) + } + + /// W1036 when the `drop` of a `Drop` impl calls `method` on a value of type `base`, and the + /// call is a channel wait with no time limit. + pub(crate) fn warn_wait_in_drop(&mut self, base: &Type, method: &str, span: &Span) { + if !(self.in_drop || self.in_wait_limit) || self.within_depth > 0 || self.speculating { + return; + } + let timed = match method { + "send" => "send_for", + "recv" => "recv_for", + _ => return, + }; + let base = match base { + Type::Borrow { inner, .. } | Type::Ref(inner, _) => inner.as_ref(), + ty => ty, + }; + let name = match base { + Type::Struct(n, _) => n.clone(), + Type::GenericInstance(b, _) => match b.as_ref() { + Type::Struct(n, _) => n.clone(), + _ => return, + }, + _ => return, + }; + // The ends whose `send` or `recv` can wait. The `send` of a oneshot and of a watch + // channel does not wait. + let waits = match (method, name.split('<').next()) { + ("send", Some(end)) => matches!(end, "Sender" | "BroadcastSender"), + (_, Some(end)) => matches!( + end, + "Receiver" + | "OneshotReceiver" + | "BroadcastReceiver" + | "WatchReceiver" + | "WorkReceiver" + ), + _ => false, + }; + if !waits { + return; + } + if self.in_wait_limit { + self.errors.warn( + crate::diagnostic::DiagnosticCode::W1036, + format!( + "'{method}' waits in 'wait_limit'. 'wait_limit' runs before the drop, to say \ + how long its waits can take, so it should return a time and not wait" + ), + Some(crate::diagnostic::SourceSpan::from_ast_span(span)), + ); + return; + } + self.errors.warn( + crate::diagnostic::DiagnosticCode::W1036, + format!( + "'{method}' waits with no time limit of its own in a 'drop'. A drop runs with \ + cancellation off, so if the other end of the channel never acts, this wait \ + holds up the drop until the limit of the drop: its type's 'wait_limit', 10 \ + seconds by default. Use '{timed}' with a time limit, or put the wait in the \ + body of 'within'" + ), + Some(crate::diagnostic::SourceSpan::from_ast_span(span)), + ); + } +} +``` + +Explain what this code does, function by function.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/explain3.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/explain3.txt new file mode 100644 index 0000000..70bcbd5 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/explain3.txt @@ -0,0 +1,134 @@ +<|im_start|>user +`src/hir/decl_check/bounds.rs`: + +```rust +//===- decl_check submodule - Vx Compiler -----------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// A bound on a type parameter has to name a trait that exists. +// +//===----------------------------------------------------------------------===// + +use super::super::*; + +impl TypeChecker<'_> { + /// Refuse a bound such as `T : NoSuchTrait` whose trait is not declared (E3042). + /// + /// A bound is otherwise only asked when a call binds the parameter, so a misspelled one + /// on a function nobody calls, or on a struct, was never reported. + pub fn check_bounds_name_a_trait(&mut self) { + // (where the bound is written, the parameter, the trait it names, the place of the owner) + let mut unknown: Vec<(String, String, String, decl::DeclPlace)> = Vec::new(); + let traits = &self.env.traits; + let mut collect = + |owner: &str, generics: &[decl::GenericParam], place: &decl::DeclPlace| { + for param in generics { + if let decl::GenericParam::Type { name, bounds } = param { + for bound in bounds { + // `D : Topology` and `M : Memory` mark a topology and a memory + // parameter. They are keywords, not traits. + if matches!(bound.trait_name.as_ref(), "Topology" | "Memory") { + continue; + } + if !traits.contains_key(&bound.trait_name) { + unknown.push(( + owner.to_string(), + name.to_string(), + bound.trait_name.to_string(), + place.clone(), + )); + } + } + } + } + }; + + for s in self.env.structs.values() { + collect(&format!("struct {}", s.name), &s.generics, &s.place); + } + for e in self.env.enums.values() { + collect(&format!("enum {}", e.name), &e.generics, &e.place); + } + for t in self.env.traits.values() { + collect(&format!("trait {}", t.name), &t.generics, &t.place); + // A method signature has no place of its own, so its trait's is used. + for m in &t.methods { + collect( + &format!("method {}::{}", t.name, m.name), + &m.generics, + &t.place, + ); + } + } + for block in self.env.impls.values().flatten() { + let owner = match &block.trait_name { + Some(t) => format!("impl {} for {}", t, block.target_type), + None => format!("impl {}", block.target_type), + }; + collect(&owner, &block.generics, &block.place); + let impl_params: Vec<&str> = block.generics.iter().map(|g| g.name()).collect(); + // A trait default copied into the impl is reported on the trait. + for m in block + .methods + .iter() + .filter(|m| !block.copied_defaults.contains(&m.name)) + { + // A method is also given its impl's parameters, already reported above. + let own: Vec = m + .generics + .iter() + .filter(|g| !impl_params.contains(&g.name())) + .cloned() + .collect(); + collect( + &format!("method {}::{}", block.target_type, m.name), + &own, + &function_place(m), + ); + } + } + for (f, _) in self.env.generic_functions.values() { + collect(&format!("fn {}", f.name), &f.generics, &function_place(f)); + } + + // The tables are hash maps, and a generic method can be listed under its impl and as a + // function, so sort for a stable order and drop the repeats. + unknown.sort_by(|a, b| (&a.0, &a.1, &a.2).cmp(&(&b.0, &b.1, &b.2))); + unknown.dedup_by(|a, b| (&a.0, &a.1, &a.2) == (&b.0, &b.1, &b.2)); + let outside = self.errors.here(); + for (owner, param, trait_name, place) in unknown { + self.errors.point_at(&place, &outside); + self.errors.error_with_code( + crate::diagnostic::DiagnosticCode::E3042, + format!( + "the bound `{param} : {trait_name}` on `{owner}` names no trait; \ + no trait called '{trait_name}' is declared or imported" + ), + None, + ); + } + self.errors.point_back(outside); + } +} + +/// Where a function is written, as a declaration's place. +fn function_place(f: &decl::Function) -> decl::DeclPlace { + decl::DeclPlace { + file: f.file.clone(), + span: f.span, + } +} +``` + +Explain what this code does, function by function.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/write1.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/write1.txt new file mode 100644 index 0000000..9e393b6 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/write1.txt @@ -0,0 +1,8 @@ +<|im_start|>user +Write a Python function merge_intervals(intervals) that merges overlapping closed intervals and returns them sorted. Add pytest tests for it, with empty input and touching intervals.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/write2.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/write2.txt new file mode 100644 index 0000000..11f00b9 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/write2.txt @@ -0,0 +1,8 @@ +<|im_start|>user +Write a C function `void reverse_words(char *s)` that reverses the order of the words in a string in place, with single spaces between words. Add a main() that tests it.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/write3.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/write3.txt new file mode 100644 index 0000000..2bd5648 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/llama/write3.txt @@ -0,0 +1,8 @@ +<|im_start|>user +Write a Rust struct Trie with new, insert, contains and starts_with for lowercase ASCII words. Add unit tests.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/complete1.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/complete1.txt new file mode 100644 index 0000000..9e8250e --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/complete1.txt @@ -0,0 +1,101 @@ +<|im_start|>user +`src/hir/flatten/affine.rs`: + +```rust +//===- affine.rs - Vx Compiler --------------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Counted loops that the code generator writes as `affine.for`, so that the affine passes can +// fuse and tile them. docs/discussions/loop_optimizations_in_the_frontend_and_in_mlir.md has the +// rules. +// +//===----------------------------------------------------------------------===// + +use super::*; +use crate::bytecode::AFFINE_FOR_BRANCHES; + +/// Whether the body of a loop can be the body of an `affine.for`: nothing in it leaves the loop, +/// and it holds no region that the MLIR passes lower by splitting its block. +pub(super) fn affine_body(body: &[Statement]) -> bool { + stays_in(body, false) +} + +/// Whether nothing in `stmts` leaves the loop. In a nested loop, `in_loop` is set, and a +/// `break` or `continue` stays in that loop. +fn stays_in(stmts: &[Statement], in_loop: bool) -> bool { + stmts.iter().all(|s| match s { + Statement::Return(_) => false, + Statement::Break(_) | Statement::Continue(_) => in_loop, + Statement::ForLoop(f) => { + exprs_stay_in(std::slice::from_ref(s), in_loop) && stays_in(&f.body, true) + } + Statement::Loop(l) => { + exprs_stay_in(std::slice::from_ref(s), in_loop) && stays_in(&l.body, true) + } + // An unexpanded macro may hold anything. + Statement::MacroCall(_) | Statement::Error(_) => false, + _ => exprs_stay_in(std::slice::from_ref(s), in_loop), + }) +} + +/// Whether the expressions of `stmts`, and the blocks in them, stay in the loop. +fn exprs_stay_in(stmts: &[Statement], in_loop: bool) -> bool { + let mut ok = true; + let mut check = |e: &Expr| { + ok &= match e { + Expr::If(i) => { + stays_in(&i.then_block, in_loop) + && i.else_block.as_ref().is_none_or(|b| stays_in(b, in_loop)) + } + Expr::Match(m) => m.arms.iter().all(|a| stays_in(&a.body, in_loop)), + // The checker makes a `tasks` block and a task body an `UnsafeBlock` with a `task` + // mark, and the lowering of a task splits its block. + Expr::UnsafeBlock(b) => b.task.is_none() && stays_in(&b.stmts, in_loop), + Expr::ComptimeBlock(b) => stays_in(&b.stmts, in_loop), + Expr::SpawnOn(_) + | Expr::TaskBlock(_) + | Expr::InlineMlir(_) + | Expr::Closure(_) + | Expr::MacroCall(_) => false, + _ => true, + } + }; + for s in stmts { + // A nested loop's body is checked by `stays_in`. Only its own expressions are here. + match s { + Statement::ForLoop(f) => { + crate::syntax::visit_expr(&f.iterable, &mut check); + f.invariants + .iter() + .for_each(|e| crate::syntax::visit_expr(e, &mut check)); + } + Statement::Loop(l) => l + .invariants + .iter() + .for_each(|e| crate::syntax::visit_expr(e, &mut check)), + _ => crate::syntax::visit_exprs(std::slice::from_ref(s), &mut check), + } + } + ok +} + +impl Lowerer<'_> { + /// Whether `v` can be a bound of an `affine.for` here: a constant, a value from before the + /// outermost open affine loop, or the variable of an open affine loop. + fn affine_bound(&self, v: &Val) -> bool { + let r = v.reg.0 as usize; + match self.affine_open.first() { + None => true, +``` + +This file stops in the middle. Continue it from exactly where it stops. Output only the rest of the file.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/complete2.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/complete2.txt new file mode 100644 index 0000000..d8f89e1 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/complete2.txt @@ -0,0 +1,111 @@ +<|im_start|>user +`utils/memalg/shakedown.py`: + +```python +#!/usr/bin/env python3 +"""Predict -> measure -> compare, end to end. + +The dry run. Its output is an error table for one memory link on the machine we already +own, and its purpose is to find bugs in OUR harness -- a wrong formula, a mislabeled column, a +unit mismatch -- before any GPU time is paid for. The MLSys admission matrix was dry-run the same +way and it caught an 8x arithmetic error before any money was spent. + +Three steps, each of which can fail loudly: + + predict generate a Vx program that transfers a tile of each swept size, compile it against the + machine file, and harvest `--diagnostics-json` -> predicted picoseconds per hop. + measure run the C benchmark -> achieved copy time per size. + compare join on byte count, report signed relative error. + +The join is on `bytes`, which is why the extractor had to emit it: without a byte +count in the prediction record there is nothing to join on and the two halves cannot be related at +all. +""" + +import argparse +import csv +import json +import os +import subprocess +import sys +import tempfile + +# The tile shapes swept. Square f32 tiles, so bytes = 4*d*d; chosen so the byte counts line up +# with the measurement's powers of two. +DIMS = [32, 64, 128, 256, 512, 1024, 2048, 4096] + + +def tile_bytes(d): + return 4 * d * d + + +def predict(vxc, machine, workdir): + """Compile one probe program per size and harvest its predicted hop costs. + + One program per size rather than one program with every size: the resident-set check would + reject a program holding every tile at once, and a rejected compile emits no routes. + """ + out = {} + for d in DIMS: + src = os.path.join(workdir, f"probe_{d}.vx") + with open(src, "w") as f: + f.write( + "fn main() -> i32 {\n" + f" let tile : Tensor = Tensor([{d}, {d}]);\n" + " let _h = transfer(tile, Memory::HBM);\n" + " return 0;\n" + "}\n" + ) + js = os.path.join(workdir, f"probe_{d}.json") + proc = subprocess.run( + [vxc, "--machine", machine, src, "--diagnostics-json", js, "--emit-mlir"], + capture_output=True, + text=True, + ) + if not os.path.exists(js): + print(f" !! no diagnostics for {d}x{d}: {proc.stderr.strip()[:200]}", file=sys.stderr) + continue + rec = json.load(open(js)) + for r in rec.get("routes", []): + if r["path"] == ["CPU_DRAM", "HBM"] and r.get("derived_cost") is not None: + if r.get("derived_unit") != "ps": + # A cycle-denominated cost cannot be compared against a wall-clock measurement + # without a declared clock. Refusing beats silently treating cycles as ps. + print( + f" !! {d}x{d}: predicted unit is {r['derived_unit']}, not ps -- " + "cannot compare against wall-clock without a clock figure", + file=sys.stderr, + ) + continue + out[r["bytes"]] = r["derived_cost"] + return out + + +def measure(binary): + proc = subprocess.run([binary], capture_output=True, text=True, check=True) + rows = {} + for row in csv.DictReader(proc.stdout.splitlines()): + rows[int(row["bytes"])] = { + "ns": float(row["median_ns"]), + "q1": float(row["q1_ns"]), + "q3": float(row["q3_ns"]), + "copy_gbps": float(row["copy_GBps"]), + "traffic_gbps": float(row["traffic_GBps"]), + } + return rows + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--vxc", default="target/release/vxc") + ap.add_argument("--machine", default="fleet/m4-uma.vx") + ap.add_argument("--bench", default="utils/memalg/measure_link") + ap.add_argument("--out", default=None, help="write the error table here as CSV") +``` + +This file stops in the middle. Continue it from exactly where it stops. Output only the rest of the file.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/complete3.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/complete3.txt new file mode 100644 index 0000000..8dac3a8 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/complete3.txt @@ -0,0 +1,133 @@ +<|im_start|>user +`stdlib/rust_core/src/io.rs`: + +```rust +//===- io.rs - Vx Compiler -------------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file implements the standard library I/O primitives. +// It contains the Rust-side FFI implementations for file system operations, +// console printing, and basic input/output functionality exposed to Vx programs. +// +//===----------------------------------------------------------------------===// +//! FFI bindings for `std::fs::File`. + +use crate::{instantiate_file_ffi, instantiate_stdio_ffi}; + +instantiate_file_ffi!(crate::ffi::io::off_the_worker); +instantiate_stdio_ffi!(); + +/// While a task runs, each thread keeps what it prints until a newline, and then writes the +/// whole line at once. So the lines of tasks that print at the same time do not mix. With no +/// task running, each piece is written at once, as before, so its order with output from C is +/// the order of the calls. +pub(crate) mod lines { + use std::cell::RefCell; + use std::io::Write; + use std::sync::atomic::{AtomicUsize, Ordering}; + + static RUNNING_TASKS: AtomicUsize = AtomicUsize::new(0); + + thread_local! { + static LINE: RefCell> = const { RefCell::new(Vec::new()) }; + /// Set between the two `vx_print_to_stderr` calls around an `eprint!` or a `panic`. + static TO_STDERR: std::cell::Cell = const { std::cell::Cell::new(false) }; + } + + pub(crate) fn set_stderr(on: bool) { + TO_STDERR.with(|flag| flag.set(on)); + } + + /// Swaps the line and the stderr flag of this thread with these. The shared runtime gives + /// each fiber its own, so that the lines of two fibers on one thread do not mix. + pub(crate) fn swap_with_thread(line: &mut Vec, to_stderr: &mut bool) { + LINE.with(|l| std::mem::swap(&mut *l.borrow_mut(), line)); + TO_STDERR.with(|flag| *to_stderr = flag.replace(*to_stderr)); + } + + /// Takes what this thread keeps of its line. + #[cfg(test)] + pub(crate) fn take_line() -> Vec { + LINE.with(|l| std::mem::take(&mut *l.borrow_mut())) + } + + pub(crate) fn task_started() { + RUNNING_TASKS.fetch_add(1, Ordering::SeqCst); + } + + /// At the end of a task on its own thread: writes what is left of its line. + pub(crate) fn task_ended() { + flush(); + RUNNING_TASKS.fetch_sub(1, Ordering::SeqCst); + } + + /// Writes what is left of this thread's line. + pub(crate) fn flush() { + LINE.with(|line| { + let mut line = line.borrow_mut(); + if !line.is_empty() { + let mut out = std::io::stdout().lock(); + let _ = out.write_all(&line); + let _ = out.flush(); + line.clear(); + } + }); + } + + pub(crate) fn print(text: &str) { + // Standard error is not buffered, and a task's line on it is not kept apart. + if TO_STDERR.with(|flag| flag.get()) { + let _ = std::io::stderr().lock().write_all(text.as_bytes()); + return; + } + LINE.with(|line| { + let mut line = line.borrow_mut(); + if RUNNING_TASKS.load(Ordering::SeqCst) == 0 && line.is_empty() { + let mut out = std::io::stdout().lock(); + let _ = out.write_all(text.as_bytes()); + let _ = out.flush(); + return; + } + line.extend_from_slice(text.as_bytes()); + if let Some(end) = line.iter().rposition(|&b| b == b'\n') { + let mut out = std::io::stdout().lock(); + let _ = out.write_all(&line[..=end]); + let _ = out.flush(); + line.drain(..=end); + } + }); + } +} + +#[no_mangle] +pub extern "C" fn print_i32(val: i32) -> i32 { + lines::print(&format!("{}", val)); + 0 +} + +#[no_mangle] +pub extern "C" fn print_i64(val: i64) -> i32 { + lines::print(&format!("{}", val)); + 0 +} + +/// The unsigned counterparts of `print_i32`/`print_i64`. MLIR's integer types are signless, +/// so a Vx `u64` and `i64` reach codegen as the same `i64` and only the element type says +/// which is which; without these every value above the signed range printed as a negative +/// number. One per width, so the element type alone decides the call. +#[no_mangle] +pub extern "C" fn print_u8(val: u8) -> i32 { + lines::print(&format!("{}", val)); +``` + +This file stops in the middle. Continue it from exactly where it stops. Output only the rest of the file.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/edit1.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/edit1.txt new file mode 100644 index 0000000..0ac411a --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/edit1.txt @@ -0,0 +1,127 @@ +<|im_start|>user +`scripts/tools/differential_fuzz/generators/tensors.py`: + +```python +"""Functions that build tensors in nested blocks and return one, often early. + +`g(n, k)` makes tensors of length `n` in nested `if`s and `for` loops, adds to them, and +returns one, possibly from inside a block. `main` calls it for four values of `k` and prints +every element. The Rust twin uses `Vec`. Aimed at the freeing of heap buffers: an early +return from nested blocks is where #993 and #1014 were. + +Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +See LICENSE for license information. +SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +""" + +import random + +from fuzzlib import Program + +class Gen: + def __init__(self, rng): + self.rng = rng + self.count = 0 + + def fresh(self): + self.count += 1 + return f"v{self.count}" + + def val(self, ints): + r = self.rng.random() + if r < 0.3 or not ints: + return str(self.rng.randint(0, 9)) + a = self.rng.choice(ints) + if r < 0.7: + return f"({a} + {self.rng.choice(ints + ['1', '2'])})" + return a + + def body(self, tensors, ints, depth): + out = [] + for _ in range(self.rng.randint(1, 4)): + k = self.rng.random() + if k < 0.25 or not tensors: + t = self.fresh() + out.append(("new", t)) + tensors = tensors + [t] + elif k < 0.5: + out.append(("fill", self.rng.choice(tensors), self.val(ints))) + elif k < 0.65 and depth < 3: + out.append(("if", self.val(ints), self.body(tensors, ints, depth + 1), + self.body(tensors, ints, depth + 1) if self.rng.random() < 0.5 else None)) + elif k < 0.8 and depth < 3: + iv = f"i{depth}" + out.append(("for", iv, self.rng.randint(0, 3), self.body(tensors, ints + [iv], depth + 1))) + elif k < 0.9 and depth > 0: + out.append(("ret", self.val(ints), self.rng.choice(tensors))) + else: + a, b = self.rng.choice(tensors), self.rng.choice(tensors) + out.append(("add", a, b)) + return out + +def render(stmts, lang, ind): + pad = " " * ind + L = [] + for s in stmts: + if s[0] == "new": + if lang == "vx": + L += [f"{pad}let mut {s[1]} = Tensor([n]);", f"{pad}for j in 0..n {{", f"{pad} {s[1]}[j] = 0;", f"{pad}}}"] + else: + L += [f"{pad}let mut {s[1]}: Vec = vec![0; n as usize];"] + elif s[0] == "fill": + idx = "j" if lang == "vx" else "j as usize" + L += [f"{pad}for j in 0..n {{", f"{pad} {s[1]}[{idx}] = {s[1]}[{idx}] + j + {s[2]};", f"{pad}}}"] + elif s[0] == "add": + idx = "j" if lang == "vx" else "j as usize" + L += [f"{pad}for j in 0..n {{", f"{pad} {s[1]}[{idx}] = {s[1]}[{idx}] + {s[2]}[{idx}];", f"{pad}}}"] + elif s[0] == "if": + L.append(f"{pad}if ({s[1]}) % 2 == 0 {{") + L += render(s[2], lang, ind + 1) + if s[3] is not None: + L.append(f"{pad}}} else {{") + L += render(s[3], lang, ind + 1) + L.append(f"{pad}}}") + elif s[0] == "for": + L.append(f"{pad}for {s[1]} in 0..{s[2]} {{") + L += render(s[3], lang, ind + 1) + L.append(f"{pad}}}") + elif s[0] == "ret": + L.append(f"{pad}if ({s[1]}) % 3 == 0 {{") + L.append(f"{pad} return {s[2]};") + L.append(f"{pad}}}") + return L + + +def generate(seed): + rng = random.Random(seed) + g = Gen(rng) + tree = g.body([], ["k"], 0) + last = rng.choice([s[1] for s in tree if s[0] == "new"] or ["NONE"]) + if last == "NONE": + tree.insert(0, ("new", "v0")) + last = "v0" + returned = next(s for s in tree if s[0] == "new" and s[1] == last) + + def source(stmts, lang): + if lang == "vx": + return "\n".join( + ["fn g(n : i32, k : i32) -> Tensor {"] + render(stmts, "vx", 1) + + [f" return {last};", "}", "", "fn main() -> i32 {", " for k in 0..4 {", + " let r = g(3, k);", " for j in 0..3 {", " print(r[j]);", + " print!(\" \");", " }", " }", " return 0;", "}", ""]) + return "\n".join( + ["#![allow(unused, unused_mut, unused_variables, unreachable_code)]", + "fn g(n: i32, k: i32) -> Vec {"] + render(stmts, "rs", 1) + + [f" return {last};", "}", "fn main() {", " let mut s = String::new();", + " for k in 0..4 { let r = g(3, k); for j in 0..3 { s += &format!(\"{} \", r[j]); } }", + " print!(\"{}\", s);", "}", ""]) + + return Program(tree, source, keep=lambda stmt, block: stmt is returned) +``` + +Add a type hint to every function parameter and return value. Output the whole file, and change nothing else.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/edit2.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/edit2.txt new file mode 100644 index 0000000..022308f --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/edit2.txt @@ -0,0 +1,131 @@ +<|im_start|>user +`src/hir/check/host_waits.rs`: + +```rust +//===- check submodule - Vx Compiler ----------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// A channel end or a lock stays on the host (M6 in +// docs/discussions/waiting_tasks_channels_and_task_errors.md). A GPU does not promise that a +// block of threads makes progress, so a kernel that waits for the host while the host waits for +// the kernel never ends. A `spawn on` body for a device that names one gets E6038. +// +//===----------------------------------------------------------------------===// + +use super::super::*; + +impl TypeChecker<'_> { + /// Whether code on `top` runs on a device, not on the host. A GPU that shares the memory of + /// the host still runs on the device. + pub(crate) fn runs_on_a_device(&self, top: &Topology) -> bool { + match top { + Topology::CPU + | Topology::CpuAvx512 + | Topology::CpuNeon + | Topology::AMX + | Topology::Current => false, + Topology::GPU(_) | Topology::NPU(_) | Topology::AccCore(_) | Topology::ANE => true, + Topology::Slice(inner, ..) => self.runs_on_a_device(inner), + Topology::Custom(..) => { + self.transfer_cost_graph.default_memory_for(top) + != self.transfer_cost_graph.default_memory_for(&Topology::CPU) + } + } + } + + /// E6038 when the device body being checked names `name`, of type `ty`, and `ty` holds a + /// channel end or a lock. True when it reported the error. + pub(crate) fn report_host_only_on_a_device( + &mut self, + name: &str, + ty: &Type, + span: &Span, + ) -> bool { + let Some(spawn) = self.device_spawn else { + return false; + }; + // A generic function that the body calls is checked with the topology of the host. + if self.speculating || !self.runs_on_a_device(&self.active_topology) { + return false; + } + let Some(why) = self.host_only_part(ty, &mut Vec::new()) else { + return false; + }; + self.unreadable_reported.insert(*span); + self.errors.error_with_code( + crate::diagnostic::DiagnosticCode::E6038, + format!( + "the body of the `spawn on` at line {} runs on {}, and it uses '{name}': {why}. A \ + channel end and a lock stay on the host, because a wait on the device for the \ + host can wait forever. Use '{name}' before the `spawn on`, or after it", + spawn.line, + self.active_topology.display_name() + ), + Some(crate::diagnostic::SourceSpan::from_ast_span(span)), + ); + true + } + + /// The chain of fields from `ty` to a channel end or a lock in it, or `None` when it holds + /// none. + fn host_only_part(&mut self, ty: &Type, visiting: &mut Vec) -> Option { + match ty { + Type::Borrow { inner, .. } + | Type::Ref(inner, _) + | Type::Verified(inner) + | Type::Distinct(inner) + | Type::DisjointRanges(inner) + | Type::Pinned(inner, _) => self.host_only_part(inner, visiting), + Type::Struct(..) | Type::Enum(..) | Type::GenericInstance(..) => { + if self.implements_host_only(ty) { + return Some(format!("'{ty}' can wait for the host")); + } + let (name, args) = match ty { + Type::GenericInstance(base, args) => match base.as_ref() { + Type::Struct(n, _) | Type::Enum(n, _) => (n.clone(), args.clone()), + _ => return None, + }, + Type::Struct(n, _) | Type::Enum(n, _) => (n.clone(), Vec::new()), + _ => return None, + }; + if visiting.contains(ty) { + return None; + } + visiting.push(ty.clone()); + let why = self + .held_types(&name, &args) + .into_iter() + .find_map(|(field, held)| { + self.host_only_part(&held, visiting).map(|inner| { + format!("{field} of '{ty}' has type '{held}', and {inner}") + }) + }); + visiting.pop(); + why + } + _ => None, + } + } + + /// Whether the standard library marks `ty` with `impl HostOnly`, as it does for a channel end + /// and a lock. + fn implements_host_only(&mut self, ty: &Type) -> bool { + let blocks = self.env.impls.get("HostOnly").cloned().unwrap_or_default(); + blocks + .iter() + .any(|ib| self.unify_types(&ib.target_type, ty, &mut std::collections::HashMap::new())) + } +} +``` + +Add a `///` doc comment above every function that has none. Output the whole file, and change nothing else.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/edit3.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/edit3.txt new file mode 100644 index 0000000..032730c --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/edit3.txt @@ -0,0 +1,133 @@ +<|im_start|>user +`utils/memalg/measure_link.c`: + +```c +// measure_link.c -- achieved copy bandwidth across a size sweep (the per-seam protocol). +// +// The measurement half of the shakedown. Emits one CSV row per (size, rep-median) so the compare +// step joins it against the compiler's predictions by byte count. +// +// Protocol, mirroring what the M-series will do on rented hardware, so that the *protocol* is what +// gets debugged here rather than on a metered box: +// +// * log-spaced sizes from 4 KiB to 256 MiB, both to catch a latency floor at the small end and +// to get past every cache at the large end; +// * >= 9 reps, median reported with IQR, because a mean over a noisy laptop is not a measurement; +// * a warm-up rep per size, discarded -- the first touch pays page faults, and on a lazily-mapped +// allocation that is a first-touch cost, not a bandwidth; +// * buffers re-touched between reps so the copy is not reading from a cache it just filled; +// * `clock_gettime(CLOCK_MONOTONIC)`, never wall time. +// +// Reports BOTH the copy rate (bytes copied / time) and the traffic rate (2x that, since a memcpy +// reads a byte and writes a byte). Which of the two a declared "memory bandwidth" figure should be +// compared against is exactly the sort of question a dry run is supposed to force into the open -- +// so the harness reports both rather than picking one and hiding the choice. +// +// cc -O2 measure_link.c -o measure_link && ./measure_link > raw.csv +#include +#include +#include +#include + +#ifndef REPS +#define REPS 11 +#endif + +static double now_sec(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (double)ts.tv_sec + (double)ts.tv_nsec * 1e-9; +} + +static int cmp_double(const void *a, const void *b) { + double x = *(const double *)a, y = *(const double *)b; + return (x > y) - (x < y); +} + +int main(void) { + // 4 KiB .. 256 MiB, log-spaced (x2). The small end is where a bandwidth-only model is expected + // to under-predict cost because a latency floor dominates; measuring that crossover IS a result. + size_t sizes[64]; + int n = 0; + for (size_t s = 4096; s <= (256ul << 20); s *= 2) sizes[n++] = s; + + printf("bytes,median_ns,q1_ns,q3_ns,copy_GBps,traffic_GBps,reps\n"); + + for (int i = 0; i < n; ++i) { + size_t bytes = sizes[i]; + char *src = malloc(bytes); + char *dst = malloc(bytes); + if (!src || !dst) { + fprintf(stderr, "alloc failed at %zu bytes\n", bytes); + free(src); free(dst); + continue; + } + // First touch every page so the timed region measures copying, not faulting. + memset(src, 0x5a, bytes); + memset(dst, 0x00, bytes); + + memcpy(dst, src, bytes); // warm-up, discarded + + // How many copies per timed region. `CLOCK_MONOTONIC` on this machine has ~1 us granularity, + // so a single 4 KiB copy times as either 0 or 1000 ns -- which yields an infinite bandwidth + // and, worse, looks like a number. Timing a calibrated batch and dividing is the fix, and + // finding this on the laptop instead of on a rented box is the whole point of the dry run. + // + // The batch is grown until the timed region is >= TARGET_NS, so the clock's granularity is a + // negligible fraction of what is being measured at every size. + const double TARGET_NS = 5e6; // 5 ms + long iters = 1; + for (;;) { + double t0 = now_sec(); + for (long k = 0; k < iters; ++k) memcpy(dst, src, bytes); + double elapsed = (now_sec() - t0) * 1e9; + if (elapsed >= TARGET_NS || iters >= (1L << 30)) break; + // Scale straight to the target rather than doubling, with a floor so a zero reading (the + // very case this loop exists for) still makes progress. + long next = elapsed > 0 ? (long)(iters * TARGET_NS / elapsed) + 1 : iters * 8; + iters = next > iters ? next : iters * 2; + } + + double samples[REPS]; + for (int r = 0; r < REPS; ++r) { + double t0 = now_sec(); + for (long k = 0; k < iters; ++k) memcpy(dst, src, bytes); + double t1 = now_sec(); + samples[r] = (t1 - t0) * 1e9 / (double)iters; // ns per copy + } + // Keep the result observable so the copy cannot be optimised away. + volatile char sink = dst[bytes - 1]; + (void)sink; + + qsort(samples, REPS, sizeof(double), cmp_double); + double med = samples[REPS / 2]; + double q1 = samples[REPS / 4]; + double q3 = samples[(3 * REPS) / 4]; + if (med <= 0.0) { + // Still unmeasurable. Report it as missing rather than as an infinite bandwidth: a row that + // says nothing is recoverable, a row that says `inf` gets averaged into a result. + fprintf(stderr, "%zu bytes: unmeasurable even at %ld iters/rep -- row skipped\n", bytes, + iters); + free(src); + free(dst); + continue; + } + double copy_gbps = (double)bytes / med; // bytes/ns == GB/s + double traffic_gbps = 2.0 * copy_gbps; // a memcpy reads AND writes + + printf("%zu,%.1f,%.1f,%.1f,%.2f,%.2f,%d\n", bytes, med, q1, q3, copy_gbps, traffic_gbps, REPS); + fflush(stdout); + + free(src); + free(dst); + } + return 0; +} +``` + +Add a one-line comment above every function that says what it does. Output the whole file, and change nothing else.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/explain1.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/explain1.txt new file mode 100644 index 0000000..86e53dd --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/explain1.txt @@ -0,0 +1,125 @@ +<|im_start|>user +`src/hir/places.rs`: + +```rust +//===- places.rs - Vx Compiler ---------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +//! Shared "place" helpers — one derivation of *which memory an lvalue names* and *whether two paths +//! overlap*, used by both the borrow checker (conflict detection, `expr.rs`) and the flat lowerer +//! (alias-scope disjointness, `flatten.rs`). +//! +//! These facts used to be computed twice -- the checker's `extract_base_and_path` and its three +//! inline overlap loops, and the lowerer's `place_base_path` / `paths_may_alias`. Both were sound +//! but duplicated; this module is the single source both now call. The borrow checker keeps its +//! `Vec` representation (its `BorrowRecord` stores string paths) by adapting +//! `base_and_path` at the boundary; the overlap predicate is generic over the path element, so +//! `Vec` and `Vec` share it without conversion. +use crate::symbol::Symbol; +use crate::syntax::Expr; + +/// The path element for an index: `[3]` for an integer literal, and [`ANY_INDEX`] for anything +/// else, which may be any element. So `q[0]` and `q[1]` are different places, and `q[i]` may be +/// either of them. +pub fn index_element(index: &Expr) -> String { + match index { + Expr::Range(_) => RANGE_INDEX.to_string(), + Expr::Number(n) => match n.value.parse::() { + Ok(k) => format!("[{k}]"), + Err(_) => ANY_INDEX.to_string(), + }, + _ => ANY_INDEX.to_string(), + } +} + +/// The path element of an index whose value is not known: it may name any element. +pub const ANY_INDEX: &str = "[?]"; + +/// The path element of a range index, `q[1..3]`: some rows of `q`. The result keeps its first +/// dimension, so an index after it, `q[1..3][1]`, picks a row of `q` again, not a column. +pub const RANGE_INDEX: &str = "[..]"; + +/// Add `elem` to the end of `path`. An index after a range is a row of the same dimension, so +/// it joins the range into [`ANY_INDEX`], and a range after a range stays a range. +pub fn push_path_element + From>(path: &mut Vec, elem: String) { + if let Some(last) = path.last_mut() { + if last.as_ref() == RANGE_INDEX && elem.starts_with('[') { + if elem != RANGE_INDEX { + *last = T::from(ANY_INDEX.to_string()); + } + return; + } + } + path.push(T::from(elem)); +} + +/// The root local and projection path of an lvalue: `o.x.y` -> `(o, [x, y])`, `q[0].x` -> +/// `(q, [[0], x])`, a bare local -> `(o, [])`. An index is a path element, written by +/// [`index_element`]. `None` for a base with no nameable root (`&5`, a call result). +pub fn base_and_path(e: &Expr) -> Option<(Symbol, Vec)> { + match e { + Expr::Identifier(id) => Some((id.name.clone(), Vec::new())), + Expr::MemberAccess(m) => { + let (root, mut path) = base_and_path(&m.base)?; + path.push(m.member.clone()); + Some((root, path)) + } + Expr::IndexAccess(ix) => { + let (root, mut path) = base_and_path(&ix.base)?; + push_path_element(&mut path, index_element(&ix.index)); + Some((root, path)) + } + _ => None, + } +} + +/// Whether two projection paths under the **same** root may name overlapping memory: true when +/// one is a prefix of the other (`[inner]` vs `[inner, v]`) or they match at every shared level. +/// Distinct fields (`[x]` vs `[y]`) and distinct constant indices (`[[0]]` vs `[[1]]`) are +/// disjoint; [`ANY_INDEX`] matches any element. Generic over the path element so the checker's +/// `[String]` and the lowerer's [`Symbol`] paths share it. Returning `true` for paths that are in +/// fact disjoint is always the safe direction: it withholds a `noalias` or reports a conflict. +pub fn paths_may_alias>(a: &[T], b: &[T]) -> bool { + a.iter().zip(b).all(|(x, y)| { + let (x, y) = (x.as_ref(), y.as_ref()); + x == y || [ANY_INDEX, RANGE_INDEX].contains(&x) || [ANY_INDEX, RANGE_INDEX].contains(&y) + }) +} + +/// How a place reads in a message: `q[0].x`, with a dot before each field and none before an +/// index. A tuple's fields, which the parser names `_0`, `_1`, .., read as the program writes +/// them: `t.0`. +pub fn display_place>(root: &str, path: &[T]) -> String { + let mut out = root.to_string(); + for p in path { + let p = p.as_ref(); + if !p.starts_with('[') { + out.push('.'); + } + match p.strip_prefix('_') { + Some(n) if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => out.push_str(n), + _ => out.push_str(p), + } + } + out +} + +/// A moved place as the checker records it, `p.a` or `t._0`, as it reads in a message. +pub fn display_dotted(place: &str) -> String { + let mut parts = place.split('.'); + let root = parts.next().unwrap_or_default(); + let path: Vec<&str> = parts.collect(); + display_place(root, &path) +} +``` + +Explain what this code does, function by function.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/explain2.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/explain2.txt new file mode 100644 index 0000000..75cc3ff --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/explain2.txt @@ -0,0 +1,128 @@ +<|im_start|>user +`src/hir/check/drop_waits.rs`: + +```rust +//===- check submodule - Vx Compiler ----------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// A `drop` runs with cancellation off, so a cancel cannot stop a wait in it. A `send` or `recv` +// there waits until the time limit of the `drop` when the other end never acts. W1036 warns +// about such a call, and the fix is `send_for` or `recv_for`, or a call of `within` (F6 and F6a +// in docs/discussions/waiting_tasks_channels_and_task_errors.md). A wait in a closure literal +// written as the body of `within` has the limit of the call, so it gets no warning. A closure in +// a variable gets the warning, because the check cannot see that the variable goes to `within`. `wait_limit` runs before cancellation is off, +// and it should return a time and not wait, so W1036 warns about a wait in it too. +// It is a warning, not an error, because the check does not look into the functions that the +// `drop` calls. +// +//===----------------------------------------------------------------------===// + +use super::super::*; + +impl TypeChecker<'_> { + /// Whether `func` is the `drop` of a `Drop` impl: the `drop` that its receiver type uses. + pub(crate) fn is_drop_impl(&mut self, func: &Function) -> bool { + if !func.name.ends_with("drop") && !func.name.contains("$drop$") { + return false; + } + self.is_drop_impl_method(func, "drop") + } + + /// Whether `func` is the `wait_limit` of a `Drop` impl. + pub(crate) fn is_wait_limit_impl(&mut self, func: &Function) -> bool { + if !func.name.contains("wait_limit") { + return false; + } + self.is_drop_impl_method(func, "wait_limit") + } + + /// Whether `func` is the method `method` of the `Drop` impl of its receiver type. + fn is_drop_impl_method(&mut self, func: &Function, method: &str) -> bool { + let Some((_, receiver)) = func.params.first() else { + return false; + }; + let ty = match receiver { + Type::Borrow { inner, .. } | Type::Ref(inner, _) => inner.as_ref().clone(), + ty => ty.clone(), + }; + self.drops_impl_method(&ty, method) + .is_some_and(|name| name.as_ref() == func.name.as_ref()) + } + + /// W1036 when the `drop` of a `Drop` impl calls `method` on a value of type `base`, and the + /// call is a channel wait with no time limit. + pub(crate) fn warn_wait_in_drop(&mut self, base: &Type, method: &str, span: &Span) { + if !(self.in_drop || self.in_wait_limit) || self.within_depth > 0 || self.speculating { + return; + } + let timed = match method { + "send" => "send_for", + "recv" => "recv_for", + _ => return, + }; + let base = match base { + Type::Borrow { inner, .. } | Type::Ref(inner, _) => inner.as_ref(), + ty => ty, + }; + let name = match base { + Type::Struct(n, _) => n.clone(), + Type::GenericInstance(b, _) => match b.as_ref() { + Type::Struct(n, _) => n.clone(), + _ => return, + }, + _ => return, + }; + // The ends whose `send` or `recv` can wait. The `send` of a oneshot and of a watch + // channel does not wait. + let waits = match (method, name.split('<').next()) { + ("send", Some(end)) => matches!(end, "Sender" | "BroadcastSender"), + (_, Some(end)) => matches!( + end, + "Receiver" + | "OneshotReceiver" + | "BroadcastReceiver" + | "WatchReceiver" + | "WorkReceiver" + ), + _ => false, + }; + if !waits { + return; + } + if self.in_wait_limit { + self.errors.warn( + crate::diagnostic::DiagnosticCode::W1036, + format!( + "'{method}' waits in 'wait_limit'. 'wait_limit' runs before the drop, to say \ + how long its waits can take, so it should return a time and not wait" + ), + Some(crate::diagnostic::SourceSpan::from_ast_span(span)), + ); + return; + } + self.errors.warn( + crate::diagnostic::DiagnosticCode::W1036, + format!( + "'{method}' waits with no time limit of its own in a 'drop'. A drop runs with \ + cancellation off, so if the other end of the channel never acts, this wait \ + holds up the drop until the limit of the drop: its type's 'wait_limit', 10 \ + seconds by default. Use '{timed}' with a time limit, or put the wait in the \ + body of 'within'" + ), + Some(crate::diagnostic::SourceSpan::from_ast_span(span)), + ); + } +} +``` + +Explain what this code does, function by function.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/explain3.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/explain3.txt new file mode 100644 index 0000000..a0c208f --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/explain3.txt @@ -0,0 +1,133 @@ +<|im_start|>user +`src/hir/decl_check/bounds.rs`: + +```rust +//===- decl_check submodule - Vx Compiler -----------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// A bound on a type parameter has to name a trait that exists. +// +//===----------------------------------------------------------------------===// + +use super::super::*; + +impl TypeChecker<'_> { + /// Refuse a bound such as `T : NoSuchTrait` whose trait is not declared (E3042). + /// + /// A bound is otherwise only asked when a call binds the parameter, so a misspelled one + /// on a function nobody calls, or on a struct, was never reported. + pub fn check_bounds_name_a_trait(&mut self) { + // (where the bound is written, the parameter, the trait it names, the place of the owner) + let mut unknown: Vec<(String, String, String, decl::DeclPlace)> = Vec::new(); + let traits = &self.env.traits; + let mut collect = + |owner: &str, generics: &[decl::GenericParam], place: &decl::DeclPlace| { + for param in generics { + if let decl::GenericParam::Type { name, bounds } = param { + for bound in bounds { + // `D : Topology` and `M : Memory` mark a topology and a memory + // parameter. They are keywords, not traits. + if matches!(bound.trait_name.as_ref(), "Topology" | "Memory") { + continue; + } + if !traits.contains_key(&bound.trait_name) { + unknown.push(( + owner.to_string(), + name.to_string(), + bound.trait_name.to_string(), + place.clone(), + )); + } + } + } + } + }; + + for s in self.env.structs.values() { + collect(&format!("struct {}", s.name), &s.generics, &s.place); + } + for e in self.env.enums.values() { + collect(&format!("enum {}", e.name), &e.generics, &e.place); + } + for t in self.env.traits.values() { + collect(&format!("trait {}", t.name), &t.generics, &t.place); + // A method signature has no place of its own, so its trait's is used. + for m in &t.methods { + collect( + &format!("method {}::{}", t.name, m.name), + &m.generics, + &t.place, + ); + } + } + for block in self.env.impls.values().flatten() { + let owner = match &block.trait_name { + Some(t) => format!("impl {} for {}", t, block.target_type), + None => format!("impl {}", block.target_type), + }; + collect(&owner, &block.generics, &block.place); + let impl_params: Vec<&str> = block.generics.iter().map(|g| g.name()).collect(); + // A trait default copied into the impl is reported on the trait. + for m in block + .methods + .iter() + .filter(|m| !block.copied_defaults.contains(&m.name)) + { + // A method is also given its impl's parameters, already reported above. + let own: Vec = m + .generics + .iter() + .filter(|g| !impl_params.contains(&g.name())) + .cloned() + .collect(); + collect( + &format!("method {}::{}", block.target_type, m.name), + &own, + &function_place(m), + ); + } + } + for (f, _) in self.env.generic_functions.values() { + collect(&format!("fn {}", f.name), &f.generics, &function_place(f)); + } + + // The tables are hash maps, and a generic method can be listed under its impl and as a + // function, so sort for a stable order and drop the repeats. + unknown.sort_by(|a, b| (&a.0, &a.1, &a.2).cmp(&(&b.0, &b.1, &b.2))); + unknown.dedup_by(|a, b| (&a.0, &a.1, &a.2) == (&b.0, &b.1, &b.2)); + let outside = self.errors.here(); + for (owner, param, trait_name, place) in unknown { + self.errors.point_at(&place, &outside); + self.errors.error_with_code( + crate::diagnostic::DiagnosticCode::E3042, + format!( + "the bound `{param} : {trait_name}` on `{owner}` names no trait; \ + no trait called '{trait_name}' is declared or imported" + ), + None, + ); + } + self.errors.point_back(outside); + } +} + +/// Where a function is written, as a declaration's place. +fn function_place(f: &decl::Function) -> decl::DeclPlace { + decl::DeclPlace { + file: f.file.clone(), + span: f.span, + } +} +``` + +Explain what this code does, function by function.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/write1.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/write1.txt new file mode 100644 index 0000000..316ba64 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/write1.txt @@ -0,0 +1,7 @@ +<|im_start|>user +Write a Python function merge_intervals(intervals) that merges overlapping closed intervals and returns them sorted. Add pytest tests for it, with empty input and touching intervals.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/write2.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/write2.txt new file mode 100644 index 0000000..bcb9afb --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/write2.txt @@ -0,0 +1,7 @@ +<|im_start|>user +Write a C function `void reverse_words(char *s)` that reverses the order of the words in a string in place, with single spaces between words. Add a main() that tests it.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/write3.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/write3.txt new file mode 100644 index 0000000..d992c11 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/heldout/vx/write3.txt @@ -0,0 +1,7 @@ +<|im_start|>user +Write a Rust struct Trie with new, insert, contains and starts_with for lowercase ASCII words. Add unit tests.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/tokens.csv b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/tokens.csv new file mode 100644 index 0000000..68741a9 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/tokens.csv @@ -0,0 +1,31 @@ +prompt,tokens +context/ctx64,64 +context/ctx512,512 +context/ctx2048,2048 +context/ctx8192,8192 +context/ctx16384,16384 +context/ctx32768,32768 +twelve/edit1,1799 +twelve/edit2,1577 +twelve/edit3,2251 +twelve/complete1,1726 +twelve/complete2,1608 +twelve/complete3,1508 +twelve/write1,41 +twelve/write2,52 +twelve/write3,39 +twelve/explain1,1384 +twelve/explain2,1549 +twelve/explain3,1915 +heldout/edit1,1668 +heldout/edit2,1286 +heldout/edit3,1605 +heldout/complete1,1044 +heldout/complete2,1086 +heldout/complete3,1288 +heldout/write1,44 +heldout/write2,52 +heldout/write3,35 +heldout/explain1,1503 +heldout/explain2,1330 +heldout/explain3,1257 diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/complete1.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/complete1.txt new file mode 100644 index 0000000..e4f8827 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/complete1.txt @@ -0,0 +1,130 @@ +<|im_start|>user +`src/report.rs`: + +```rust +//===- report.rs - Vx Compiler ---------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// What the memory-algebra analysis found, in the shape a consumer reads it in: resident sets, +// transfer routes and their costs, and counted traffic. +// +// These are the checker's output, not the checker's working state, which is why they live outside +// hir/. --diagnostics-json is a report format, and a report format that imports the type checker's +// internals cannot change without the checker changing too. +// +//===----------------------------------------------------------------------===// + +/// One memory space's working set for a function: the granule-rounded sum of the tiles placed +/// there, against the space's declared capacity. Recorded for *every* placed space, not only +/// those that overflow — an admitted program emits no capacity diagnostic, so this is the only +/// place its resident total appears. Downstream that total is what turns a capacity verdict into +/// an engine's required memory utilization (#285). See [`crate::hir::env::TypeChecker::resident_sets`]. +#[derive(Debug, Clone, PartialEq)] +pub struct ResidentSet { + pub space: crate::syntax::MemorySpace, + /// The device whose copy of the space this is (`Card[1]`), when the space is the memory of a + /// topology with more than one device. Each device has its own copy and its own working set. + pub device: Option, + /// Granule-rounded sum of tiles placed in this space by one function. + pub total_bytes: u64, + pub capacity_bytes: u64, + pub tiles: usize, + /// Whether the space is declared `overcommit` (an overflow is W1028, not E6010). + pub overcommit: bool, +} + +/// A resolved `transfer`: the chain of memory spaces the value actually moves through and the +/// declared cost of each hop. A direct transfer has one hop; a multi-hop route (synthesized when +/// no direct edge exists) has one per staging step. `derived_cost` is the bandwidth-roofline cost +/// when the declarations make it computable, which is what the emitted `vx.transfer` carries. +/// See [`crate::hir::env::TypeChecker::staging_routes`] (#282). +#[derive(Debug, Clone, PartialEq)] +pub struct StagingRoute { + /// The spaces traversed, source first: `[CPU_DRAM, HBM3e, SMEM]`. + pub path: Vec, + /// Per-edge declared cost, one shorter than `path`; `None` for an edge with no declared cost. + pub edge_costs: Vec>, + /// The cost graph's total for the whole route. + pub total_cost: u32, + /// Bandwidth-derived (roofline) cost, when the declarations supply bandwidths. + /// + /// `u64`, not `u32`: a picosecond-resolution time cost overflows `u32` at 4.3 ms, which a + /// multi-gigabyte host transfer exceeds, and a saturated cost would read as a slow transfer + /// rather than a missing one. + pub derived_cost: Option, + /// Bytes this transfer moves, when the shape is statically known. + /// + /// Without it a harvested cost cannot be interpreted: "260064 ps" is not a prediction unless + /// the size it is a cost *of* travels with it, and comparing predicted against measured needs + /// both. `None` for a dynamically-shaped tensor, where no cost is derivable either. + pub bytes: Option, + /// Which cost source produced `derived_cost`. The two are mutually exclusive per edge (E6013), + /// so this names the one that applied rather than a precedence winner — and it is what tells a + /// consumer whether a residual is attributable to a declared link figure or to an inferred + /// containment roofline. + pub cost_source: Option, + /// The unit `derived_cost` is in — cycles, or picoseconds. Carried rather than dropped because + /// one program's routes legitimately mix them: an on-die hop declared `B/cyc` and a host link + /// declared `GB/s` produce costs of different *dimension*, and a harvested prediction that does + /// not say which is not a prediction. (The fleet's `HBM->L2` and `L2->SMEM` are exactly this + /// pair.) + pub derived_unit: Option, + /// Which composition law priced a containment route: `sum` or `bottleneck`. + /// + /// `None` for a link-rate hop, which has one leg and so composes nothing. Carried because the + /// two laws differ by ~2x on a multi-hop walk and a harvested prediction that does not say + /// which one applied cannot be re-scored later -- the same reason `derived_unit` is carried. + pub composition: Option, + /// Bytes moved per space, derived from code (#353). `None` when the movement cannot be + /// counted statically, in which case `traffic_absent_reason` says why -- a guess here would + /// be indistinguishable from a measurement in the record a campaign harvests, which is the + /// same reason `derived_cost` is `None` rather than 0 when no bandwidth is declared. + pub traffic: Option, + /// Why `traffic` is `None`. `None` when traffic is present. + pub traffic_absent_reason: Option, +} + +/// Bytes read and written against one placed buffer by a `spawn` region (#353). +/// +/// Per BUFFER, not just per space, because the amplification this stage exists to show is a +/// fact about a particular tensor: a streamed operand is re-read on every outer iteration +/// while the blocked one is read once. Summed into their shared space they +/// become one number that hides which of them is the problem. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BufferTraffic { + pub buffer: String, + pub space: crate::syntax::MemorySpace, + pub read_bytes: u64, + pub written_bytes: u64, +} + +/// What one `spawn on(...)` region moves, counted from its indexed accesses and the static +/// trip counts of the loops around them (#353). +/// +/// The transfer-hop counts say what it costs to GET a tile to a space. This says what the +/// kernel then does with it, which is where re-reading lives: a tile staged once and read +/// sixteen times is sixteen reads, and no declared edge cost can say so because the movement +/// across the edge happened exactly once. +#[derive(Debug, Clone, PartialEq)] +pub struct SpawnRegionTraffic { + /// The function the `spawn` appears in. + pub function: String, + /// The topology the region runs on, as its display name. + pub topology: String, + /// Aggregate per space, or `None` when the region could not be counted exactly. + pub traffic: Option, + /// Per placed buffer, sorted by name. Empty when `traffic` is `None`. +``` + +This file stops in the middle. Continue it from exactly where it stops. Output only the rest of the file.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/complete2.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/complete2.txt new file mode 100644 index 0000000..64b29cb --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/complete2.txt @@ -0,0 +1,146 @@ +<|im_start|>user +`scripts/tools/check_doc_examples.py`: + +```python +#!/usr/bin/env python3 +"""Compile every Vx example in the documentation. + +Documentation drifts silently because nothing executes it. An audit of this repository found the +README's own headline example did not parse, a tutorial teaching a topology syntax that was never +implemented, `grad` documented with the wrong arity, and a grammar production admitting two types +the parser rejects. Every one of those had been correct when written. + +This makes that class of error a build failure. + + python3 scripts/tools/check_doc_examples.py # check everything + python3 scripts/tools/check_doc_examples.py --list # show what would be checked + python3 scripts/tools/check_doc_examples.py README.md # check specific files + +A block is checked when it is fenced ```vx or ```rust, contains a top-level declaration, and is +not skipped by one of the rules below. To exempt a block deliberately, put + + + +on the line before its fence, ideally with a reason. + +Most blocks are only parsed. A block marked + + + +is compiled and run instead, and what it prints must equal the ```text block that follows it +(one short line, such as "It prints:", may come between them). + +The hand-written pages under `www/` are checked as well, through their `
` blocks. The
+landing page carries the most-read Vx code on the site and was the only code on it that nothing
+compiled -- everything in the book is covered because the book is markdown. The same skip comment
+works there, on the line before the `
`.
+
+Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions.
+See LICENSE for license information.
+SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+"""
+
+import html
+import os
+import re
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+FENCE = re.compile(
+    r"(?:\s*\n)?```(vx|rust)\n(.*?)```", re.S
+)
+# The expected output, after at most one short line such as "It prints:".
+OUTPUT = re.compile(r"\s*(?:[^`\n]+\n\s*)?```text\n(.*?)```", re.S)
+
+# The same idea for the hand-written pages: a 
 block, optionally preceded by the skip
+# comment. Their code carries syntax highlighting as  tags, which are stripped before the
+# body is compiled.
+HTML_BLOCK = re.compile(
+    r"(?:()\s*\n?\s*)?
(.*?)
", re.S +) +TAG = re.compile(r"<[^>]+>") + +# A block has to declare something to be a compilable unit. Bare statements are illustrative +# fragments and are left alone. +DECLARES = re.compile(r"^\s*(fn |pub fn |unsafe fn |safe fn |struct |enum |trait |impl |extern |macro_rules!|Memory |Topology )", re.M) + +# Constructs that exist in Rust and not in Vx. Architecture documents embed compiler internals in +# ```rust fences, and those are Rust, not examples of the language. +RUST_ONLY = re.compile( + r"^\s*use\s+\w|#\[|#!\[|\bpub\s+(struct|enum|mod|const|trait)\b|\bcrate::|" + r"&self\b|&mut self\b|\bimpl\s+\w+\s+for\s+\w+\s*\{[^}]*fn\s+\w+\s*\(\s*&|" + # Types and idioms from the standard Rust library that Vx has no equivalent of. The + # architecture documents embed real compiler internals, and these are what give them away. + r"\bArc<|\bRc<|\bWeak<|\bRefCell<|\bMutex<|\bRwLock<|\bBox +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/complete3.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/complete3.txt new file mode 100644 index 0000000..4452b50 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/complete3.txt @@ -0,0 +1,136 @@ +<|im_start|>user +`src/session.rs`: + +```rust +//===- session.rs - Vx Compiler --------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines the core compiler session and local worker states. +// It orchestrates the compilation pipeline across multiple threads, managing shared +// diagnostics, module registries, and global state required during the lowering +// of Vx source code to MLIR. +// +//===----------------------------------------------------------------------===// +use crate::bytecode::HirInstruction; +use crate::gid::{TypeId, UnboundedFunctionMetadata}; +use std::sync::Arc; + +// The frozen nominal-type registry (layouts + module indices + cycle-checked). Built once per +// compilation at the Phase 2 freeze point and shared read-only across worker threads. Re-exported +// here so `GlobalSession` and the verifier name it via `session`, but the type lives in `registry`. +pub use crate::registry::ImmutableGlobalRegistry; + +/// Represents the frozen past of the compilation process. +/// It contains everything compiled before the current phase. +/// +/// # Data-Oriented Design (DOD) Constraints +/// This session deliberately separates dynamic compiler metadata into strictly +/// typed, homogeneous arenas rather than using a single polymorphic `Enum` array +/// (e.g., `enum SlowPathData { Function(...), Generics(...) }`). +/// +/// 1. **Cache-Line Density**: `UnboundedFunctionMetadata` is a dense structure of `u64` +/// bitfields. Iterating over it is highly predictable. `Vec`, however, +/// is a heap-allocated fat pointer with variable lengths. Mixing them would introduce +/// unpredictable struct padding and pointer-chasing overhead. +/// 2. **Hardware Prefetching**: By keeping `generics_arena` separate, the CPU's spatial +/// prefetcher can stream through the dense `slow_path_arena` at maximum bandwidth +/// during the critical lifetime subtyping pass, without stalling on scattered `Vec` pointers. +pub struct GlobalSession { + pub epoch: u64, + /// How this compilation forms a generic instantiation's identity. + /// + /// A per-compilation fact, frozen with the rest of the epoch, because that is what it is: two + /// compilations in one process may legitimately want different strategies, and a worker must + /// not be able to observe a choice that belongs to someone else's compile. It lived in a + /// process-global until Vx#381 -- set from `--intern-mode` on one thread and read by every + /// worker from inside the parallel type-check. + pub intern_mode: crate::intern_mode::InternMode, + /// `-fauto-schedule-levels`: an `across` loop on an arch that cannot launch its levels runs + /// as a plain `for` that carries its level, instead of E6032. + pub auto_schedule_levels: bool, + pub registry: Arc, + + /// The dense, homogeneous arena for complex parameter and lifetime evaluation. + /// Accessed heavily during Phase 1 type-checking and borrow checking. + pub slow_path_arena: Arc>, + + /// The heterogeneous arena for structural generic instantiations. + /// Separated to prevent cache fragmentation in the `slow_path_arena`. + pub generics_arena: Arc>, + pub generics_offsets: Arc>, +} + +impl GlobalSession { + /// A session with an *empty* frozen registry — for callers that don't build one (the + /// sequential driver, unit tests). The parallel pipeline uses [`Self::with_registry`]. + pub fn new(epoch: u64) -> Self { + Self::with_registry( + epoch, + ImmutableGlobalRegistry::build_and_validate(Vec::new()) + .expect("an empty registry is always valid"), + ) + } + + /// A session holding the frozen registry built at the Phase 2 freeze point. + pub fn with_registry(epoch: u64, registry: ImmutableGlobalRegistry) -> Self { + Self { + epoch, + intern_mode: crate::intern_mode::InternMode::Deferred, + auto_schedule_levels: false, + registry: Arc::new(registry), + slow_path_arena: Arc::new(Vec::new()), + generics_arena: Arc::new(Vec::new()), + generics_offsets: Arc::new(Vec::new()), + } + } + + /// The same session with a chosen interning strategy. Consuming rather than a setter, because + /// the session is frozen once it is shared: every worker holds an `Arc` of it and reads it by + /// `&`, so it must be settled before it is wrapped. + pub fn in_intern_mode(mut self, mode: crate::intern_mode::InternMode) -> Self { + self.intern_mode = mode; + self + } + + /// The same session with `-fauto-schedule-levels` on or off. + pub fn auto_schedule_levels(mut self, on: bool) -> Self { + self.auto_schedule_levels = on; + self + } +} + +/// Represents the mutable present of a single worker thread during Phase 1. +pub struct LocalWorkerState { + pub global: Arc, + + // Completely lock-free, thread-local mutation + pub local_slow_path_arena: Vec, + pub local_generics_arena: Vec, + pub local_generics_offsets: Vec<(usize, usize)>, + + // The flat arrays replacing the AST + pub local_type_stream: Vec, // array of 256-bit GIDs + pub local_hir_stream: Vec, + + /// Tensor-type side table: `GID -> (element, shape)` for every tensor type this function's stream + /// references. Tensor GIDs are content hashes (not invertible) and tensors are structural (never + /// in the nominal registry), so codegen can't reconstruct a tensor's memref type from the stream + /// alone -- most acutely for `TensorAlloc`. The lowerer records it here as it emits tensor values; + /// the flat codegen consumes it (the tensor analogue of the registry's struct `layouts`). + pub local_tensor_types: Vec<(TypeId, crate::syntax::ElementType, Vec)>, + + /// String side table: the string-literal bytes for each `PrintStr` this function's stream emits, +``` + +This file stops in the middle. Continue it from exactly where it stops. Output only the rest of the file.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/edit1.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/edit1.txt new file mode 100644 index 0000000..2acb824 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/edit1.txt @@ -0,0 +1,183 @@ +<|im_start|>user +`scripts/tools/gen_error_index.py`: + +```python +#!/usr/bin/env python3 +"""Generate the diagnostic index from the compiler's own diagnostic table. + +`src/diagnostic.rs` is the single place every code is declared, each with a doc comment saying +what it means and a section header grouping it. That makes it the only honest source for a +reference: a hand-written index drifts the moment someone adds a code, and 78 of the 113 codes +were undocumented anywhere before this existed. + + python3 scripts/tools/gen_error_index.py # write the index + python3 scripts/tools/gen_error_index.py --check # fail if it is out of date + +Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +See LICENSE for license information. +SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +""" + +import re +import subprocess +import sys +from pathlib import Path + +SOURCE = Path("src/diagnostic.rs") +OUTPUT = Path("www/book/src/error-index.md") + +# The section headers in diagnostic.rs are terse. These say what the stage actually does, so the +# index reads as a guide rather than as a dump of the enum. +SECTION_BLURB = { + "Warnings": "Reported without stopping the compile. A warning means the program is accepted " + "but something in it is probably not what was intended.", + "Parser Errors": "Raised while turning source text into an AST. The program is not " + "syntactically valid Vx.", + "Name Resolution Errors": "Raised when a name cannot be resolved to a declaration, or " + "resolves to something of the wrong kind.", + "Type Errors": "Raised by the type checker. Vx performs no implicit numeric conversion, so " + "many of these are mismatches that a language with coercion would have silently accepted.", + "Borrow/Ownership Errors": "Raised by the borrow checker and the linear-type rules. These " + "rule out use-after-move, aliasing violations and lifetimes that outlive what they point at.", + "Safety Errors": "Raised where an operation needs an `unsafe` context and does not have one.", + "Topology/Hardware Errors": "Raised by the placement and capacity rules — the checks that " + "make Vx different from a single-address-space language. A value in the wrong memory space, " + "a region on the wrong device, a working set that does not fit, or a transfer with no " + "declared route.", + "Tensor/Math Errors": "Raised on tensor shapes and numeric operations, including shape " + "mismatches that are decided at compile time.", + "Contract/Verification Errors": "Raised when a `requires`, `ensures` or `invariant` clause " + "cannot be discharged, or when a seam obligation is left unproven.", +} + +HEADER = """# Diagnostic index + +Every code that the Vx compiler defines, and what it means. Some codes, among them the parser's +`E1xxx` codes, do not appear in the compiler's messages yet +([Vx#3227](https://github.com/vx-lang/Vx/issues/3227)). + +Codes are grouped by the compilation stage that raises them, and the group is readable off the +number: `E1xxx` is the parser, `E3xxx` the type checker, `E6xxx` the placement and capacity rules, +and so on. A `W` prefix is a warning rather than an error. + +> This file is generated from `src/diagnostic.rs` by `scripts/tools/gen_error_index.py`. Edit the +> doc comments on the codes there, not this file. + +Every code below links to its own page, which carries the message the compiler emits and, where +the test suite has one, a program that triggers it. + +""" + + +def parse(source_text): + """Yield (section, code, description) in declaration order.""" + section = None + pending = [] + + for line in source_text.splitlines(): + stripped = line.strip() + + header = re.match(r"//\s*---\s*(.+?)\s*\((?:[EW]\dxxx)\)\s*---", stripped) + if header: + section = header.group(1) + pending = [] + continue + + doc = re.match(r"///\s?(.*)", stripped) + if doc: + pending.append(doc.group(1).strip()) + continue + + code = re.match(r"^([EW][0-9]{4}),$", stripped) + if code: + yield section, code.group(1), " ".join(p for p in pending if p).strip() + pending = [] + continue + + # Anything else (attributes, blank lines, the enum braces) resets the doc buffer only if + # it is a real statement; blank lines inside a doc block are kept. + if stripped and not stripped.startswith("#"): + pending = [] + + +def render(entries): + out = [HEADER] + by_section = {} + for section, code, desc in entries: + by_section.setdefault(section or "Uncategorised", []).append((code, desc)) + + out.append("## Contents\n") + for section in by_section: + anchor = section.lower().replace(" ", "-").replace("/", "") + codes = [c for c, _ in by_section[section]] + out.append(f"- [{section}](#{anchor}) — `{codes[0]}`–`{codes[-1]}` ({len(codes)} codes)") + out.append("") + + for section, items in by_section.items(): + out.append(f"## {section}\n") + blurb = SECTION_BLURB.get(section) + if blurb: + out.append(f"{blurb}\n") + out.append("| Code | Meaning |") + out.append("| --- | --- |") + for code, desc in items: + # Each code also has a page of its own at vxlang.org/errors/, with the message and a + # program that triggers it. Root-relative, so mdBook leaves it alone. + out.append(f"| [`{code}`](/errors/{code}/) | {desc or '—'} |") + out.append("") + + total = sum(len(v) for v in by_section.values()) + out.append("______________________________________________________________________\n") + out.append(f"{total} diagnostics.\n") + return "\n".join(out) + + +def main(): + if not SOURCE.exists(): + print(f"error: {SOURCE} not found; run from the repository root", file=sys.stderr) + return 1 + + entries = list(parse(SOURCE.read_text())) + if not entries: + print("error: no diagnostic codes parsed -- has the table's shape changed?", file=sys.stderr) + return 1 + + rendered = render(entries) + + # Matches the shape mdformat produces, so the generated file needs no follow-up pass. + + try: + rendered = subprocess.run( + ["mdformat", "-"], input=rendered, capture_output=True, text=True, check=True + ).stdout + except (FileNotFoundError, subprocess.CalledProcessError): + pass # mdformat is optional locally; CI has it. + + if "--check" in sys.argv: + current = OUTPUT.read_text() if OUTPUT.exists() else "" + if current != rendered: + print( + f"error: {OUTPUT} is out of date.\n" + f" Run: python3 {Path(__file__).as_posix()}", + file=sys.stderr, + ) + return 1 + print(f"{OUTPUT} is up to date ({len(entries)} diagnostics)") + return 0 + + OUTPUT.write_text(rendered) + print(f"wrote {OUTPUT} ({len(entries)} diagnostics)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) +``` + +Add a type hint to every function parameter and return value. Output the whole file, and change nothing else.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/edit2.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/edit2.txt new file mode 100644 index 0000000..e53583a --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/edit2.txt @@ -0,0 +1,152 @@ +<|im_start|>user +`src/hash.rs`: + +```rust +//===- hash.rs - Vx Compiler -----------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file provides specialized, stable hashing utilities for the compiler. +// It implements robust hash generation for type IDs, module signatures, and +// anonymous structural types, ensuring consistent symbol mangling and metadata +// serialization across incremental builds. +// +//===----------------------------------------------------------------------===// +/// 64-bit FNV-1a parameters (standard offset basis + prime). FNV is **project-controlled and stable +/// across toolchains** — unlike `FxHasher`/`DefaultHasher`, whose algorithms may change between +/// library/compiler releases. GID word 0/1 are content hashes that must reproduce byte-for-byte +/// across builds and machines (reproducible builds, cross-crate identity), so the algorithm cannot +/// be an unpinned dependency. This mirrors the FNV scheme `arch.rs` already hand-rolls for dispatch +/// ids, for the same reason. See #195. FNV-1a is *not* cryptographic: accidental collisions are +/// negligible but not impossible, so `ImmutableGlobalRegistry::build_and_validate` additionally +/// rejects any two distinct symbols that land on the same GID. +const FNV_OFFSET_BASIS_64: u64 = 0xcbf2_9ce4_8422_2325; +const FNV_PRIME_64: u64 = 0x0000_0100_0000_01b3; + +/// Streaming 64-bit FNV-1a: fold `bytes` into a running `hash` (seeded with the offset basis on the +/// first call, then chained) so multi-field def paths hash deterministically as one stream. +#[inline] +fn fnv1a_64(hash: u64, bytes: &[u8]) -> u64 { + let mut hash = hash; + for b in bytes { + hash ^= *b as u64; + hash = hash.wrapping_mul(FNV_PRIME_64); + } + hash +} + +/// Computes the stable 64-bit content hash (GID word 0) for a given module path. +pub fn compute_module_hash(module_path: &str) -> u64 { + fnv1a_64(FNV_OFFSET_BASIS_64, module_path.as_bytes()) +} + +/// Represents the stable topological path to a definition (struct, enum, closure). +/// This prevents incremental compilation breakage when anonymous types are re-ordered. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum DefPath<'a> { + /// A named, top-level symbol (e.g., `MyStruct`). + Named(&'a str), + /// An anonymous closure or comptime block, defined by its structural layout + /// or its position within a specific parent item, rather than file line number. + Anonymous { + parent_hash: u64, + structural_hash: u64, + }, +} + +impl<'a> DefPath<'a> { + /// Computes the deterministic 64-bit Word 1 for the TypeId (stable FNV-1a; see [`fnv1a_64`]). + pub fn compute_symbol_hash(&self) -> u64 { + match self { + DefPath::Named(name) => { + // 0 is the discriminator for Named. + let h = fnv1a_64(FNV_OFFSET_BASIS_64, &[0u8]); + fnv1a_64(h, name.as_bytes()) + } + DefPath::Anonymous { + parent_hash, + structural_hash, + } => { + // 1 is the discriminator for Anonymous; fold the two u64 fields in a fixed byte + // order so the hash is architecture-independent. + let mut h = fnv1a_64(FNV_OFFSET_BASIS_64, &[1u8]); + h = fnv1a_64(h, &parent_hash.to_le_bytes()); + fnv1a_64(h, &structural_hash.to_le_bytes()) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Pins the exact algorithm + constants (#195). These are FNV-1a-64 golden values computed + /// independently; if the hash ever silently changes (e.g. someone swaps back to a std hasher), + /// every previously emitted GID / serialized metadata would break, and this catches it. + #[test] + fn hash_is_stable_fnv1a_golden_values() { + assert_eq!(compute_module_hash("crate::a"), 0xdbc1_8e8e_2c15_a207); + assert_eq!( + DefPath::Named("Foo").compute_symbol_hash(), + 0xed6f_617e_4534_5949 + ); + } + + /// Empty input hashes to the bare offset basis (the FNV-1a identity) — a sanity anchor on the + /// seeding. + #[test] + fn empty_module_path_is_offset_basis() { + assert_eq!(compute_module_hash(""), FNV_OFFSET_BASIS_64); + } + + #[test] + fn test_named_defpath_stability() { + let path1 = DefPath::Named("MyStruct"); + let path2 = DefPath::Named("MyStruct"); + assert_eq!(path1.compute_symbol_hash(), path2.compute_symbol_hash()); + + let path3 = DefPath::Named("OtherStruct"); + assert_ne!(path1.compute_symbol_hash(), path3.compute_symbol_hash()); + } + + #[test] + fn test_anonymous_defpath_stability() { + let parent = DefPath::Named("ParentFn").compute_symbol_hash(); + + let anon1 = DefPath::Anonymous { + parent_hash: parent, + structural_hash: 0x12345678, + }; + + let anon2 = DefPath::Anonymous { + parent_hash: parent, + structural_hash: 0x12345678, + }; + + assert_eq!(anon1.compute_symbol_hash(), anon2.compute_symbol_hash()); + + let anon_different_structure = DefPath::Anonymous { + parent_hash: parent, + structural_hash: 0x87654321, + }; + + assert_ne!( + anon1.compute_symbol_hash(), + anon_different_structure.compute_symbol_hash() + ); + } +} +``` + +Add a `///` doc comment above every function that has none. Output the whole file, and change nothing else.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/edit3.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/edit3.txt new file mode 100644 index 0000000..a8c37da --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/edit3.txt @@ -0,0 +1,207 @@ +<|im_start|>user +`runtime/vx_mlir_shims.c`: + +```c +/*===- vx_mlir_shims.c - Vx Compiler ------------------------------*- C -*-===*\ +|* *| +|* Part of the Vx Project, under the Apache License v2.0 with LLVM *| +|* Exceptions. *| +|* See LICENSE for license information. *| +|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| +|* *| +\*===----------------------------------------------------------------------===*/ +/* The half-precision memref printers MLIR does not export in the form emitted + * code calls. + * + * `libmlir_runner_utils` exports printMemrefF32, F64, I32 and I64 both plainly + * and packed as `_mlir_ciface_*`, but the half-precision printers ONLY packed + * -- `nm` on MLIR 22 shows `_mlir_ciface_printMemrefBF16` and no plain + * `printMemrefBF16`. Codegen emits the plain call, so a bf16 program could not + * link, run, or emit an object. Its RUN line only emits MLIR, so nothing + * noticed. + * + * `llvm.emit_c_interface` on the declaration does not fix it: MLIR then gives + * the function a body and the ExecutionEngine wants `_mlir_printMemrefBF16` + * instead, which no library exports either. Supplying the plain symbol here is + * what closes it, and it belongs beside the runtime rather than in vx_std_core + * -- the standard library has no MLIR dependency and should not gain one to + * print a tensor. + * + * MLIR's unpacked convention for `memref<*xT>` passes (rank, pointer to the + * ranked descriptor). The packed entry point takes a pointer to exactly that + * pair. + */ + +#include +#include +#include +#include + +typedef struct { + int64_t rank; + void *descriptor; +} VxUnrankedMemRef; + +extern void _mlir_ciface_printMemrefBF16(void *unranked); +extern void _mlir_ciface_printMemrefF16(void *unranked); +extern void _mlir_ciface_printMemrefI8(void *unranked); +extern void _mlir_ciface_printMemrefI16(void *unranked); + +void printMemrefBF16(int64_t rank, void *descriptor) { + VxUnrankedMemRef packed = {rank, descriptor}; + _mlir_ciface_printMemrefBF16(&packed); +} + +void printMemrefF16(int64_t rank, void *descriptor) { + VxUnrankedMemRef packed = {rank, descriptor}; + _mlir_ciface_printMemrefF16(&packed); +} + +/* The integer tensor printers MLIR does not supply in the form codegen calls, + * or prints wrongly. MLIR has no unsigned integer type: a `u32` tensor is a + * memref of `i32`, and MLIR's printMemrefI32 reads 4000000000 as -294967296. + * printMemrefU8/U16/U32/U64 read the elements unsigned. printMemrefI8 cannot + * use MLIR's printer at all -- it prints each element as a character (`100` + * prints as `d`) -- so it is ours, reading the bytes signed like a scalar + * `i8`. All of them print the header line and the brackets, spaces and commas + * of MemRefDataPrinter in MemRefUtils.h, so the text does not depend on which + * printer a type chose. + */ + +typedef struct { + void *allocated; + void *aligned; + int64_t offset; + int64_t sizes_and_strides[]; +} VxRankedMemRef; + +static void vx_print_spaces(int64_t count) { + for (int64_t i = 0; i < count; ++i) + putchar(' '); +} + +/* The compiler sends only the element kinds that vx_print_element prints, so + * any other kind is a compiler bug. The program stops in every build: an + * `assert` is compiled out when NDEBUG is set, and the tensor would then print + * wrong values or none. */ +_Noreturn static void vx_no_element_printer(int bytes, int is_signed) { + fprintf(stderr, "[Vx] FATAL: no printer for a %d-byte %s tensor element\n", + bytes, is_signed ? "signed" : "unsigned"); + abort(); +} + +/* `bytes` is the element size. The signed branch is only for `i8`: MLIR prints + * `i16` itself, and the wide signed types keep MLIR's own printers. */ +static void vx_print_element(const void *base, int64_t at, int bytes, + int is_signed) { + if (is_signed) { + if (bytes != 1) + vx_no_element_printer(bytes, is_signed); + printf("%d", (int)((const int8_t *)base)[at]); + return; + } + switch (bytes) { + case 1: + printf("%u", (unsigned)((const uint8_t *)base)[at]); + return; + case 2: + printf("%u", (unsigned)((const uint16_t *)base)[at]); + return; + case 4: + printf("%" PRIu32, ((const uint32_t *)base)[at]); + return; + case 8: + printf("%" PRIu64, ((const uint64_t *)base)[at]); + return; + } + vx_no_element_printer(bytes, is_signed); +} + +static void vx_print_data(const void *base, int bytes, int is_signed, + int64_t dim, int64_t rank, int64_t offset, + const int64_t *sizes, const int64_t *strides) { + if (dim == 0) { + vx_print_element(base, offset, bytes, is_signed); + return; + } + printf("["); + vx_print_data(base, bytes, is_signed, dim - 1, rank, offset, sizes + 1, + strides + 1); + if (sizes[0] <= 1) { + printf("]"); + return; + } + printf(", "); + if (dim > 1) + printf("\n"); + for (int64_t i = 1; i + 1 < sizes[0]; ++i) { + vx_print_spaces(rank - dim + 1); + vx_print_data(base, bytes, is_signed, dim - 1, rank, + offset + i * strides[0], sizes + 1, strides + 1); + printf(", "); + if (dim > 1) + printf("\n"); + } + vx_print_spaces(rank - dim + 1); + vx_print_data(base, bytes, is_signed, dim - 1, rank, + offset + strides[0] * (sizes[0] - 1), sizes + 1, strides + 1); + printf("]"); +} + +static void vx_print_memref(int64_t rank, void *descriptor, int bytes, + int is_signed) { + const VxRankedMemRef *m = (const VxRankedMemRef *)descriptor; + const int64_t *sizes = m->sizes_and_strides; + const int64_t *strides = m->sizes_and_strides + rank; + printf("Unranked Memref base@ = %p rank = %" PRId64 " offset = %" PRId64 + " sizes = [", + m->aligned, rank, m->offset); + for (int64_t i = 0; i < rank; ++i) + printf(i ? ", %" PRId64 : "%" PRId64, sizes[i]); + printf("] strides = ["); + for (int64_t i = 0; i < rank; ++i) + printf(i ? ", %" PRId64 : "%" PRId64, strides[i]); + printf("] data = \n"); + if (rank == 0) + printf("["); + vx_print_data(m->aligned, bytes, is_signed, rank, rank, m->offset, sizes, + strides); + if (rank == 0) + printf("]"); + printf("\n"); + fflush(stdout); +} + +void printMemrefI8(int64_t rank, void *descriptor) { + vx_print_memref(rank, descriptor, 1, 1); +} + +void printMemrefI16(int64_t rank, void *descriptor) { + VxUnrankedMemRef packed = {rank, descriptor}; + _mlir_ciface_printMemrefI16(&packed); +} + +void printMemrefU8(int64_t rank, void *descriptor) { + vx_print_memref(rank, descriptor, 1, 0); +} + +void printMemrefU16(int64_t rank, void *descriptor) { + vx_print_memref(rank, descriptor, 2, 0); +} + +void printMemrefU32(int64_t rank, void *descriptor) { + vx_print_memref(rank, descriptor, 4, 0); +} + +void printMemrefU64(int64_t rank, void *descriptor) { + vx_print_memref(rank, descriptor, 8, 0); +} +``` + +Add a one-line comment above every function that says what it does. Output the whole file, and change nothing else.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/explain1.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/explain1.txt new file mode 100644 index 0000000..3a16598 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/explain1.txt @@ -0,0 +1,153 @@ +<|im_start|>user +`src/suggest.rs`: + +```rust +//===- suggest.rs - Vx Compiler ------------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Provides "did you mean?" suggestions for name resolution errors using +// Levenshtein edit distance. Used by E2001-E2007 diagnostics. +// +//===----------------------------------------------------------------------===// + +/// Compute Levenshtein edit distance between two strings. +pub fn levenshtein(a: &str, b: &str) -> usize { + let a_len = a.len(); + let b_len = b.len(); + + if a_len == 0 { + return b_len; + } + if b_len == 0 { + return a_len; + } + + let mut prev_row: Vec = (0..=b_len).collect(); + let mut curr_row = vec![0; b_len + 1]; + + for (i, a_char) in a.chars().enumerate() { + curr_row[0] = i + 1; + for (j, b_char) in b.chars().enumerate() { + let cost = if a_char == b_char { 0 } else { 1 }; + curr_row[j + 1] = (prev_row[j + 1] + 1) + .min(curr_row[j] + 1) + .min(prev_row[j] + cost); + } + std::mem::swap(&mut prev_row, &mut curr_row); + } + + prev_row[b_len] +} + +/// Find the closest match to `target` from a list of `candidates`. +/// Returns `None` if no candidate is within `max_dist` edits. +pub fn closest_match<'a>(target: &str, candidates: &[&'a str], max_dist: usize) -> Option<&'a str> { + candidates + .iter() + .filter_map(|c| { + let dist = levenshtein(target, c); + if dist > 0 && dist <= max_dist { + Some((*c, dist)) + } else { + None + } + }) + .min_by_key(|(_, d)| *d) + .map(|(c, _)| c) +} + +/// Suggest a correction for a name, using a dynamic max distance based on name length. +/// Short names (1-3 chars) allow 1 edit, medium names (4-7) allow 2, longer allow 3. +pub fn suggest_name<'a>(target: &str, candidates: &[&'a str]) -> Option<&'a str> { + let max_dist = match target.len() { + 0 => return None, + 1..=3 => 1, + 4..=7 => 2, + _ => 3, + }; + closest_match(target, candidates, max_dist) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_levenshtein_identical() { + assert_eq!(levenshtein("hello", "hello"), 0); + } + + #[test] + fn test_levenshtein_empty() { + assert_eq!(levenshtein("", "abc"), 3); + assert_eq!(levenshtein("abc", ""), 3); + assert_eq!(levenshtein("", ""), 0); + } + + #[test] + fn test_levenshtein_one_edit() { + assert_eq!(levenshtein("count", "conut"), 2); // transposition = 2 edits + assert_eq!(levenshtein("count", "counr"), 1); // substitution + assert_eq!(levenshtein("count", "coun"), 1); // deletion + assert_eq!(levenshtein("count", "counts"), 1); // insertion + } + + #[test] + fn test_levenshtein_multiple_edits() { + assert_eq!(levenshtein("kitten", "sitting"), 3); + } + + #[test] + fn test_closest_match_found() { + let candidates = vec!["count", "counter", "amount", "mount"]; + assert_eq!(closest_match("counr", &candidates, 2), Some("count")); + } + + #[test] + fn test_closest_match_too_far() { + let candidates = vec!["apple", "banana", "cherry"]; + assert_eq!(closest_match("xyz", &candidates, 2), None); + } + + #[test] + fn test_closest_match_exact_excluded() { + // Exact matches (distance 0) should be excluded since the name is already correct + let candidates = vec!["count", "counter"]; + assert_eq!(closest_match("count", &candidates, 2), Some("counter")); + } + + #[test] + fn test_suggest_name_short() { + let candidates = vec!["x", "y", "z", "a"]; + // 'b' is distance 1 from all candidates, so one will be returned + assert!(suggest_name("b", &candidates).is_some()); + } + + #[test] + fn test_suggest_name_medium() { + let candidates = vec!["counter", "count", "amount"]; + // 'contr' (len 5) allows max_dist=2; 'count' is dist 2 from 'contr' + let result = suggest_name("contr", &candidates); + assert!(result == Some("count") || result == Some("counter")); + } + + #[test] + fn test_suggest_name_empty() { + let candidates = vec!["x", "y"]; + assert_eq!(suggest_name("", &candidates), None); + } +} +``` + +Explain what this code does, function by function.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/explain2.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/explain2.txt new file mode 100644 index 0000000..c7e5699 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/explain2.txt @@ -0,0 +1,144 @@ +<|im_start|>user +`src/decline.rs`: + +```rust +//===- decline.rs - Vx Compiler --------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Why the flat path gave up on a function. +// +// The flat lowerer declines whatever it cannot lower yet, and the AST path stays the oracle for +// that function. Declining is expected. Declining without saying why is what makes "how much of +// the language does the flat path carry" a reading exercise instead of a query. +// +// A leaf module: both the flattener and the flat emitter produce these, and the corpus sweep +// counts them. +// +//===----------------------------------------------------------------------===// + +use std::fmt; + +/// Why one function did not lower through the flat path. +/// +/// Every variant names something the flat path does not do *yet*. None of them is an error: a +/// declined function compiles through the AST path and produces the same MLIR. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum Decline { + /// An expression the flat lowerer has no case for. Carries the `Expr` variant name. + UnsupportedExpr(&'static str), + + /// A statement the flat lowerer has no case for. Carries the `Statement` variant name. + UnsupportedStmt(&'static str), + + /// A callee with no signature in the registry -- an ambiguous cross-module name dropped from + /// `fn_sigs`, or an unregistered symbol. + UnresolvedCallee(String), + + /// A builtin called with operands the flat path does not lower: the wrong arity, or a tensor + /// whose rank or element type the emitted kernel does not accept. + BuiltinShape { + builtin: &'static str, + why: &'static str, + }, + + /// A value whose lowered type is not the one this construct needs -- indexing something that + /// is not a pointer, taking a field of a nominal the flat path has no layout for. + TypeNotModelled { what: &'static str }, + + /// A construct the flat path lowers only in memory mode, reached in register mode. + NeedsMemoryMode { construct: &'static str }, + + /// Something the flat path does not lower yet that is none of the above. `what` is a short + /// fixed phrase, never a formatted value, so the histogram groups. + Unsupported { what: &'static str }, + + /// A gap in the flat *emitter* that has not been given a phrase of its own yet, naming the + /// source line that produced it. + /// + /// The emitter bails from roughly 190 places, most of which no corpus program has ever + /// reached. Writing a description for each up front would be 190 guesses about which ones + /// matter. Carrying the site instead means the histogram names the exact line to describe, + /// and only the lines something actually reaches get the work. + EmitterGap { site: &'static str }, +} + +impl Decline { + /// A stable key for grouping. Deliberately drops the payload of the variants that carry one: + /// a histogram of "unresolved callee `foo`, unresolved callee `bar`" answers nothing that + /// "unresolved callee x2" does not. + pub fn key(&self) -> &'static str { + match self { + Decline::UnsupportedExpr(_) => "unsupported-expr", + Decline::UnsupportedStmt(_) => "unsupported-stmt", + Decline::UnresolvedCallee(_) => "unresolved-callee", + Decline::BuiltinShape { .. } => "builtin-shape", + Decline::TypeNotModelled { .. } => "type-not-modelled", + Decline::NeedsMemoryMode { .. } => "needs-memory-mode", + Decline::Unsupported { .. } => "unsupported", + Decline::EmitterGap { .. } => "emitter-gap", + } + } + + /// The key plus the one detail that says *which* construct, for a histogram that names the + /// work rather than the category: `unsupported-expr(Closure)`. + pub fn detail_key(&self) -> String { + match self { + Decline::UnsupportedExpr(k) => format!("unsupported-expr({k})"), + Decline::UnsupportedStmt(k) => format!("unsupported-stmt({k})"), + Decline::UnresolvedCallee(_) => "unresolved-callee".to_string(), + Decline::BuiltinShape { builtin, .. } => format!("builtin-shape({builtin})"), + Decline::TypeNotModelled { what } => format!("type-not-modelled({what})"), + Decline::NeedsMemoryMode { construct } => format!("needs-memory-mode({construct})"), + Decline::Unsupported { what } => format!("unsupported({what})"), + Decline::EmitterGap { site } => format!("emitter-gap({site})"), + } + } +} + +impl fmt::Display for Decline { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Decline::UnsupportedExpr(k) => write!(f, "no flat lowering for the {k} expression"), + Decline::UnsupportedStmt(k) => write!(f, "no flat lowering for the {k} statement"), + Decline::UnresolvedCallee(n) => write!(f, "no signature for the callee '{n}'"), + Decline::BuiltinShape { builtin, why } => { + write!(f, "'{builtin}' called with {why}") + } + Decline::TypeNotModelled { what } => write!(f, "{what}"), + Decline::NeedsMemoryMode { construct } => { + write!(f, "{construct} lowers only in memory mode") + } + Decline::Unsupported { what } => write!(f, "no flat lowering for {what}"), + Decline::EmitterGap { site } => write!(f, "an emitter gap at {site}"), + } + } +} + +/// What a lowering step returns: the value, or the reason the flat path gave up. +pub type Lowered = Result; + +/// An emitter bail-out that has no phrase of its own yet, stamped with where it is. +/// +/// A macro rather than a function so `line!()` expands at the bail site. +#[macro_export] +macro_rules! emitter_gap { + () => { + $crate::decline::Decline::EmitterGap { + site: concat!(file!(), ":", line!()), + } + }; +} +``` + +Explain what this code does, function by function.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/explain3.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/explain3.txt new file mode 100644 index 0000000..dd94476 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/explain3.txt @@ -0,0 +1,236 @@ +<|im_start|>user +`src/error.rs`: + +```rust +//===- error.rs - Vx Compiler ----------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines the error handling and diagnostic reporting infrastructure. +// It provides formatting routines to display rich compiler errors with source code +// snippets, line numbers, and colorful annotations to help developers quickly +// identify and resolve syntax or semantic issues. +// +//===----------------------------------------------------------------------===// + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Error(pub String); + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0) + } +} + +/// Render an error with the source line it points at and a caret under the place. `file` is +/// printed before the line and column, as `file:line:column`, when the source came from one. +pub fn format_compiler_error( + source: &str, + file: Option<&str>, + line: usize, + col: usize, + len: usize, + msg: &str, +) -> String { + if line > 0 { + if let Some(src_line) = source.lines().nth(line - 1) { + let mut out = String::with_capacity(msg.len() + src_line.len() * 2 + 64); + use std::fmt::Write; + match file { + Some(file) => { + let _ = writeln!(out, "Error at {}:{}:{}: {}", file, line, col, msg); + } + None => { + let _ = writeln!(out, "Error at {}:{}: {}", line, col, msg); + } + } + + out.push_str(src_line); + out.push('\n'); + + let mut pointer = String::new(); + for (i, c) in src_line.chars().enumerate() { + if i < col - 1 { + if c == '\t' { + pointer.push('\t'); + } else { + pointer.push(' '); + } + } else { + break; + } + } + + // Replace up to 4 trailing spaces with tildes for better visual anchoring + let mut prefix_tildes = 0; + while prefix_tildes < 4 && pointer.ends_with(' ') { + pointer.pop(); + prefix_tildes += 1; + } + for _ in 0..prefix_tildes { + pointer.push('~'); + } + + for _ in 0..len { + pointer.push('^'); + } + pointer.push_str("~~~~"); + out.push_str(&pointer); + out.push('\n'); + return out; + } + } + + // Fallback if line is out of bounds + match file { + Some(file) => format!("Error at {}:{}:{}: {}\n", file, line, col, msg), + None => format!("Error at {}:{}: {}\n", line, col, msg), + } +} + +pub fn format_compiler_warning( + source: &str, + line: usize, + col: usize, + len: usize, + code: Option, + msg: &str, +) -> String { + let code_str = match code { + Some(c) => format!("[{}]", c), + None => String::new(), + }; + + if line > 0 { + if let Some(src_line) = source.lines().nth(line - 1) { + let mut out = String::with_capacity(msg.len() + src_line.len() * 2 + 64); + use std::fmt::Write; + let _ = writeln!(out, "Warning{} at {}:{}: {}", code_str, line, col, msg); + + out.push_str(src_line); + out.push('\n'); + + let mut pointer = String::new(); + for (i, c) in src_line.chars().enumerate() { + if i < col - 1 { + if c == '\t' { + pointer.push('\t'); + } else { + pointer.push(' '); + } + } else { + break; + } + } + + // Replace up to 4 trailing spaces with tildes for better visual anchoring + let mut prefix_tildes = 0; + while prefix_tildes < 4 && pointer.ends_with(' ') { + pointer.pop(); + prefix_tildes += 1; + } + for _ in 0..prefix_tildes { + pointer.push('~'); + } + + for _ in 0..len { + pointer.push('^'); + } + pointer.push_str("~~~~"); + out.push_str(&pointer); + out.push('\n'); + return out; + } + } + + // Fallback if line is out of bounds + format!("Warning{} at {}:{}: {}\n", code_str, line, col, msg) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_format_compiler_error_len_1_with_padding() { + // " + " (col = 5) + let source = " + "; + let formatted = format_compiler_error(source, None, 1, 5, 1, "Expected operand"); + + // Should produce: + // Error at 1:5: Expected operand + // + + // ~~~~^~~~~ + let expected = "Error at 1:5: Expected operand\n + \n~~~~^~~~~\n"; + assert_eq!(formatted, expected); + } + + #[test] + fn test_format_compiler_error_len_1_no_padding() { + // "+ " (col = 1) + let source = "+ "; + let formatted = format_compiler_error(source, None, 1, 1, 1, "Unexpected"); + + // Should produce: + // Error at 1:1: Unexpected + // + + // ^~~~~ + let expected = "Error at 1:1: Unexpected\n+ \n^~~~~\n"; + assert_eq!(formatted, expected); + } + + #[test] + fn test_format_compiler_error_len_4() { + // "asdf" (col = 1) + let source = "asdf"; + let formatted = format_compiler_error(source, None, 1, 1, 4, "Unknown identifier"); + + // Should produce: + // Error at 1:1: Unknown identifier + // asdf + // ^^^^~~~~ + let expected = "Error at 1:1: Unknown identifier\nasdf\n^^^^~~~~\n"; + assert_eq!(formatted, expected); + } + + #[test] + fn test_format_compiler_error_len_4_with_padding() { + // " asdf" (col = 5) - full 4 spaces of padding + let source = " asdf"; + let formatted = format_compiler_error(source, None, 1, 5, 4, "Unknown identifier"); + + // Should produce: + // Error at 1:5: Unknown identifier + // asdf + // ~~~~^^^^~~~~ + let expected = "Error at 1:5: Unknown identifier\n asdf\n~~~~^^^^~~~~\n"; + assert_eq!(formatted, expected); + } + + #[test] + fn test_format_compiler_error_len_4_with_partial_padding() { + // " asdf" (col = 3) - only 2 spaces of padding available to replace + let source = " asdf"; + let formatted = format_compiler_error(source, None, 1, 3, 4, "Unknown identifier"); + + // Should produce: + // Error at 1:3: Unknown identifier + // asdf + // ~~^^^^~~~~ + let expected = "Error at 1:3: Unknown identifier\n asdf\n~~^^^^~~~~\n"; + assert_eq!(formatted, expected); + } +} +``` + +Explain what this code does, function by function.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/write1.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/write1.txt new file mode 100644 index 0000000..a9a637f --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/write1.txt @@ -0,0 +1,8 @@ +<|im_start|>user +Write a Python module with a class LRUCache that has get, put and a capacity, built on OrderedDict. Add pytest tests for it.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/write2.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/write2.txt new file mode 100644 index 0000000..2b5a941 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/write2.txt @@ -0,0 +1,8 @@ +<|im_start|>user +Write a C function `int parse_csv_line(const char *line, char **fields, int max_fields)` that handles quoted fields and doubled quotes inside them. Add a main() that tests it.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/write3.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/write3.txt new file mode 100644 index 0000000..3f4730e --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/llama/write3.txt @@ -0,0 +1,8 @@ +<|im_start|>user +Write a Rust struct RingBuffer with new, push, pop, len, is_empty and an iterator. Add unit tests.<|im_end|> +<|im_start|>assistant + + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/complete1.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/complete1.txt new file mode 100644 index 0000000..14de931 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/complete1.txt @@ -0,0 +1,129 @@ +<|im_start|>user +`src/report.rs`: + +```rust +//===- report.rs - Vx Compiler ---------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// What the memory-algebra analysis found, in the shape a consumer reads it in: resident sets, +// transfer routes and their costs, and counted traffic. +// +// These are the checker's output, not the checker's working state, which is why they live outside +// hir/. --diagnostics-json is a report format, and a report format that imports the type checker's +// internals cannot change without the checker changing too. +// +//===----------------------------------------------------------------------===// + +/// One memory space's working set for a function: the granule-rounded sum of the tiles placed +/// there, against the space's declared capacity. Recorded for *every* placed space, not only +/// those that overflow — an admitted program emits no capacity diagnostic, so this is the only +/// place its resident total appears. Downstream that total is what turns a capacity verdict into +/// an engine's required memory utilization (#285). See [`crate::hir::env::TypeChecker::resident_sets`]. +#[derive(Debug, Clone, PartialEq)] +pub struct ResidentSet { + pub space: crate::syntax::MemorySpace, + /// The device whose copy of the space this is (`Card[1]`), when the space is the memory of a + /// topology with more than one device. Each device has its own copy and its own working set. + pub device: Option, + /// Granule-rounded sum of tiles placed in this space by one function. + pub total_bytes: u64, + pub capacity_bytes: u64, + pub tiles: usize, + /// Whether the space is declared `overcommit` (an overflow is W1028, not E6010). + pub overcommit: bool, +} + +/// A resolved `transfer`: the chain of memory spaces the value actually moves through and the +/// declared cost of each hop. A direct transfer has one hop; a multi-hop route (synthesized when +/// no direct edge exists) has one per staging step. `derived_cost` is the bandwidth-roofline cost +/// when the declarations make it computable, which is what the emitted `vx.transfer` carries. +/// See [`crate::hir::env::TypeChecker::staging_routes`] (#282). +#[derive(Debug, Clone, PartialEq)] +pub struct StagingRoute { + /// The spaces traversed, source first: `[CPU_DRAM, HBM3e, SMEM]`. + pub path: Vec, + /// Per-edge declared cost, one shorter than `path`; `None` for an edge with no declared cost. + pub edge_costs: Vec>, + /// The cost graph's total for the whole route. + pub total_cost: u32, + /// Bandwidth-derived (roofline) cost, when the declarations supply bandwidths. + /// + /// `u64`, not `u32`: a picosecond-resolution time cost overflows `u32` at 4.3 ms, which a + /// multi-gigabyte host transfer exceeds, and a saturated cost would read as a slow transfer + /// rather than a missing one. + pub derived_cost: Option, + /// Bytes this transfer moves, when the shape is statically known. + /// + /// Without it a harvested cost cannot be interpreted: "260064 ps" is not a prediction unless + /// the size it is a cost *of* travels with it, and comparing predicted against measured needs + /// both. `None` for a dynamically-shaped tensor, where no cost is derivable either. + pub bytes: Option, + /// Which cost source produced `derived_cost`. The two are mutually exclusive per edge (E6013), + /// so this names the one that applied rather than a precedence winner — and it is what tells a + /// consumer whether a residual is attributable to a declared link figure or to an inferred + /// containment roofline. + pub cost_source: Option, + /// The unit `derived_cost` is in — cycles, or picoseconds. Carried rather than dropped because + /// one program's routes legitimately mix them: an on-die hop declared `B/cyc` and a host link + /// declared `GB/s` produce costs of different *dimension*, and a harvested prediction that does + /// not say which is not a prediction. (The fleet's `HBM->L2` and `L2->SMEM` are exactly this + /// pair.) + pub derived_unit: Option, + /// Which composition law priced a containment route: `sum` or `bottleneck`. + /// + /// `None` for a link-rate hop, which has one leg and so composes nothing. Carried because the + /// two laws differ by ~2x on a multi-hop walk and a harvested prediction that does not say + /// which one applied cannot be re-scored later -- the same reason `derived_unit` is carried. + pub composition: Option, + /// Bytes moved per space, derived from code (#353). `None` when the movement cannot be + /// counted statically, in which case `traffic_absent_reason` says why -- a guess here would + /// be indistinguishable from a measurement in the record a campaign harvests, which is the + /// same reason `derived_cost` is `None` rather than 0 when no bandwidth is declared. + pub traffic: Option, + /// Why `traffic` is `None`. `None` when traffic is present. + pub traffic_absent_reason: Option, +} + +/// Bytes read and written against one placed buffer by a `spawn` region (#353). +/// +/// Per BUFFER, not just per space, because the amplification this stage exists to show is a +/// fact about a particular tensor: a streamed operand is re-read on every outer iteration +/// while the blocked one is read once. Summed into their shared space they +/// become one number that hides which of them is the problem. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BufferTraffic { + pub buffer: String, + pub space: crate::syntax::MemorySpace, + pub read_bytes: u64, + pub written_bytes: u64, +} + +/// What one `spawn on(...)` region moves, counted from its indexed accesses and the static +/// trip counts of the loops around them (#353). +/// +/// The transfer-hop counts say what it costs to GET a tile to a space. This says what the +/// kernel then does with it, which is where re-reading lives: a tile staged once and read +/// sixteen times is sixteen reads, and no declared edge cost can say so because the movement +/// across the edge happened exactly once. +#[derive(Debug, Clone, PartialEq)] +pub struct SpawnRegionTraffic { + /// The function the `spawn` appears in. + pub function: String, + /// The topology the region runs on, as its display name. + pub topology: String, + /// Aggregate per space, or `None` when the region could not be counted exactly. + pub traffic: Option, + /// Per placed buffer, sorted by name. Empty when `traffic` is `None`. +``` + +This file stops in the middle. Continue it from exactly where it stops. Output only the rest of the file.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/complete2.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/complete2.txt new file mode 100644 index 0000000..24b2590 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/complete2.txt @@ -0,0 +1,145 @@ +<|im_start|>user +`scripts/tools/check_doc_examples.py`: + +```python +#!/usr/bin/env python3 +"""Compile every Vx example in the documentation. + +Documentation drifts silently because nothing executes it. An audit of this repository found the +README's own headline example did not parse, a tutorial teaching a topology syntax that was never +implemented, `grad` documented with the wrong arity, and a grammar production admitting two types +the parser rejects. Every one of those had been correct when written. + +This makes that class of error a build failure. + + python3 scripts/tools/check_doc_examples.py # check everything + python3 scripts/tools/check_doc_examples.py --list # show what would be checked + python3 scripts/tools/check_doc_examples.py README.md # check specific files + +A block is checked when it is fenced ```vx or ```rust, contains a top-level declaration, and is +not skipped by one of the rules below. To exempt a block deliberately, put + + + +on the line before its fence, ideally with a reason. + +Most blocks are only parsed. A block marked + + + +is compiled and run instead, and what it prints must equal the ```text block that follows it +(one short line, such as "It prints:", may come between them). + +The hand-written pages under `www/` are checked as well, through their `
` blocks. The
+landing page carries the most-read Vx code on the site and was the only code on it that nothing
+compiled -- everything in the book is covered because the book is markdown. The same skip comment
+works there, on the line before the `
`.
+
+Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions.
+See LICENSE for license information.
+SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+"""
+
+import html
+import os
+import re
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+FENCE = re.compile(
+    r"(?:\s*\n)?```(vx|rust)\n(.*?)```", re.S
+)
+# The expected output, after at most one short line such as "It prints:".
+OUTPUT = re.compile(r"\s*(?:[^`\n]+\n\s*)?```text\n(.*?)```", re.S)
+
+# The same idea for the hand-written pages: a 
 block, optionally preceded by the skip
+# comment. Their code carries syntax highlighting as  tags, which are stripped before the
+# body is compiled.
+HTML_BLOCK = re.compile(
+    r"(?:()\s*\n?\s*)?
(.*?)
", re.S +) +TAG = re.compile(r"<[^>]+>") + +# A block has to declare something to be a compilable unit. Bare statements are illustrative +# fragments and are left alone. +DECLARES = re.compile(r"^\s*(fn |pub fn |unsafe fn |safe fn |struct |enum |trait |impl |extern |macro_rules!|Memory |Topology )", re.M) + +# Constructs that exist in Rust and not in Vx. Architecture documents embed compiler internals in +# ```rust fences, and those are Rust, not examples of the language. +RUST_ONLY = re.compile( + r"^\s*use\s+\w|#\[|#!\[|\bpub\s+(struct|enum|mod|const|trait)\b|\bcrate::|" + r"&self\b|&mut self\b|\bimpl\s+\w+\s+for\s+\w+\s*\{[^}]*fn\s+\w+\s*\(\s*&|" + # Types and idioms from the standard Rust library that Vx has no equivalent of. The + # architecture documents embed real compiler internals, and these are what give them away. + r"\bArc<|\bRc<|\bWeak<|\bRefCell<|\bMutex<|\bRwLock<|\bBox +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/complete3.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/complete3.txt new file mode 100644 index 0000000..402843f --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/complete3.txt @@ -0,0 +1,135 @@ +<|im_start|>user +`src/session.rs`: + +```rust +//===- session.rs - Vx Compiler --------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines the core compiler session and local worker states. +// It orchestrates the compilation pipeline across multiple threads, managing shared +// diagnostics, module registries, and global state required during the lowering +// of Vx source code to MLIR. +// +//===----------------------------------------------------------------------===// +use crate::bytecode::HirInstruction; +use crate::gid::{TypeId, UnboundedFunctionMetadata}; +use std::sync::Arc; + +// The frozen nominal-type registry (layouts + module indices + cycle-checked). Built once per +// compilation at the Phase 2 freeze point and shared read-only across worker threads. Re-exported +// here so `GlobalSession` and the verifier name it via `session`, but the type lives in `registry`. +pub use crate::registry::ImmutableGlobalRegistry; + +/// Represents the frozen past of the compilation process. +/// It contains everything compiled before the current phase. +/// +/// # Data-Oriented Design (DOD) Constraints +/// This session deliberately separates dynamic compiler metadata into strictly +/// typed, homogeneous arenas rather than using a single polymorphic `Enum` array +/// (e.g., `enum SlowPathData { Function(...), Generics(...) }`). +/// +/// 1. **Cache-Line Density**: `UnboundedFunctionMetadata` is a dense structure of `u64` +/// bitfields. Iterating over it is highly predictable. `Vec`, however, +/// is a heap-allocated fat pointer with variable lengths. Mixing them would introduce +/// unpredictable struct padding and pointer-chasing overhead. +/// 2. **Hardware Prefetching**: By keeping `generics_arena` separate, the CPU's spatial +/// prefetcher can stream through the dense `slow_path_arena` at maximum bandwidth +/// during the critical lifetime subtyping pass, without stalling on scattered `Vec` pointers. +pub struct GlobalSession { + pub epoch: u64, + /// How this compilation forms a generic instantiation's identity. + /// + /// A per-compilation fact, frozen with the rest of the epoch, because that is what it is: two + /// compilations in one process may legitimately want different strategies, and a worker must + /// not be able to observe a choice that belongs to someone else's compile. It lived in a + /// process-global until Vx#381 -- set from `--intern-mode` on one thread and read by every + /// worker from inside the parallel type-check. + pub intern_mode: crate::intern_mode::InternMode, + /// `-fauto-schedule-levels`: an `across` loop on an arch that cannot launch its levels runs + /// as a plain `for` that carries its level, instead of E6032. + pub auto_schedule_levels: bool, + pub registry: Arc, + + /// The dense, homogeneous arena for complex parameter and lifetime evaluation. + /// Accessed heavily during Phase 1 type-checking and borrow checking. + pub slow_path_arena: Arc>, + + /// The heterogeneous arena for structural generic instantiations. + /// Separated to prevent cache fragmentation in the `slow_path_arena`. + pub generics_arena: Arc>, + pub generics_offsets: Arc>, +} + +impl GlobalSession { + /// A session with an *empty* frozen registry — for callers that don't build one (the + /// sequential driver, unit tests). The parallel pipeline uses [`Self::with_registry`]. + pub fn new(epoch: u64) -> Self { + Self::with_registry( + epoch, + ImmutableGlobalRegistry::build_and_validate(Vec::new()) + .expect("an empty registry is always valid"), + ) + } + + /// A session holding the frozen registry built at the Phase 2 freeze point. + pub fn with_registry(epoch: u64, registry: ImmutableGlobalRegistry) -> Self { + Self { + epoch, + intern_mode: crate::intern_mode::InternMode::Deferred, + auto_schedule_levels: false, + registry: Arc::new(registry), + slow_path_arena: Arc::new(Vec::new()), + generics_arena: Arc::new(Vec::new()), + generics_offsets: Arc::new(Vec::new()), + } + } + + /// The same session with a chosen interning strategy. Consuming rather than a setter, because + /// the session is frozen once it is shared: every worker holds an `Arc` of it and reads it by + /// `&`, so it must be settled before it is wrapped. + pub fn in_intern_mode(mut self, mode: crate::intern_mode::InternMode) -> Self { + self.intern_mode = mode; + self + } + + /// The same session with `-fauto-schedule-levels` on or off. + pub fn auto_schedule_levels(mut self, on: bool) -> Self { + self.auto_schedule_levels = on; + self + } +} + +/// Represents the mutable present of a single worker thread during Phase 1. +pub struct LocalWorkerState { + pub global: Arc, + + // Completely lock-free, thread-local mutation + pub local_slow_path_arena: Vec, + pub local_generics_arena: Vec, + pub local_generics_offsets: Vec<(usize, usize)>, + + // The flat arrays replacing the AST + pub local_type_stream: Vec, // array of 256-bit GIDs + pub local_hir_stream: Vec, + + /// Tensor-type side table: `GID -> (element, shape)` for every tensor type this function's stream + /// references. Tensor GIDs are content hashes (not invertible) and tensors are structural (never + /// in the nominal registry), so codegen can't reconstruct a tensor's memref type from the stream + /// alone -- most acutely for `TensorAlloc`. The lowerer records it here as it emits tensor values; + /// the flat codegen consumes it (the tensor analogue of the registry's struct `layouts`). + pub local_tensor_types: Vec<(TypeId, crate::syntax::ElementType, Vec)>, + + /// String side table: the string-literal bytes for each `PrintStr` this function's stream emits, +``` + +This file stops in the middle. Continue it from exactly where it stops. Output only the rest of the file.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/edit1.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/edit1.txt new file mode 100644 index 0000000..d90c707 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/edit1.txt @@ -0,0 +1,182 @@ +<|im_start|>user +`scripts/tools/gen_error_index.py`: + +```python +#!/usr/bin/env python3 +"""Generate the diagnostic index from the compiler's own diagnostic table. + +`src/diagnostic.rs` is the single place every code is declared, each with a doc comment saying +what it means and a section header grouping it. That makes it the only honest source for a +reference: a hand-written index drifts the moment someone adds a code, and 78 of the 113 codes +were undocumented anywhere before this existed. + + python3 scripts/tools/gen_error_index.py # write the index + python3 scripts/tools/gen_error_index.py --check # fail if it is out of date + +Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +See LICENSE for license information. +SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +""" + +import re +import subprocess +import sys +from pathlib import Path + +SOURCE = Path("src/diagnostic.rs") +OUTPUT = Path("www/book/src/error-index.md") + +# The section headers in diagnostic.rs are terse. These say what the stage actually does, so the +# index reads as a guide rather than as a dump of the enum. +SECTION_BLURB = { + "Warnings": "Reported without stopping the compile. A warning means the program is accepted " + "but something in it is probably not what was intended.", + "Parser Errors": "Raised while turning source text into an AST. The program is not " + "syntactically valid Vx.", + "Name Resolution Errors": "Raised when a name cannot be resolved to a declaration, or " + "resolves to something of the wrong kind.", + "Type Errors": "Raised by the type checker. Vx performs no implicit numeric conversion, so " + "many of these are mismatches that a language with coercion would have silently accepted.", + "Borrow/Ownership Errors": "Raised by the borrow checker and the linear-type rules. These " + "rule out use-after-move, aliasing violations and lifetimes that outlive what they point at.", + "Safety Errors": "Raised where an operation needs an `unsafe` context and does not have one.", + "Topology/Hardware Errors": "Raised by the placement and capacity rules — the checks that " + "make Vx different from a single-address-space language. A value in the wrong memory space, " + "a region on the wrong device, a working set that does not fit, or a transfer with no " + "declared route.", + "Tensor/Math Errors": "Raised on tensor shapes and numeric operations, including shape " + "mismatches that are decided at compile time.", + "Contract/Verification Errors": "Raised when a `requires`, `ensures` or `invariant` clause " + "cannot be discharged, or when a seam obligation is left unproven.", +} + +HEADER = """# Diagnostic index + +Every code that the Vx compiler defines, and what it means. Some codes, among them the parser's +`E1xxx` codes, do not appear in the compiler's messages yet +([Vx#3227](https://github.com/vx-lang/Vx/issues/3227)). + +Codes are grouped by the compilation stage that raises them, and the group is readable off the +number: `E1xxx` is the parser, `E3xxx` the type checker, `E6xxx` the placement and capacity rules, +and so on. A `W` prefix is a warning rather than an error. + +> This file is generated from `src/diagnostic.rs` by `scripts/tools/gen_error_index.py`. Edit the +> doc comments on the codes there, not this file. + +Every code below links to its own page, which carries the message the compiler emits and, where +the test suite has one, a program that triggers it. + +""" + + +def parse(source_text): + """Yield (section, code, description) in declaration order.""" + section = None + pending = [] + + for line in source_text.splitlines(): + stripped = line.strip() + + header = re.match(r"//\s*---\s*(.+?)\s*\((?:[EW]\dxxx)\)\s*---", stripped) + if header: + section = header.group(1) + pending = [] + continue + + doc = re.match(r"///\s?(.*)", stripped) + if doc: + pending.append(doc.group(1).strip()) + continue + + code = re.match(r"^([EW][0-9]{4}),$", stripped) + if code: + yield section, code.group(1), " ".join(p for p in pending if p).strip() + pending = [] + continue + + # Anything else (attributes, blank lines, the enum braces) resets the doc buffer only if + # it is a real statement; blank lines inside a doc block are kept. + if stripped and not stripped.startswith("#"): + pending = [] + + +def render(entries): + out = [HEADER] + by_section = {} + for section, code, desc in entries: + by_section.setdefault(section or "Uncategorised", []).append((code, desc)) + + out.append("## Contents\n") + for section in by_section: + anchor = section.lower().replace(" ", "-").replace("/", "") + codes = [c for c, _ in by_section[section]] + out.append(f"- [{section}](#{anchor}) — `{codes[0]}`–`{codes[-1]}` ({len(codes)} codes)") + out.append("") + + for section, items in by_section.items(): + out.append(f"## {section}\n") + blurb = SECTION_BLURB.get(section) + if blurb: + out.append(f"{blurb}\n") + out.append("| Code | Meaning |") + out.append("| --- | --- |") + for code, desc in items: + # Each code also has a page of its own at vxlang.org/errors/, with the message and a + # program that triggers it. Root-relative, so mdBook leaves it alone. + out.append(f"| [`{code}`](/errors/{code}/) | {desc or '—'} |") + out.append("") + + total = sum(len(v) for v in by_section.values()) + out.append("______________________________________________________________________\n") + out.append(f"{total} diagnostics.\n") + return "\n".join(out) + + +def main(): + if not SOURCE.exists(): + print(f"error: {SOURCE} not found; run from the repository root", file=sys.stderr) + return 1 + + entries = list(parse(SOURCE.read_text())) + if not entries: + print("error: no diagnostic codes parsed -- has the table's shape changed?", file=sys.stderr) + return 1 + + rendered = render(entries) + + # Matches the shape mdformat produces, so the generated file needs no follow-up pass. + + try: + rendered = subprocess.run( + ["mdformat", "-"], input=rendered, capture_output=True, text=True, check=True + ).stdout + except (FileNotFoundError, subprocess.CalledProcessError): + pass # mdformat is optional locally; CI has it. + + if "--check" in sys.argv: + current = OUTPUT.read_text() if OUTPUT.exists() else "" + if current != rendered: + print( + f"error: {OUTPUT} is out of date.\n" + f" Run: python3 {Path(__file__).as_posix()}", + file=sys.stderr, + ) + return 1 + print(f"{OUTPUT} is up to date ({len(entries)} diagnostics)") + return 0 + + OUTPUT.write_text(rendered) + print(f"wrote {OUTPUT} ({len(entries)} diagnostics)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) +``` + +Add a type hint to every function parameter and return value. Output the whole file, and change nothing else.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/edit2.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/edit2.txt new file mode 100644 index 0000000..a8d2349 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/edit2.txt @@ -0,0 +1,151 @@ +<|im_start|>user +`src/hash.rs`: + +```rust +//===- hash.rs - Vx Compiler -----------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file provides specialized, stable hashing utilities for the compiler. +// It implements robust hash generation for type IDs, module signatures, and +// anonymous structural types, ensuring consistent symbol mangling and metadata +// serialization across incremental builds. +// +//===----------------------------------------------------------------------===// +/// 64-bit FNV-1a parameters (standard offset basis + prime). FNV is **project-controlled and stable +/// across toolchains** — unlike `FxHasher`/`DefaultHasher`, whose algorithms may change between +/// library/compiler releases. GID word 0/1 are content hashes that must reproduce byte-for-byte +/// across builds and machines (reproducible builds, cross-crate identity), so the algorithm cannot +/// be an unpinned dependency. This mirrors the FNV scheme `arch.rs` already hand-rolls for dispatch +/// ids, for the same reason. See #195. FNV-1a is *not* cryptographic: accidental collisions are +/// negligible but not impossible, so `ImmutableGlobalRegistry::build_and_validate` additionally +/// rejects any two distinct symbols that land on the same GID. +const FNV_OFFSET_BASIS_64: u64 = 0xcbf2_9ce4_8422_2325; +const FNV_PRIME_64: u64 = 0x0000_0100_0000_01b3; + +/// Streaming 64-bit FNV-1a: fold `bytes` into a running `hash` (seeded with the offset basis on the +/// first call, then chained) so multi-field def paths hash deterministically as one stream. +#[inline] +fn fnv1a_64(hash: u64, bytes: &[u8]) -> u64 { + let mut hash = hash; + for b in bytes { + hash ^= *b as u64; + hash = hash.wrapping_mul(FNV_PRIME_64); + } + hash +} + +/// Computes the stable 64-bit content hash (GID word 0) for a given module path. +pub fn compute_module_hash(module_path: &str) -> u64 { + fnv1a_64(FNV_OFFSET_BASIS_64, module_path.as_bytes()) +} + +/// Represents the stable topological path to a definition (struct, enum, closure). +/// This prevents incremental compilation breakage when anonymous types are re-ordered. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum DefPath<'a> { + /// A named, top-level symbol (e.g., `MyStruct`). + Named(&'a str), + /// An anonymous closure or comptime block, defined by its structural layout + /// or its position within a specific parent item, rather than file line number. + Anonymous { + parent_hash: u64, + structural_hash: u64, + }, +} + +impl<'a> DefPath<'a> { + /// Computes the deterministic 64-bit Word 1 for the TypeId (stable FNV-1a; see [`fnv1a_64`]). + pub fn compute_symbol_hash(&self) -> u64 { + match self { + DefPath::Named(name) => { + // 0 is the discriminator for Named. + let h = fnv1a_64(FNV_OFFSET_BASIS_64, &[0u8]); + fnv1a_64(h, name.as_bytes()) + } + DefPath::Anonymous { + parent_hash, + structural_hash, + } => { + // 1 is the discriminator for Anonymous; fold the two u64 fields in a fixed byte + // order so the hash is architecture-independent. + let mut h = fnv1a_64(FNV_OFFSET_BASIS_64, &[1u8]); + h = fnv1a_64(h, &parent_hash.to_le_bytes()); + fnv1a_64(h, &structural_hash.to_le_bytes()) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Pins the exact algorithm + constants (#195). These are FNV-1a-64 golden values computed + /// independently; if the hash ever silently changes (e.g. someone swaps back to a std hasher), + /// every previously emitted GID / serialized metadata would break, and this catches it. + #[test] + fn hash_is_stable_fnv1a_golden_values() { + assert_eq!(compute_module_hash("crate::a"), 0xdbc1_8e8e_2c15_a207); + assert_eq!( + DefPath::Named("Foo").compute_symbol_hash(), + 0xed6f_617e_4534_5949 + ); + } + + /// Empty input hashes to the bare offset basis (the FNV-1a identity) — a sanity anchor on the + /// seeding. + #[test] + fn empty_module_path_is_offset_basis() { + assert_eq!(compute_module_hash(""), FNV_OFFSET_BASIS_64); + } + + #[test] + fn test_named_defpath_stability() { + let path1 = DefPath::Named("MyStruct"); + let path2 = DefPath::Named("MyStruct"); + assert_eq!(path1.compute_symbol_hash(), path2.compute_symbol_hash()); + + let path3 = DefPath::Named("OtherStruct"); + assert_ne!(path1.compute_symbol_hash(), path3.compute_symbol_hash()); + } + + #[test] + fn test_anonymous_defpath_stability() { + let parent = DefPath::Named("ParentFn").compute_symbol_hash(); + + let anon1 = DefPath::Anonymous { + parent_hash: parent, + structural_hash: 0x12345678, + }; + + let anon2 = DefPath::Anonymous { + parent_hash: parent, + structural_hash: 0x12345678, + }; + + assert_eq!(anon1.compute_symbol_hash(), anon2.compute_symbol_hash()); + + let anon_different_structure = DefPath::Anonymous { + parent_hash: parent, + structural_hash: 0x87654321, + }; + + assert_ne!( + anon1.compute_symbol_hash(), + anon_different_structure.compute_symbol_hash() + ); + } +} +``` + +Add a `///` doc comment above every function that has none. Output the whole file, and change nothing else.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/edit3.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/edit3.txt new file mode 100644 index 0000000..6b9b566 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/edit3.txt @@ -0,0 +1,206 @@ +<|im_start|>user +`runtime/vx_mlir_shims.c`: + +```c +/*===- vx_mlir_shims.c - Vx Compiler ------------------------------*- C -*-===*\ +|* *| +|* Part of the Vx Project, under the Apache License v2.0 with LLVM *| +|* Exceptions. *| +|* See LICENSE for license information. *| +|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| +|* *| +\*===----------------------------------------------------------------------===*/ +/* The half-precision memref printers MLIR does not export in the form emitted + * code calls. + * + * `libmlir_runner_utils` exports printMemrefF32, F64, I32 and I64 both plainly + * and packed as `_mlir_ciface_*`, but the half-precision printers ONLY packed + * -- `nm` on MLIR 22 shows `_mlir_ciface_printMemrefBF16` and no plain + * `printMemrefBF16`. Codegen emits the plain call, so a bf16 program could not + * link, run, or emit an object. Its RUN line only emits MLIR, so nothing + * noticed. + * + * `llvm.emit_c_interface` on the declaration does not fix it: MLIR then gives + * the function a body and the ExecutionEngine wants `_mlir_printMemrefBF16` + * instead, which no library exports either. Supplying the plain symbol here is + * what closes it, and it belongs beside the runtime rather than in vx_std_core + * -- the standard library has no MLIR dependency and should not gain one to + * print a tensor. + * + * MLIR's unpacked convention for `memref<*xT>` passes (rank, pointer to the + * ranked descriptor). The packed entry point takes a pointer to exactly that + * pair. + */ + +#include +#include +#include +#include + +typedef struct { + int64_t rank; + void *descriptor; +} VxUnrankedMemRef; + +extern void _mlir_ciface_printMemrefBF16(void *unranked); +extern void _mlir_ciface_printMemrefF16(void *unranked); +extern void _mlir_ciface_printMemrefI8(void *unranked); +extern void _mlir_ciface_printMemrefI16(void *unranked); + +void printMemrefBF16(int64_t rank, void *descriptor) { + VxUnrankedMemRef packed = {rank, descriptor}; + _mlir_ciface_printMemrefBF16(&packed); +} + +void printMemrefF16(int64_t rank, void *descriptor) { + VxUnrankedMemRef packed = {rank, descriptor}; + _mlir_ciface_printMemrefF16(&packed); +} + +/* The integer tensor printers MLIR does not supply in the form codegen calls, + * or prints wrongly. MLIR has no unsigned integer type: a `u32` tensor is a + * memref of `i32`, and MLIR's printMemrefI32 reads 4000000000 as -294967296. + * printMemrefU8/U16/U32/U64 read the elements unsigned. printMemrefI8 cannot + * use MLIR's printer at all -- it prints each element as a character (`100` + * prints as `d`) -- so it is ours, reading the bytes signed like a scalar + * `i8`. All of them print the header line and the brackets, spaces and commas + * of MemRefDataPrinter in MemRefUtils.h, so the text does not depend on which + * printer a type chose. + */ + +typedef struct { + void *allocated; + void *aligned; + int64_t offset; + int64_t sizes_and_strides[]; +} VxRankedMemRef; + +static void vx_print_spaces(int64_t count) { + for (int64_t i = 0; i < count; ++i) + putchar(' '); +} + +/* The compiler sends only the element kinds that vx_print_element prints, so + * any other kind is a compiler bug. The program stops in every build: an + * `assert` is compiled out when NDEBUG is set, and the tensor would then print + * wrong values or none. */ +_Noreturn static void vx_no_element_printer(int bytes, int is_signed) { + fprintf(stderr, "[Vx] FATAL: no printer for a %d-byte %s tensor element\n", + bytes, is_signed ? "signed" : "unsigned"); + abort(); +} + +/* `bytes` is the element size. The signed branch is only for `i8`: MLIR prints + * `i16` itself, and the wide signed types keep MLIR's own printers. */ +static void vx_print_element(const void *base, int64_t at, int bytes, + int is_signed) { + if (is_signed) { + if (bytes != 1) + vx_no_element_printer(bytes, is_signed); + printf("%d", (int)((const int8_t *)base)[at]); + return; + } + switch (bytes) { + case 1: + printf("%u", (unsigned)((const uint8_t *)base)[at]); + return; + case 2: + printf("%u", (unsigned)((const uint16_t *)base)[at]); + return; + case 4: + printf("%" PRIu32, ((const uint32_t *)base)[at]); + return; + case 8: + printf("%" PRIu64, ((const uint64_t *)base)[at]); + return; + } + vx_no_element_printer(bytes, is_signed); +} + +static void vx_print_data(const void *base, int bytes, int is_signed, + int64_t dim, int64_t rank, int64_t offset, + const int64_t *sizes, const int64_t *strides) { + if (dim == 0) { + vx_print_element(base, offset, bytes, is_signed); + return; + } + printf("["); + vx_print_data(base, bytes, is_signed, dim - 1, rank, offset, sizes + 1, + strides + 1); + if (sizes[0] <= 1) { + printf("]"); + return; + } + printf(", "); + if (dim > 1) + printf("\n"); + for (int64_t i = 1; i + 1 < sizes[0]; ++i) { + vx_print_spaces(rank - dim + 1); + vx_print_data(base, bytes, is_signed, dim - 1, rank, + offset + i * strides[0], sizes + 1, strides + 1); + printf(", "); + if (dim > 1) + printf("\n"); + } + vx_print_spaces(rank - dim + 1); + vx_print_data(base, bytes, is_signed, dim - 1, rank, + offset + strides[0] * (sizes[0] - 1), sizes + 1, strides + 1); + printf("]"); +} + +static void vx_print_memref(int64_t rank, void *descriptor, int bytes, + int is_signed) { + const VxRankedMemRef *m = (const VxRankedMemRef *)descriptor; + const int64_t *sizes = m->sizes_and_strides; + const int64_t *strides = m->sizes_and_strides + rank; + printf("Unranked Memref base@ = %p rank = %" PRId64 " offset = %" PRId64 + " sizes = [", + m->aligned, rank, m->offset); + for (int64_t i = 0; i < rank; ++i) + printf(i ? ", %" PRId64 : "%" PRId64, sizes[i]); + printf("] strides = ["); + for (int64_t i = 0; i < rank; ++i) + printf(i ? ", %" PRId64 : "%" PRId64, strides[i]); + printf("] data = \n"); + if (rank == 0) + printf("["); + vx_print_data(m->aligned, bytes, is_signed, rank, rank, m->offset, sizes, + strides); + if (rank == 0) + printf("]"); + printf("\n"); + fflush(stdout); +} + +void printMemrefI8(int64_t rank, void *descriptor) { + vx_print_memref(rank, descriptor, 1, 1); +} + +void printMemrefI16(int64_t rank, void *descriptor) { + VxUnrankedMemRef packed = {rank, descriptor}; + _mlir_ciface_printMemrefI16(&packed); +} + +void printMemrefU8(int64_t rank, void *descriptor) { + vx_print_memref(rank, descriptor, 1, 0); +} + +void printMemrefU16(int64_t rank, void *descriptor) { + vx_print_memref(rank, descriptor, 2, 0); +} + +void printMemrefU32(int64_t rank, void *descriptor) { + vx_print_memref(rank, descriptor, 4, 0); +} + +void printMemrefU64(int64_t rank, void *descriptor) { + vx_print_memref(rank, descriptor, 8, 0); +} +``` + +Add a one-line comment above every function that says what it does. Output the whole file, and change nothing else.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/explain1.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/explain1.txt new file mode 100644 index 0000000..07afd8c --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/explain1.txt @@ -0,0 +1,152 @@ +<|im_start|>user +`src/suggest.rs`: + +```rust +//===- suggest.rs - Vx Compiler ------------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Provides "did you mean?" suggestions for name resolution errors using +// Levenshtein edit distance. Used by E2001-E2007 diagnostics. +// +//===----------------------------------------------------------------------===// + +/// Compute Levenshtein edit distance between two strings. +pub fn levenshtein(a: &str, b: &str) -> usize { + let a_len = a.len(); + let b_len = b.len(); + + if a_len == 0 { + return b_len; + } + if b_len == 0 { + return a_len; + } + + let mut prev_row: Vec = (0..=b_len).collect(); + let mut curr_row = vec![0; b_len + 1]; + + for (i, a_char) in a.chars().enumerate() { + curr_row[0] = i + 1; + for (j, b_char) in b.chars().enumerate() { + let cost = if a_char == b_char { 0 } else { 1 }; + curr_row[j + 1] = (prev_row[j + 1] + 1) + .min(curr_row[j] + 1) + .min(prev_row[j] + cost); + } + std::mem::swap(&mut prev_row, &mut curr_row); + } + + prev_row[b_len] +} + +/// Find the closest match to `target` from a list of `candidates`. +/// Returns `None` if no candidate is within `max_dist` edits. +pub fn closest_match<'a>(target: &str, candidates: &[&'a str], max_dist: usize) -> Option<&'a str> { + candidates + .iter() + .filter_map(|c| { + let dist = levenshtein(target, c); + if dist > 0 && dist <= max_dist { + Some((*c, dist)) + } else { + None + } + }) + .min_by_key(|(_, d)| *d) + .map(|(c, _)| c) +} + +/// Suggest a correction for a name, using a dynamic max distance based on name length. +/// Short names (1-3 chars) allow 1 edit, medium names (4-7) allow 2, longer allow 3. +pub fn suggest_name<'a>(target: &str, candidates: &[&'a str]) -> Option<&'a str> { + let max_dist = match target.len() { + 0 => return None, + 1..=3 => 1, + 4..=7 => 2, + _ => 3, + }; + closest_match(target, candidates, max_dist) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_levenshtein_identical() { + assert_eq!(levenshtein("hello", "hello"), 0); + } + + #[test] + fn test_levenshtein_empty() { + assert_eq!(levenshtein("", "abc"), 3); + assert_eq!(levenshtein("abc", ""), 3); + assert_eq!(levenshtein("", ""), 0); + } + + #[test] + fn test_levenshtein_one_edit() { + assert_eq!(levenshtein("count", "conut"), 2); // transposition = 2 edits + assert_eq!(levenshtein("count", "counr"), 1); // substitution + assert_eq!(levenshtein("count", "coun"), 1); // deletion + assert_eq!(levenshtein("count", "counts"), 1); // insertion + } + + #[test] + fn test_levenshtein_multiple_edits() { + assert_eq!(levenshtein("kitten", "sitting"), 3); + } + + #[test] + fn test_closest_match_found() { + let candidates = vec!["count", "counter", "amount", "mount"]; + assert_eq!(closest_match("counr", &candidates, 2), Some("count")); + } + + #[test] + fn test_closest_match_too_far() { + let candidates = vec!["apple", "banana", "cherry"]; + assert_eq!(closest_match("xyz", &candidates, 2), None); + } + + #[test] + fn test_closest_match_exact_excluded() { + // Exact matches (distance 0) should be excluded since the name is already correct + let candidates = vec!["count", "counter"]; + assert_eq!(closest_match("count", &candidates, 2), Some("counter")); + } + + #[test] + fn test_suggest_name_short() { + let candidates = vec!["x", "y", "z", "a"]; + // 'b' is distance 1 from all candidates, so one will be returned + assert!(suggest_name("b", &candidates).is_some()); + } + + #[test] + fn test_suggest_name_medium() { + let candidates = vec!["counter", "count", "amount"]; + // 'contr' (len 5) allows max_dist=2; 'count' is dist 2 from 'contr' + let result = suggest_name("contr", &candidates); + assert!(result == Some("count") || result == Some("counter")); + } + + #[test] + fn test_suggest_name_empty() { + let candidates = vec!["x", "y"]; + assert_eq!(suggest_name("", &candidates), None); + } +} +``` + +Explain what this code does, function by function.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/explain2.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/explain2.txt new file mode 100644 index 0000000..be0ac30 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/explain2.txt @@ -0,0 +1,143 @@ +<|im_start|>user +`src/decline.rs`: + +```rust +//===- decline.rs - Vx Compiler --------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Why the flat path gave up on a function. +// +// The flat lowerer declines whatever it cannot lower yet, and the AST path stays the oracle for +// that function. Declining is expected. Declining without saying why is what makes "how much of +// the language does the flat path carry" a reading exercise instead of a query. +// +// A leaf module: both the flattener and the flat emitter produce these, and the corpus sweep +// counts them. +// +//===----------------------------------------------------------------------===// + +use std::fmt; + +/// Why one function did not lower through the flat path. +/// +/// Every variant names something the flat path does not do *yet*. None of them is an error: a +/// declined function compiles through the AST path and produces the same MLIR. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum Decline { + /// An expression the flat lowerer has no case for. Carries the `Expr` variant name. + UnsupportedExpr(&'static str), + + /// A statement the flat lowerer has no case for. Carries the `Statement` variant name. + UnsupportedStmt(&'static str), + + /// A callee with no signature in the registry -- an ambiguous cross-module name dropped from + /// `fn_sigs`, or an unregistered symbol. + UnresolvedCallee(String), + + /// A builtin called with operands the flat path does not lower: the wrong arity, or a tensor + /// whose rank or element type the emitted kernel does not accept. + BuiltinShape { + builtin: &'static str, + why: &'static str, + }, + + /// A value whose lowered type is not the one this construct needs -- indexing something that + /// is not a pointer, taking a field of a nominal the flat path has no layout for. + TypeNotModelled { what: &'static str }, + + /// A construct the flat path lowers only in memory mode, reached in register mode. + NeedsMemoryMode { construct: &'static str }, + + /// Something the flat path does not lower yet that is none of the above. `what` is a short + /// fixed phrase, never a formatted value, so the histogram groups. + Unsupported { what: &'static str }, + + /// A gap in the flat *emitter* that has not been given a phrase of its own yet, naming the + /// source line that produced it. + /// + /// The emitter bails from roughly 190 places, most of which no corpus program has ever + /// reached. Writing a description for each up front would be 190 guesses about which ones + /// matter. Carrying the site instead means the histogram names the exact line to describe, + /// and only the lines something actually reaches get the work. + EmitterGap { site: &'static str }, +} + +impl Decline { + /// A stable key for grouping. Deliberately drops the payload of the variants that carry one: + /// a histogram of "unresolved callee `foo`, unresolved callee `bar`" answers nothing that + /// "unresolved callee x2" does not. + pub fn key(&self) -> &'static str { + match self { + Decline::UnsupportedExpr(_) => "unsupported-expr", + Decline::UnsupportedStmt(_) => "unsupported-stmt", + Decline::UnresolvedCallee(_) => "unresolved-callee", + Decline::BuiltinShape { .. } => "builtin-shape", + Decline::TypeNotModelled { .. } => "type-not-modelled", + Decline::NeedsMemoryMode { .. } => "needs-memory-mode", + Decline::Unsupported { .. } => "unsupported", + Decline::EmitterGap { .. } => "emitter-gap", + } + } + + /// The key plus the one detail that says *which* construct, for a histogram that names the + /// work rather than the category: `unsupported-expr(Closure)`. + pub fn detail_key(&self) -> String { + match self { + Decline::UnsupportedExpr(k) => format!("unsupported-expr({k})"), + Decline::UnsupportedStmt(k) => format!("unsupported-stmt({k})"), + Decline::UnresolvedCallee(_) => "unresolved-callee".to_string(), + Decline::BuiltinShape { builtin, .. } => format!("builtin-shape({builtin})"), + Decline::TypeNotModelled { what } => format!("type-not-modelled({what})"), + Decline::NeedsMemoryMode { construct } => format!("needs-memory-mode({construct})"), + Decline::Unsupported { what } => format!("unsupported({what})"), + Decline::EmitterGap { site } => format!("emitter-gap({site})"), + } + } +} + +impl fmt::Display for Decline { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Decline::UnsupportedExpr(k) => write!(f, "no flat lowering for the {k} expression"), + Decline::UnsupportedStmt(k) => write!(f, "no flat lowering for the {k} statement"), + Decline::UnresolvedCallee(n) => write!(f, "no signature for the callee '{n}'"), + Decline::BuiltinShape { builtin, why } => { + write!(f, "'{builtin}' called with {why}") + } + Decline::TypeNotModelled { what } => write!(f, "{what}"), + Decline::NeedsMemoryMode { construct } => { + write!(f, "{construct} lowers only in memory mode") + } + Decline::Unsupported { what } => write!(f, "no flat lowering for {what}"), + Decline::EmitterGap { site } => write!(f, "an emitter gap at {site}"), + } + } +} + +/// What a lowering step returns: the value, or the reason the flat path gave up. +pub type Lowered = Result; + +/// An emitter bail-out that has no phrase of its own yet, stamped with where it is. +/// +/// A macro rather than a function so `line!()` expands at the bail site. +#[macro_export] +macro_rules! emitter_gap { + () => { + $crate::decline::Decline::EmitterGap { + site: concat!(file!(), ":", line!()), + } + }; +} +``` + +Explain what this code does, function by function.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/explain3.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/explain3.txt new file mode 100644 index 0000000..f08793b --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/explain3.txt @@ -0,0 +1,235 @@ +<|im_start|>user +`src/error.rs`: + +```rust +//===- error.rs - Vx Compiler ----------------------------------*- Rust -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines the error handling and diagnostic reporting infrastructure. +// It provides formatting routines to display rich compiler errors with source code +// snippets, line numbers, and colorful annotations to help developers quickly +// identify and resolve syntax or semantic issues. +// +//===----------------------------------------------------------------------===// + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Error(pub String); + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0) + } +} + +/// Render an error with the source line it points at and a caret under the place. `file` is +/// printed before the line and column, as `file:line:column`, when the source came from one. +pub fn format_compiler_error( + source: &str, + file: Option<&str>, + line: usize, + col: usize, + len: usize, + msg: &str, +) -> String { + if line > 0 { + if let Some(src_line) = source.lines().nth(line - 1) { + let mut out = String::with_capacity(msg.len() + src_line.len() * 2 + 64); + use std::fmt::Write; + match file { + Some(file) => { + let _ = writeln!(out, "Error at {}:{}:{}: {}", file, line, col, msg); + } + None => { + let _ = writeln!(out, "Error at {}:{}: {}", line, col, msg); + } + } + + out.push_str(src_line); + out.push('\n'); + + let mut pointer = String::new(); + for (i, c) in src_line.chars().enumerate() { + if i < col - 1 { + if c == '\t' { + pointer.push('\t'); + } else { + pointer.push(' '); + } + } else { + break; + } + } + + // Replace up to 4 trailing spaces with tildes for better visual anchoring + let mut prefix_tildes = 0; + while prefix_tildes < 4 && pointer.ends_with(' ') { + pointer.pop(); + prefix_tildes += 1; + } + for _ in 0..prefix_tildes { + pointer.push('~'); + } + + for _ in 0..len { + pointer.push('^'); + } + pointer.push_str("~~~~"); + out.push_str(&pointer); + out.push('\n'); + return out; + } + } + + // Fallback if line is out of bounds + match file { + Some(file) => format!("Error at {}:{}:{}: {}\n", file, line, col, msg), + None => format!("Error at {}:{}: {}\n", line, col, msg), + } +} + +pub fn format_compiler_warning( + source: &str, + line: usize, + col: usize, + len: usize, + code: Option, + msg: &str, +) -> String { + let code_str = match code { + Some(c) => format!("[{}]", c), + None => String::new(), + }; + + if line > 0 { + if let Some(src_line) = source.lines().nth(line - 1) { + let mut out = String::with_capacity(msg.len() + src_line.len() * 2 + 64); + use std::fmt::Write; + let _ = writeln!(out, "Warning{} at {}:{}: {}", code_str, line, col, msg); + + out.push_str(src_line); + out.push('\n'); + + let mut pointer = String::new(); + for (i, c) in src_line.chars().enumerate() { + if i < col - 1 { + if c == '\t' { + pointer.push('\t'); + } else { + pointer.push(' '); + } + } else { + break; + } + } + + // Replace up to 4 trailing spaces with tildes for better visual anchoring + let mut prefix_tildes = 0; + while prefix_tildes < 4 && pointer.ends_with(' ') { + pointer.pop(); + prefix_tildes += 1; + } + for _ in 0..prefix_tildes { + pointer.push('~'); + } + + for _ in 0..len { + pointer.push('^'); + } + pointer.push_str("~~~~"); + out.push_str(&pointer); + out.push('\n'); + return out; + } + } + + // Fallback if line is out of bounds + format!("Warning{} at {}:{}: {}\n", code_str, line, col, msg) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_format_compiler_error_len_1_with_padding() { + // " + " (col = 5) + let source = " + "; + let formatted = format_compiler_error(source, None, 1, 5, 1, "Expected operand"); + + // Should produce: + // Error at 1:5: Expected operand + // + + // ~~~~^~~~~ + let expected = "Error at 1:5: Expected operand\n + \n~~~~^~~~~\n"; + assert_eq!(formatted, expected); + } + + #[test] + fn test_format_compiler_error_len_1_no_padding() { + // "+ " (col = 1) + let source = "+ "; + let formatted = format_compiler_error(source, None, 1, 1, 1, "Unexpected"); + + // Should produce: + // Error at 1:1: Unexpected + // + + // ^~~~~ + let expected = "Error at 1:1: Unexpected\n+ \n^~~~~\n"; + assert_eq!(formatted, expected); + } + + #[test] + fn test_format_compiler_error_len_4() { + // "asdf" (col = 1) + let source = "asdf"; + let formatted = format_compiler_error(source, None, 1, 1, 4, "Unknown identifier"); + + // Should produce: + // Error at 1:1: Unknown identifier + // asdf + // ^^^^~~~~ + let expected = "Error at 1:1: Unknown identifier\nasdf\n^^^^~~~~\n"; + assert_eq!(formatted, expected); + } + + #[test] + fn test_format_compiler_error_len_4_with_padding() { + // " asdf" (col = 5) - full 4 spaces of padding + let source = " asdf"; + let formatted = format_compiler_error(source, None, 1, 5, 4, "Unknown identifier"); + + // Should produce: + // Error at 1:5: Unknown identifier + // asdf + // ~~~~^^^^~~~~ + let expected = "Error at 1:5: Unknown identifier\n asdf\n~~~~^^^^~~~~\n"; + assert_eq!(formatted, expected); + } + + #[test] + fn test_format_compiler_error_len_4_with_partial_padding() { + // " asdf" (col = 3) - only 2 spaces of padding available to replace + let source = " asdf"; + let formatted = format_compiler_error(source, None, 1, 3, 4, "Unknown identifier"); + + // Should produce: + // Error at 1:3: Unknown identifier + // asdf + // ~~^^^^~~~~ + let expected = "Error at 1:3: Unknown identifier\n asdf\n~~^^^^~~~~\n"; + assert_eq!(formatted, expected); + } +} +``` + +Explain what this code does, function by function.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/write1.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/write1.txt new file mode 100644 index 0000000..4c6ec5f --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/write1.txt @@ -0,0 +1,7 @@ +<|im_start|>user +Write a Python module with a class LRUCache that has get, put and a capacity, built on OrderedDict. Add pytest tests for it.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/write2.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/write2.txt new file mode 100644 index 0000000..ff6783d --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/write2.txt @@ -0,0 +1,7 @@ +<|im_start|>user +Write a C function `int parse_csv_line(const char *line, char **fields, int max_fields)` that handles quoted fields and doubled quotes inside them. Add a main() that tests it.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/write3.txt b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/write3.txt new file mode 100644 index 0000000..4c6caf4 --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/prompts/twelve/vx/write3.txt @@ -0,0 +1,7 @@ +<|im_start|>user +Write a Rust struct RingBuffer with new, push, pop, len, is_empty and an iterator. Add unit tests.<|im_end|> +<|im_start|>assistant + + + + diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/run.sh b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/run.sh new file mode 100755 index 0000000..33933fd --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/run.sh @@ -0,0 +1,251 @@ +#!/bin/bash +# The benchmark of the Qwen3.6 app against llama.cpp on an M4, as docs/benchmarking_policy.md of +# the Vx repository asks. Run it under `caffeinate -dims`, on a Mac with no other work. It writes +# logs/, log.txt and env.txt into OUT. Then `parse.py OUT` writes runs.csv and summary.md. +# +# 1. Flash attention of llama.cpp: on and off at the 2,048-token prompt. The later stages use +# the setting with the faster median. +# 2. llama-bench: pp512, pp2048 and pp8192, and tg128 after 0 to 32,768 tokens, 5 repetitions. +# 3. Table A: 256 generated tokens after 64 to 32,768 prompt tokens. +# 4. Table P: the prompts of 512 to 8,192 tokens, PROMPT_RUNS times in one process. The first +# run includes the first launch of each kernel. The runs after it show the time in a session. +# 5. Table T: the draft lengths, on the 12 tuning prompts, once each. The app tries each length of +# DRAFTS, and llama-speculative-simple with the MTP heads each of MTP_DRAFTS. Table C uses the +# length with the fastest geometric mean. llama-speculative-simple with n-gram drafts +# (ngram-mod and ngram-cache) keeps the settings of llama.cpp: ngram-cache always drafts 8 +# tokens. llama-lookup is not in the benchmark: on this model its text differs from that +# of llama-completion, and its log has errors from llama_decode. +# 6. Table C: the 12 held-out prompts, 512 generated tokens. The programs (C_CASES) are the app, +# the app with --draft DRAFT, the app with --mtp MTP_APP, the app with --mtp MTP_APP and +# --draft DRAFT, llama-completion, and llama-speculative-simple with ngram-mod and with the MTP +# heads (MTP_N tokens). +# +# This copy of the script of docs/benchmarks/2026-11-20-qwen36-m4 adds the app with --mtp. The +# default stages leave out table T: the draft settings come from the tuning prompts (DRAFT, +# MTP_APP: docs/optimizations.md, entries 16 and 19; MTP_N: table T of the 2026-11-20 run, with the +# same build of llama.cpp). Table C leaves out ngram-cache, which was slower than ngram-mod there. +# +# Each case runs ROUNDS times. Round 2 runs the programs in the reverse order. Before each run, the +# script waits until no other process uses more than 20% of a CPU and the GPU is idle, and then +# waits COOL seconds more. A run takes about 1 to 3 minutes. Each run of the app first compiles the +# app, for about 1.5 minutes. The default stages take about 12 hours. +# Build llama.cpp from its commit b1b770d with llama-timing.patch. Without the patch, +# llama-speculative-simple stops the clock of the prompt before the GPU ends the prompt, and counts +# the rest of the prompt in the time of the generated tokens. +# STAGES selects the stages: fa, bench, A, P, T and C. Without the stage fa, give FA=on or FA=off. +# Without the stage T, give DRAFT and MTP_N. A short test can also set CONTEXTS, +# P_CONTEXTS, PROMPTS, A_TOKENS, TOKENS and the lists of draft lengths. The report uses the defaults. +# RERUN="NAME..." runs only the runs with these names, with the same OUT, for example the runs that +# another job on the Mac overlapped. Move their old logs away first. parse.py takes the last line of +# log.txt for each name. +set -u +HERE=$(cd "$(dirname "$0")" && pwd) +OUT=${OUT:-$HERE/out} +ROUNDS=${ROUNDS:-3} +COOL=${COOL:-30} +STAGES=${STAGES:-fa bench A P C} +DRAFT=${DRAFT:-11} +MTP_N=${MTP_N:-3} +MTP_APP=${MTP_APP:-3,5} +C_CASES=${C_CASES:-vx vxdraft vxmtp vxmtpdraft completion ngram mtp} +RERUN=${RERUN:-} +DRAFTS=${DRAFTS:-3 5 7 9 11 15} +MTP_DRAFTS=${MTP_DRAFTS:-1 2 3 4 6} +PROMPT_RUNS=${PROMPT_RUNS:-3} +CONTEXTS=${CONTEXTS:-64 512 2048 8192 16384 32768} +P_CONTEXTS=${P_CONTEXTS:-512 2048 8192} +PROMPTS=${PROMPTS:-edit1 complete1 write1 explain1 edit2 complete2 write2 explain2 edit3 complete3 write3 explain3} +A_TOKENS=${A_TOKENS:-256} +TOKENS=${TOKENS:-512} +VXC=${VXC:?the release vxc} +FLEET=${FLEET:?the fleet/ folder of that vxc} +QV=${QV:-$(cd "$HERE/../../.." && pwd)} +VXW=${VXW:?the weight file of the app} +VXT=${VXT:?the tokenizer file of the app} +GGUF=${GGUF:?the GGUF file} +MTP=${MTP:?the GGUF file of the MTP heads} +LB=${LB:?the bin/ folder of llama.cpp} +LLAMA_SRC=${LLAMA_SRC:-$LB/../..} +P=$HERE/prompts +want() { [[ " $STAGES " == *" $1 "* ]]; } +mkdir -p "$OUT/logs" +cd "$OUT" || exit 1 + +gpu_busy() { # the Device Utilization % of the GPU + ioreg -r -d 1 -c IOAccelerator | grep -o '"Device Utilization %"=[0-9]*' | head -1 | cut -d= -f2 +} +others_busy() { # another process uses more than 20% of a CPU, or the GPU is busy + ps -Ao %cpu,comm -r | awk 'NR>1 && $2 !~ /claude|Terminal|WindowServer|kernel_task/ && $1 > 20 {found=1} END {exit !found}' \ + || [ "$(gpu_busy)" -gt 5 ] +} +# Waits until the machine is quiet, then COOL seconds, and checks again after them. A process that +# starts in the COOL seconds starts the wait again. +quiet() { + while true; do + while others_busy; do + sleep 10 + done + sleep "$COOL" + others_busy || return 0 + done +} +busy() { ps -Ao %cpu,comm -r | awk 'NR>1 && $2 !~ /claude|Terminal/ {printf "%s %s", $1, $2; exit}' | sed 's|.*/||'; } + +# Each program prints its whole command line first, so that the log has it. +show() { + echo "command: $*" + "$@" +} +vx() { # PROMPT STEPS [options] + local f=$1 n=$2 + shift 2 + show "$VXC" -O2 "$QV/src/main.vx" --package qwen="$QV/src" --host default --machine "$FLEET/m4-uma.vx" -- \ + "$VXW" --tokenizer "$VXT" --prompt-file "$f" --steps "$n" --ignore-eos "$@" +} +llama() { # TOOL PROMPT N CTX [options] + local tool=$1 f=$2 n=$3 c=$4 + shift 4 + show "$LB/$tool" -m "$GGUF" -f "$f" -n "$n" -c "$c" --temp 0 -ngl 99 -fa "$FA" --no-escape --ignore-eos "$@" +} +completion() { llama llama-completion "$@" -no-cnv; } +# llama-speculative-simple refuses a prompt longer than the batch (-b, 2,048 by default). The +# longest prompt has 2,251 tokens. +spec() { llama llama-speculative-simple "$@" -b 4096; } + +run() { # NAME COMMAND...: one run, its output in logs/NAME.txt, a line in log.txt + local name=$1 + shift + if [ -n "$RERUN" ] && [[ " $RERUN " != *" $name "* ]]; then return; fi + quiet + local b g t0 + b=$(busy) + g=$(gpu_busy) + t0=$(date +%Y-%m-%dT%H:%M:%S) + "$@" > "logs/$name.txt" 2>&1 + local rc=$? + echo "$name start=$t0 end=$(date +%Y-%m-%dT%H:%M:%S) rc=$rc busy=[$b] gpu=$g%" | tee -a log.txt +} + +{ + echo "date: $(date), stages: $STAGES" + echo "machine: $(sysctl -n hw.model), $(sysctl -n machdep.cpu.brand_string), $(($(sysctl -n hw.memsize) / 1073741824)) GB" + system_profiler SPDisplaysDataType 2> /dev/null | grep -E "Chipset Model|Total Number of Cores|Metal Support" + echo "macOS: $(sw_vers -productVersion) ($(sw_vers -buildVersion))" + echo "power: $(pmset -g batt | head -1)" + echo "vxc: $("$VXC" --version 2>&1)" + echo "qwen-vx: $(git -C "$QV" log -1 --format='%H %s'), changed files: $(git -C "$QV" status --short -- src | wc -l | tr -d ' ')" + echo "llama.cpp: $("$LB/llama-completion" --version 2>&1 | tr '\n' ' ')" + echo "llama.cpp source: $(git -C "$LLAMA_SRC" log -1 --format=%H), changes: $(git -C "$LLAMA_SRC" diff --stat | tail -1)" + git -C "$LLAMA_SRC" diff > llama.cpp.diff + echo "GGUF: $GGUF $(stat -f %z "$GGUF") bytes" + echo "MTP GGUF: $MTP $(stat -f %z "$MTP") bytes" + echo "app weights: $VXW $(stat -f %z "$VXW") bytes" + echo "app tokenizer: $VXT $(stat -f %z "$VXT") bytes" + echo "rounds: $ROUNDS, cool: $COOL s, prompt runs: $PROMPT_RUNS" + echo "contexts: $CONTEXTS, prompt contexts: $P_CONTEXTS, generated tokens: $A_TOKENS and $TOKENS" + echo "prompts: $PROMPTS" + want T && echo "draft lengths tried: app $DRAFTS, MTP $MTP_DRAFTS" + echo "table C: $C_CASES; app --draft $DRAFT, app --mtp $MTP_APP, llama.cpp draft-mtp $MTP_N" + [ -n "$RERUN" ] && echo "rerun: $RERUN" +} >> env.txt + +# The order of the programs in round r: as given in odd rounds, reversed in even rounds. +order() { # R NAME... + local r=$1 + shift + if [ $((r % 2)) = 1 ]; then echo "$@"; else echo "$@" | tr ' ' '\n' | tail -r | tr '\n' ' '; fi +} + +# 1. Flash attention of llama.cpp +if want fa; then + for r in $(seq 1 "$ROUNDS"); do + for fa in $(order "$r" on off); do + FA=$fa run "fa-$fa.ctx2048.r$r" completion "$P/context/llama/ctx2048.txt" 256 4096 + done + done + ms() { grep 'common_perf_print: *eval time' "$1" | sed -E 's/.*\( *([0-9.]+) ms per token.*/\1/'; } + med() { sort -n | awk '{a[NR]=$1} END {print a[int((NR+1)/2)]}'; } + on=$(for f in logs/fa-on.ctx2048.r*.txt; do ms "$f"; done | med) + off=$(for f in logs/fa-off.ctx2048.r*.txt; do ms "$f"; done | med) + FA=$(awk -v a="$on" -v b="$off" 'BEGIN {print (a <= b) ? "on" : "off"}') + echo "flash attention: on $on ms, off $off ms (medians at 2,048 tokens); chosen: $FA" | tee -a log.txt env.txt +fi +FA=${FA:?give FA=on or FA=off, or run the stage fa} +want fa || echo "flash attention: given by FA; chosen: $FA" | tee -a log.txt env.txt + +# 2. llama-bench +want bench && run llama-bench-pp show "$LB/llama-bench" -m "$GGUF" -p 512,2048,8192 -n 0 -r 5 -ngl 99 -fa "$FA" -o md +want bench && run llama-bench-tg show "$LB/llama-bench" -m "$GGUF" -p 0 -n 128 -d 0,2048,8192,16384,32768 -r 5 -ngl 99 -fa "$FA" -o md + +# 3. Table A +want A && for r in $(seq 1 "$ROUNDS"); do + for c in $CONTEXTS; do + for tool in $(order "$r" vx llama); do + if [ "$tool" = vx ]; then + run "A.vx.ctx$c.r$r" vx "$P/context/vx/ctx$c.txt" "$A_TOKENS" + else + run "A.llama.ctx$c.r$r" completion "$P/context/llama/ctx$c.txt" "$A_TOKENS" $((c + 512)) + fi + done + done +done + +# 4. Table P +want P && for r in $(seq 1 "$ROUNDS"); do + for c in $P_CONTEXTS; do + for tool in $(order "$r" vx llama); do + if [ "$tool" = vx ]; then + run "P.vx.ctx$c.r$r" vx "$P/context/vx/ctx$c.txt" 1 --prompt-runs "$PROMPT_RUNS" + else + run "P.llama.ctx$c.r$r" completion "$P/context/llama/ctx$c.txt" 1 $((c + 512)) + fi + done + done +done + +# 5. Table T +if want T; then + cases="vx completion ngram cache" + for d in $DRAFTS; do cases="$cases vxdraft$d"; done + for d in $MTP_DRAFTS; do cases="$cases mtp$d"; done + r=0 + for n in $PROMPTS; do + r=$((r + 1)) + for kind in $(order "$r" $cases); do + f=$P/twelve/llama/$n.txt + case $kind in + vx) run "T.$n.r1.vx" vx "$P/twelve/vx/$n.txt" "$TOKENS" ;; + vxdraft*) run "T.$n.r1.$kind" vx "$P/twelve/vx/$n.txt" "$TOKENS" --draft "${kind#vxdraft}" ;; + completion) run "T.$n.r1.completion" completion "$f" "$TOKENS" 8192 ;; + ngram) run "T.$n.r1.ngram" spec "$f" "$TOKENS" 8192 --spec-type ngram-mod ;; + mtp*) run "T.$n.r1.$kind" spec "$f" "$TOKENS" 8192 --spec-type draft-mtp -md "$MTP" -ngld 99 --spec-draft-n-max "${kind#mtp}" ;; + cache) run "T.$n.r1.cache" spec "$f" "$TOKENS" 8192 --spec-type ngram-cache ;; + esac + done + done + choice=$(python3 "$HERE/parse.py" "$OUT" --choose) || exit 1 + eval "$choice" + echo "draft lengths chosen in table T: $choice" | tee -a log.txt env.txt +else + echo "draft lengths given: DRAFT=${DRAFT:?} MTP_N=${MTP_N:?}" | tee -a log.txt env.txt +fi + +# 6. Table C +want C && for r in $(seq 1 "$ROUNDS"); do + for n in $PROMPTS; do + f=$P/heldout/llama/$n.txt + for kind in $(order "$r" $C_CASES); do + case $kind in + vx) run "C.$n.r$r.vx" vx "$P/heldout/vx/$n.txt" "$TOKENS" ;; + vxdraft) run "C.$n.r$r.vxdraft$DRAFT" vx "$P/heldout/vx/$n.txt" "$TOKENS" --draft "$DRAFT" ;; + vxmtp) run "C.$n.r$r.vxmtp" vx "$P/heldout/vx/$n.txt" "$TOKENS" --mtp "$MTP_APP" ;; + vxmtpdraft) run "C.$n.r$r.vxmtpdraft$DRAFT" vx "$P/heldout/vx/$n.txt" "$TOKENS" --mtp "$MTP_APP" --draft "$DRAFT" ;; + completion) run "C.$n.r$r.completion" completion "$f" "$TOKENS" 8192 ;; + cache) run "C.$n.r$r.cache" spec "$f" "$TOKENS" 8192 --spec-type ngram-cache ;; + ngram) run "C.$n.r$r.ngram" spec "$f" "$TOKENS" 8192 --spec-type ngram-mod ;; + mtp) run "C.$n.r$r.mtp$MTP_N" spec "$f" "$TOKENS" 8192 --spec-type draft-mtp -md "$MTP" -ngld 99 --spec-draft-n-max "$MTP_N" ;; + esac + done + done +done +echo "done $(date +%Y-%m-%dT%H:%M:%S)" | tee -a log.txt diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/runs.csv b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/runs.csv new file mode 100644 index 0000000..422822f --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/runs.csv @@ -0,0 +1,313 @@ +table,prompt,kind,round,program,setting,prompt_tokens,llama_prompt_tokens,prompt_ms,first_prompt_ms,later_prompt_ms,ms_per_token,timed_tokens,checks,drafted,accepted,flash_attn,threads,errors,log,start,end,rc,busy,gpu,same_text,same_chars +A,context/ctx16384,ctx,1,llama-completion,,16384,16384,54128.2800,,,32.2700,255,,,,on,4,0,logs/A.llama.ctx16384.r1.txt,2026-11-25T10:28:38,2026-11-25T10:29:51,0,bash,0,, +A,context/ctx16384,ctx,2,llama-completion,,16384,16384,53658.8400,,,32.3100,255,,,,on,4,0,logs/A.llama.ctx16384.r2.txt,2026-11-25T10:55:11,2026-11-25T10:56:23,0,bash,0,, +A,context/ctx16384,ctx,3,llama-completion,,16384,16384,54465.3100,,,32.2600,255,,,,on,4,0,logs/A.llama.ctx16384.r3.txt,2026-11-25T11:28:22,2026-11-25T11:29:34,0,launchd,0,, +A,context/ctx2048,ctx,1,llama-completion,,2048,2048,5062.4000,,,26.2600,255,,,,on,4,0,logs/A.llama.ctx2048.r1.txt,2026-11-25T10:19:53,2026-11-25T10:20:14,0,bash,0,, +A,context/ctx2048,ctx,2,llama-completion,,2048,2048,5066.1200,,,26.2600,255,,,,on,4,0,logs/A.llama.ctx2048.r2.txt,2026-11-25T10:46:50,2026-11-25T10:47:11,0,3.7 agy,0,, +A,context/ctx2048,ctx,3,llama-completion,,2048,2048,5067.6400,,,26.2800,255,,,,on,4,0,logs/A.llama.ctx2048.r3.txt,2026-11-25T11:19:17,2026-11-25T11:19:38,0,com.apple.AppleUserHIDDrivers,0,, +A,context/ctx32768,ctx,1,llama-completion,,32768,32768,161093.5400,,,58.0000,255,,,,on,4,0,logs/A.llama.ctx32768.r1.txt,2026-11-25T10:35:59,2026-11-25T10:39:05,0,bash,0,, +A,context/ctx32768,ctx,2,llama-completion,,32768,32768,163903.0300,,,58.9000,255,,,,on,4,0,logs/A.llama.ctx32768.r2.txt,2026-11-25T11:00:30,2026-11-25T11:03:38,0,networkserviceproxy,0,, +A,context/ctx32768,ctx,3,llama-completion,,32768,32768,149761.3000,,,65.1000,255,,,,on,4,0,logs/A.llama.ctx32768.r3.txt,2026-11-25T11:35:32,2026-11-25T11:38:29,0,0.9 agy,0,, +A,context/ctx512,ctx,1,llama-completion,,512,512,1216.4400,,,25.8200,255,,,,on,4,0,logs/A.llama.ctx512.r1.txt,2026-11-25T10:16:10,2026-11-25T10:16:27,0,contextstored,0,, +A,context/ctx512,ctx,2,llama-completion,,512,512,1219.4000,,,26.0300,255,,,,on,4,0,logs/A.llama.ctx512.r2.txt,2026-11-25T10:43:12,2026-11-25T10:43:30,0,airportd,0,, +A,context/ctx512,ctx,3,llama-completion,,512,512,1218.9700,,,26.4900,255,,,,on,4,0,logs/A.llama.ctx512.r3.txt,2026-11-25T11:15:46,2026-11-25T11:16:04,0,com.apple.AppleUserHIDDrivers,0,, +A,context/ctx64,ctx,1,llama-completion,,64,64,251.5100,,,25.6700,255,,,,on,4,0,logs/A.llama.ctx64.r1.txt,2026-11-25T10:12:32,2026-11-25T10:12:49,0,AXVisualSupportAgent,0,, +A,context/ctx64,ctx,2,llama-completion,,64,64,250.2800,,,25.9000,255,,,,on,4,0,logs/A.llama.ctx64.r2.txt,2026-11-25T10:39:45,2026-11-25T10:39:53,0,airportd,0,, +A,context/ctx64,ctx,3,llama-completion,,64,64,251.5200,,,25.8200,255,,,,on,4,0,logs/A.llama.ctx64.r3.txt,2026-11-25T11:12:12,2026-11-25T11:12:29,0,xprotectd,0,, +A,context/ctx8192,ctx,1,llama-completion,,8192,8192,22708.7100,,,28.0200,255,,,,on,4,0,logs/A.llama.ctx8192.r1.txt,2026-11-25T10:23:52,2026-11-25T10:24:32,0,com.apple.DriverKit-AppleBCMWLAN,0,, +A,context/ctx8192,ctx,2,llama-completion,,8192,8192,22632.3200,,,27.8800,255,,,,on,4,0,logs/A.llama.ctx8192.r2.txt,2026-11-25T10:50:44,2026-11-25T10:51:24,0,com.apple.AppleUserHIDDrivers,0,, +A,context/ctx8192,ctx,3,llama-completion,,8192,8192,22765.6700,,,28.1100,255,,,,on,4,0,logs/A.llama.ctx8192.r3.txt,2026-11-25T11:23:27,2026-11-25T11:24:07,0,distnoted,0,, +A,context/ctx16384,ctx,1,qwen-vx,,16384,,45967.6361,,,26.6003,,,,,,,0,logs/A.vx.ctx16384.r1.txt,2026-11-25T10:25:12,2026-11-25T10:27:58,0,bash,0,, +A,context/ctx16384,ctx,2,qwen-vx,,16384,,46380.3368,,,26.7552,,,,,,,0,logs/A.vx.ctx16384.r2.txt,2026-11-25T10:57:03,2026-11-25T10:59:49,0,bash,0,, +A,context/ctx16384,ctx,3,qwen-vx,,16384,,46196.0106,,,26.5911,,,,,,,0,logs/A.vx.ctx16384.r3.txt,2026-11-25T11:24:47,2026-11-25T11:27:41,0,com.apple.AppleUserHIDDrivers,0,, +A,context/ctx2048,ctx,1,qwen-vx,,2048,,4108.5272,,,22.6163,,,,,,,0,logs/A.vx.ctx2048.r1.txt,2026-11-25T10:17:08,2026-11-25T10:19:12,0,ZoomUpdater,0,, +A,context/ctx2048,ctx,2,qwen-vx,,2048,,4109.4403,,,22.6181,,,,,,,0,logs/A.vx.ctx2048.r2.txt,2026-11-25T10:47:52,2026-11-25T10:50:04,0,launchd,0,, +A,context/ctx2048,ctx,3,qwen-vx,,2048,,4110.9838,,,22.6272,,,,,,,0,logs/A.vx.ctx2048.r3.txt,2026-11-25T11:16:44,2026-11-25T11:18:37,0,com.apple.AppleUserHIDDrivers,0,, +A,context/ctx32768,ctx,1,qwen-vx,,32768,,141011.3831,,,48.6566,,,,,,,0,logs/A.vx.ctx32768.r1.txt,2026-11-25T10:30:41,2026-11-25T10:35:09,0,cfprefsd,0,, +A,context/ctx32768,ctx,2,qwen-vx,,32768,,147674.0570,,,50.4905,,,,,,,0,logs/A.vx.ctx32768.r2.txt,2026-11-25T11:04:19,2026-11-25T11:08:53,0,bash,0,, +A,context/ctx32768,ctx,3,qwen-vx,,32768,,150820.0989,,,51.4064,,,,,,,0,logs/A.vx.ctx32768.r3.txt,2026-11-25T11:30:14,2026-11-25T11:34:52,0,xprotectd,0,, +A,context/ctx512,ctx,1,qwen-vx,,512,,1122.1459,,,22.1971,,,,,,,0,logs/A.vx.ctx512.r1.txt,2026-11-25T10:13:29,2026-11-25T10:15:30,0,mediaanalysisd,0,, +A,context/ctx512,ctx,2,qwen-vx,,512,,1121.1429,,,22.1604,,,,,,,0,logs/A.vx.ctx512.r2.txt,2026-11-25T10:44:10,2026-11-25T10:46:10,0,bash,0,, +A,context/ctx512,ctx,3,qwen-vx,,512,,1122.3640,,,22.2036,,,,,,,0,logs/A.vx.ctx512.r3.txt,2026-11-25T11:13:09,2026-11-25T11:15:06,0,UserEventAgent,0,, +A,context/ctx64,ctx,1,qwen-vx,,64,,262.7456,,,22.0815,,,,,,,0,logs/A.vx.ctx64.r1.txt,2026-11-25T10:09:43,2026-11-25T10:11:52,0,com.apple.AppleUserHIDDrivers,0,, +A,context/ctx64,ctx,2,qwen-vx,,64,,262.0611,,,22.0487,,,,,,,0,logs/A.vx.ctx64.r2.txt,2026-11-25T10:40:33,2026-11-25T10:42:32,0,bash,0,, +A,context/ctx64,ctx,3,qwen-vx,,64,,262.3756,,,22.0265,,,,,,,0,logs/A.vx.ctx64.r3.txt,2026-11-25T11:09:33,2026-11-25T11:11:32,0,com.apple.AppleUserHIDDrivers,0,, +A,context/ctx8192,ctx,1,qwen-vx,,8192,,18890.1138,,,24.1591,,,,,,,0,logs/A.vx.ctx8192.r1.txt,2026-11-25T10:20:54,2026-11-25T10:23:12,0,trustd,0,, +A,context/ctx8192,ctx,2,qwen-vx,,8192,,18989.6679,,,24.1602,,,,,,,0,logs/A.vx.ctx8192.r2.txt,2026-11-25T10:52:04,2026-11-25T10:54:31,0,WindowServer,0,, +A,context/ctx8192,ctx,3,qwen-vx,,8192,,18947.3171,,,24.1139,,,,,,,0,logs/A.vx.ctx8192.r3.txt,2026-11-25T11:20:19,2026-11-25T11:22:47,0,bash,0,, +C,heldout/complete1,complete,1,llama-completion,,1044,1044,2588.2400,,,26.1100,511,,,,on,4,0,logs/C.complete1.r1.completion.txt,2026-11-25T12:41:50,2026-11-25T12:42:16,0,2.1 agy,0,, +C,heldout/complete1,complete,1,llama.cpp draft-mtp,3,1044,1044,2703.0000,,,18.1029,515,,459,362,on,4,0,logs/C.complete1.r1.mtp3.txt,2026-11-25T12:43:54,2026-11-25T12:44:08,0,bash,0,False,1055 +C,heldout/complete1,complete,1,llama.cpp ngram-mod,,1044,1044,2551.0000,,,26.2885,513,,0,0,on,4,0,logs/C.complete1.r1.ngram.txt,2026-11-25T12:42:56,2026-11-25T12:43:13,0,xprotectd,0,True,2085 +C,heldout/complete1,complete,1,qwen-vx,,1044,,2168.9289,,,22.2705,,,,,,,0,logs/C.complete1.r1.vx.txt,2026-11-25T12:30:44,2026-11-25T12:32:51,0,airportd,0,, +C,heldout/complete1,complete,1,qwen-vx --draft,11,1044,,2167.6614,,,21.1836,,161,167,87,,,0,logs/C.complete1.r1.vxdraft11.txt,2026-11-25T12:33:31,2026-11-25T12:35:39,0,0.3 agy,0,True,1982 +C,heldout/complete1,complete,1,qwen-vx --mtp,,1044,,2230.0096,,,16.7782,,240,356,270,,,0,logs/C.complete1.r1.vxmtp.txt,2026-11-25T12:36:19,2026-11-25T12:38:22,0,0.4 agy,0,True,1982 +C,heldout/complete1,complete,1,qwen-vx --mtp --draft,11,1044,,2230.2980,,,16.7714,,240,356,270,,,0,logs/C.complete1.r1.vxmtpdraft11.txt,2026-11-25T12:39:02,2026-11-25T12:41:10,0,loginwindow,0,True,1982 +C,heldout/complete1,complete,2,llama-completion,,1044,1044,2572.6600,,,26.1300,511,,,,on,4,0,logs/C.complete1.r2.completion.txt,2026-11-25T15:24:28,2026-11-25T15:24:45,0,com.apple.AppleUserHIDDrivers,0,, +C,heldout/complete1,complete,2,llama.cpp draft-mtp,3,1044,1044,2722.0000,,,17.1709,515,,459,362,on,4,0,logs/C.complete1.r2.mtp3.txt,2026-11-25T15:22:28,2026-11-25T15:22:50,0,com.apple.AppleUserHIDDrivers,0,False,1055 +C,heldout/complete1,complete,2,llama.cpp ngram-mod,,1044,1044,2551.0000,,,26.9298,513,,0,0,on,4,0,logs/C.complete1.r2.ngram.txt,2026-11-25T15:23:30,2026-11-25T15:23:48,0,com.apple.AppleUserHIDDrivers,0,True,2085 +C,heldout/complete1,complete,2,qwen-vx,,1044,,2169.7886,,,22.2324,,,,,,,0,logs/C.complete1.r2.vx.txt,2026-11-25T15:33:36,2026-11-25T15:35:30,0,com.apple.AppleUserHIDDrivers,0,, +C,heldout/complete1,complete,2,qwen-vx --draft,11,1044,,2170.8639,,,21.1574,,161,167,87,,,0,logs/C.complete1.r2.vxdraft11.txt,2026-11-25T15:30:49,2026-11-25T15:32:56,0,com.apple.AppleUserHIDDrivers,0,True,1982 +C,heldout/complete1,complete,2,qwen-vx --mtp,,1044,,2230.0506,,,16.7627,,240,356,270,,,0,logs/C.complete1.r2.vxmtp.txt,2026-11-25T15:28:09,2026-11-25T15:30:09,0,UserEventAgent,0,True,1982 +C,heldout/complete1,complete,2,qwen-vx --mtp --draft,11,1044,,2230.4785,,,16.7800,,240,356,270,,,0,logs/C.complete1.r2.vxmtpdraft11.txt,2026-11-25T15:25:25,2026-11-25T15:27:29,0,xprotectd,0,True,1982 +C,heldout/complete1,complete,3,llama-completion,,1044,1044,2582.7100,,,26.0300,511,,,,on,4,0,logs/C.complete1.r3.completion.txt,2026-11-25T19:31:27,2026-11-25T19:31:53,0,bash,0,, +C,heldout/complete1,complete,3,llama.cpp draft-mtp,3,1044,1044,2701.0000,,,17.8932,515,,459,362,on,4,0,logs/C.complete1.r3.mtp3.txt,2026-11-25T19:33:31,2026-11-25T19:33:45,0,airportd,0,False,1055 +C,heldout/complete1,complete,3,llama.cpp ngram-mod,,1044,1044,2551.0000,,,26.3333,513,,0,0,on,4,0,logs/C.complete1.r3.ngram.txt,2026-11-25T19:32:33,2026-11-25T19:32:51,0,bash,0,True,2085 +C,heldout/complete1,complete,3,qwen-vx,,1044,,2176.8820,,,22.3297,,,,,,,0,logs/C.complete1.r3.vx.txt,2026-11-25T19:20:27,2026-11-25T19:22:32,0,secd,0,, +C,heldout/complete1,complete,3,qwen-vx --draft,11,1044,,2173.7106,,,21.2105,,161,167,87,,,0,logs/C.complete1.r3.vxdraft11.txt,2026-11-25T19:23:13,2026-11-25T19:25:19,0,WindowServer,0,True,1982 +C,heldout/complete1,complete,3,qwen-vx --mtp,,1044,,2233.4025,,,16.7734,,240,356,270,,,0,logs/C.complete1.r3.vxmtp.txt,2026-11-25T19:25:59,2026-11-25T19:28:02,0,com.apple.AppleUserHIDDrivers,0,True,1982 +C,heldout/complete1,complete,3,qwen-vx --mtp --draft,11,1044,,2236.3639,,,16.8289,,240,356,270,,,0,logs/C.complete1.r3.vxmtpdraft11.txt,2026-11-25T19:28:42,2026-11-25T19:30:47,0,com.apple.AppleUserHIDDrivers,0,True,1982 +C,heldout/complete2,complete,1,llama-completion,,1086,1086,2756.3800,,,26.2700,511,,,,on,4,0,logs/C.complete2.r1.completion.txt,2026-11-25T13:39:26,2026-11-25T13:39:52,0,com.apple.AppleUserHIDDrivers,0,, +C,heldout/complete2,complete,1,llama.cpp draft-mtp,3,1086,1086,2862.0000,,,17.4806,516,,461,362,on,4,0,logs/C.complete2.r1.mtp3.txt,2026-11-25T13:41:30,2026-11-25T13:41:44,0,xprotectd,0,True,1938 +C,heldout/complete2,complete,1,llama.cpp ngram-mod,,1086,1086,2720.0000,,,26.3626,513,,0,0,on,4,0,logs/C.complete2.r1.ngram.txt,2026-11-25T13:40:32,2026-11-25T13:40:50,0,airportd,0,True,1938 +C,heldout/complete2,complete,1,qwen-vx,,1086,,2214.4506,,,22.3701,,,,,,,0,logs/C.complete2.r1.vx.txt,2026-11-25T13:26:36,2026-11-25T13:28:54,0,com.apple.AppleUserHIDDrivers,0,, +C,heldout/complete2,complete,1,qwen-vx --draft,11,1086,,2213.2487,,,21.4173,,92,98,60,,,0,logs/C.complete2.r1.vxdraft11.txt,2026-11-25T13:30:55,2026-11-25T13:32:59,0,1.3 agy,0,True,1934 +C,heldout/complete2,complete,1,qwen-vx --mtp,,1086,,2275.9976,,,15.6653,,204,382,306,,,0,logs/C.complete2.r1.vxmtp.txt,2026-11-25T13:33:39,2026-11-25T13:35:53,0,bash,0,True,1934 +C,heldout/complete2,complete,1,qwen-vx --mtp --draft,11,1086,,2275.6503,,,15.6402,,204,382,306,,,0,logs/C.complete2.r1.vxmtpdraft11.txt,2026-11-25T13:36:33,2026-11-25T13:38:46,0,com.apple.AppleUserHIDDrivers,0,True,1934 +C,heldout/complete2,complete,2,llama-completion,,1086,1086,2735.8500,,,26.0400,511,,,,on,4,0,logs/C.complete2.r2.completion.txt,2026-11-25T16:30:23,2026-11-25T16:30:40,0,com.apple.DriverKit-AppleBCMWLAN,0,, +C,heldout/complete2,complete,2,llama.cpp draft-mtp,3,1086,1086,2875.0000,,,18.0736,516,,461,362,on,4,0,logs/C.complete2.r2.mtp3.txt,2026-11-25T16:28:22,2026-11-25T16:28:45,0,bash,0,True,1938 +C,heldout/complete2,complete,2,llama.cpp ngram-mod,,1086,1086,2717.0000,,,26.3938,513,,0,0,on,4,0,logs/C.complete2.r2.ngram.txt,2026-11-25T16:29:25,2026-11-25T16:29:42,0,com.apple.AppleUserHIDDrivers,0,True,1938 +C,heldout/complete2,complete,2,qwen-vx,,1086,,2216.1660,,,22.3164,,,,,,,0,logs/C.complete2.r2.vx.txt,2026-11-25T16:39:44,2026-11-25T16:42:00,0,bash,0,, +C,heldout/complete2,complete,2,qwen-vx --draft,11,1086,,2219.4591,,,21.3498,,92,98,60,,,0,logs/C.complete2.r2.vxdraft11.txt,2026-11-25T16:36:47,2026-11-25T16:38:54,0,com.apple.AppleUserHIDDrivers,0,True,1934 +C,heldout/complete2,complete,2,qwen-vx --mtp,,1086,,2278.5068,,,15.6769,,204,382,306,,,0,logs/C.complete2.r2.vxmtp.txt,2026-11-25T16:34:05,2026-11-25T16:36:07,0,AXVisualSupportAgent,0,True,1934 +C,heldout/complete2,complete,2,qwen-vx --mtp --draft,11,1086,,2276.0420,,,15.6605,,204,382,306,,,0,logs/C.complete2.r2.vxmtpdraft11.txt,2026-11-25T16:31:20,2026-11-25T16:33:25,0,com.apple.AppleUserHIDDrivers,0,True,1934 +C,heldout/complete2,complete,3,llama-completion,,1086,1086,2758.7400,,,26.0900,511,,,,on,4,0,logs/C.complete2.r3.completion.txt,2026-11-25T20:28:03,2026-11-25T20:28:29,0,WindowServer,0,, +C,heldout/complete2,complete,3,llama.cpp draft-mtp,3,1086,1086,2885.0000,,,17.8140,516,,461,362,on,4,0,logs/C.complete2.r3.mtp3.txt,2026-11-25T20:30:07,2026-11-25T20:30:21,0,WindowServer,0,True,1938 +C,heldout/complete2,complete,3,llama.cpp ngram-mod,,1086,1086,2727.0000,,,26.3899,513,,0,0,on,4,0,logs/C.complete2.r3.ngram.txt,2026-11-25T20:29:09,2026-11-25T20:29:27,0,WindowServer,0,True,1938 +C,heldout/complete2,complete,3,qwen-vx,,1086,,2227.3967,,,22.3669,,,,,,,0,logs/C.complete2.r3.vx.txt,2026-11-25T20:17:05,2026-11-25T20:19:21,0,airportd,0,, +C,heldout/complete2,complete,3,qwen-vx --draft,11,1086,,2220.3779,,,21.4167,,92,98,60,,,0,logs/C.complete2.r3.vxdraft11.txt,2026-11-25T20:20:01,2026-11-25T20:22:06,0,bash,0,True,1934 +C,heldout/complete2,complete,3,qwen-vx --mtp,,1086,,2282.1054,,,15.7109,,204,382,306,,,0,logs/C.complete2.r3.vxmtp.txt,2026-11-25T20:22:47,2026-11-25T20:24:49,0,WindowServer,0,True,1934 +C,heldout/complete2,complete,3,qwen-vx --mtp --draft,11,1086,,2282.5928,,,15.6665,,204,382,306,,,0,logs/C.complete2.r3.vxmtpdraft11.txt,2026-11-25T20:25:29,2026-11-25T20:27:23,0,com.apple.AppleUserHIDDrivers,0,True,1934 +C,heldout/complete3,complete,1,llama-completion,,1288,1288,3228.2200,,,26.1100,511,,,,on,4,0,logs/C.complete3.r1.completion.txt,2026-11-25T14:36:10,2026-11-25T14:36:36,0,com.apple.DriverKit-AppleBCMWLAN,0,, +C,heldout/complete3,complete,1,llama.cpp draft-mtp,3,1288,1288,3366.0000,,,16.5883,515,,428,372,on,4,0,logs/C.complete3.r1.mtp3.txt,2026-11-25T14:38:17,2026-11-25T14:38:30,0,secd,0,False,1395 +C,heldout/complete3,complete,1,llama.cpp ngram-mod,,1288,1288,3197.0000,,,30.2710,513,,41,41,on,4,0,logs/C.complete3.r1.ngram.txt,2026-11-25T14:37:16,2026-11-25T14:37:36,0,bash,0,False,1395 +C,heldout/complete3,complete,1,qwen-vx,,1288,,2655.4687,,,22.3249,,,,,,,0,logs/C.complete3.r1.vx.txt,2026-11-25T14:25:01,2026-11-25T14:27:10,0,loginwindow,0,, +C,heldout/complete3,complete,1,qwen-vx --draft,11,1288,,2656.0371,,,18.3635,,139,334,210,,,0,logs/C.complete3.r1.vxdraft11.txt,2026-11-25T14:27:50,2026-11-25T14:29:55,0,com.apple.DriverKit-AppleBCMWLAN,0,True,1384 +C,heldout/complete3,complete,1,qwen-vx --mtp,,1288,,2730.8335,,,13.9710,,152,418,358,,,0,logs/C.complete3.r1.vxmtp.txt,2026-11-25T14:30:35,2026-11-25T14:32:38,0,PerfPowerServices,0,True,1384 +C,heldout/complete3,complete,1,qwen-vx --mtp --draft,11,1288,,2731.9930,,,13.7800,,133,473,377,,,0,logs/C.complete3.r1.vxmtpdraft11.txt,2026-11-25T14:33:18,2026-11-25T14:35:30,0,bash,0,True,1384 +C,heldout/complete3,complete,2,llama-completion,,1288,1288,3223.5000,,,26.3500,511,,,,on,4,0,logs/C.complete3.r2.completion.txt,2026-11-25T17:51:42,2026-11-25T17:52:00,0,bash,0,, +C,heldout/complete3,complete,2,llama.cpp draft-mtp,3,1288,1288,3381.0000,,,16.4175,515,,428,372,on,4,0,logs/C.complete3.r2.mtp3.txt,2026-11-25T17:49:39,2026-11-25T17:50:02,0,WindowServer,0,False,1395 +C,heldout/complete3,complete,2,llama.cpp ngram-mod,,1288,1288,3197.0000,,,30.2339,513,,41,41,on,4,0,logs/C.complete3.r2.ngram.txt,2026-11-25T17:50:42,2026-11-25T17:51:02,0,com.apple.AppleUserHIDDrivers,0,False,1395 +C,heldout/complete3,complete,2,qwen-vx,,1288,,2664.2659,,,22.3808,,,,,,,0,logs/C.complete3.r2.vx.txt,2026-11-25T18:28:59,2026-11-25T18:31:08,0,com.apple.AppleUserHIDDrivers,0,, +C,heldout/complete3,complete,2,qwen-vx --draft,11,1288,,2651.8629,,,18.4372,,139,334,210,,,0,logs/C.complete3.r2.vxdraft11.txt,2026-11-25T22:44:04,2026-11-25T22:46:20,0,com.apple.AppleUserHIDDrivers,0,True,1384 +C,heldout/complete3,complete,2,qwen-vx --mtp,,1288,,2752.4467,,,14.1535,,152,418,358,,,0,logs/C.complete3.r2.vxmtp.txt,2026-11-25T17:55:11,2026-11-25T17:57:13,0,WindowServer,0,True,1384 +C,heldout/complete3,complete,2,qwen-vx --mtp --draft,11,1288,,2741.7710,,,13.8112,,133,473,377,,,0,logs/C.complete3.r2.vxmtpdraft11.txt,2026-11-25T17:52:40,2026-11-25T17:54:30,0,WindowServer,0,True,1384 +C,heldout/complete3,complete,3,llama-completion,,1288,1288,3234.4800,,,26.0900,511,,,,on,4,0,logs/C.complete3.r3.completion.txt,2026-11-25T21:26:24,2026-11-25T21:26:51,0,WindowServer,0,, +C,heldout/complete3,complete,3,llama.cpp draft-mtp,3,1288,1288,3387.0000,,,16.6913,515,,428,372,on,4,0,logs/C.complete3.r3.mtp3.txt,2026-11-25T21:29:01,2026-11-25T21:29:15,0,WindowServer,0,False,1395 +C,heldout/complete3,complete,3,llama.cpp ngram-mod,,1288,1288,3204.0000,,,30.2963,513,,41,41,on,4,0,logs/C.complete3.r3.ngram.txt,2026-11-25T21:27:31,2026-11-25T21:27:51,0,WindowServer,0,False,1395 +C,heldout/complete3,complete,3,qwen-vx,,1288,,2668.7651,,,22.4049,,,,,,,0,logs/C.complete3.r3.vx.txt,2026-11-25T21:15:03,2026-11-25T21:17:21,0,WindowServer,0,, +C,heldout/complete3,complete,3,qwen-vx --draft,11,1288,,2658.5958,,,18.4348,,139,334,210,,,0,logs/C.complete3.r3.vxdraft11.txt,2026-11-25T21:18:01,2026-11-25T21:20:06,0,com.apple.AppleUserHIDDrivers,0,True,1384 +C,heldout/complete3,complete,3,qwen-vx --mtp,,1288,,2742.7275,,,14.0276,,152,418,358,,,0,logs/C.complete3.r3.vxmtp.txt,2026-11-25T21:20:46,2026-11-25T21:22:49,0,WindowServer,0,True,1384 +C,heldout/complete3,complete,3,qwen-vx --mtp --draft,11,1288,,2739.7311,,,13.8366,,133,473,377,,,0,logs/C.complete3.r3.vxmtpdraft11.txt,2026-11-25T21:23:29,2026-11-25T21:25:44,0,WindowServer,0,True,1384 +C,heldout/edit1,edit,1,llama-completion,,1668,1668,4227.9200,,,26.4600,511,,,,on,4,0,logs/C.edit1.r1.completion.txt,2026-11-25T12:27:05,2026-11-25T12:27:33,0,com.apple.DriverKit-AppleBCMWLAN,0,, +C,heldout/edit1,edit,1,llama.cpp draft-mtp,3,1668,1668,4382.0000,,,15.9574,516,,405,381,on,4,0,logs/C.edit1.r1.mtp3.txt,2026-11-25T12:29:39,2026-11-25T12:29:53,0,airportd,0,True,1768 +C,heldout/edit1,edit,1,llama.cpp ngram-mod,,1668,1668,4163.0000,,,20.2281,513,,233,233,on,4,0,logs/C.edit1.r1.ngram.txt,2026-11-25T12:28:43,2026-11-25T12:28:59,0,bash,0,True,1768 +C,heldout/edit1,edit,1,qwen-vx,,1668,,3412.3409,,,22.4827,,,,,,,0,logs/C.edit1.r1.vx.txt,2026-11-25T12:16:06,2026-11-25T12:18:14,0,bash,0,, +C,heldout/edit1,edit,1,qwen-vx --draft,11,1668,,3407.0940,,,13.8800,,107,404,337,,,0,logs/C.edit1.r1.vxdraft11.txt,2026-11-25T12:18:54,2026-11-25T12:20:59,0,xprotectd,0,True,1768 +C,heldout/edit1,edit,1,qwen-vx --mtp,,1668,,3504.5834,,,13.5390,,134,428,376,,,0,logs/C.edit1.r1.vxmtp.txt,2026-11-25T12:21:39,2026-11-25T12:23:42,0,bash,0,True,1768 +C,heldout/edit1,edit,1,qwen-vx --mtp --draft,11,1668,,3504.3292,,,12.0230,,91,481,419,,,0,logs/C.edit1.r1.vxmtpdraft11.txt,2026-11-25T12:24:22,2026-11-25T12:26:25,0,launchd,0,True,1768 +C,heldout/edit1,edit,2,llama-completion,,1668,1668,4209.7900,,,26.2900,511,,,,on,4,0,logs/C.edit1.r2.completion.txt,2026-11-25T15:09:31,2026-11-25T15:09:50,0,bash,0,, +C,heldout/edit1,edit,2,llama.cpp draft-mtp,3,1668,1668,4404.0000,,,16.2112,516,,405,381,on,4,0,logs/C.edit1.r2.mtp3.txt,2026-11-25T15:07:41,2026-11-25T15:07:55,0,com.apple.DriverKit-AppleBCMWLAN,0,True,1768 +C,heldout/edit1,edit,2,llama.cpp ngram-mod,,1668,1668,4174.0000,,,20.3704,513,,233,233,on,4,0,logs/C.edit1.r2.ngram.txt,2026-11-25T15:08:35,2026-11-25T15:08:51,0,com.apple.AppleUserHIDDrivers,0,True,1768 +C,heldout/edit1,edit,2,qwen-vx,,1668,,3402.2446,,,22.3993,,,,,,,0,logs/C.edit1.r2.vx.txt,2026-11-25T15:19:40,2026-11-25T15:21:48,0,PerfPowerServices,0,, +C,heldout/edit1,edit,2,qwen-vx --draft,11,1668,,3402.7846,,,13.8898,,107,404,337,,,0,logs/C.edit1.r2.vxdraft11.txt,2026-11-25T15:16:56,2026-11-25T15:19:00,0,3.7 agy,0,True,1768 +C,heldout/edit1,edit,2,qwen-vx --mtp,,1668,,3502.7447,,,13.5363,,134,428,376,,,0,logs/C.edit1.r2.vxmtp.txt,2026-11-25T15:13:12,2026-11-25T15:15:26,0,com.apple.DriverKit-AppleBCMWLAN,0,True,1768 +C,heldout/edit1,edit,2,qwen-vx --mtp --draft,11,1668,,3503.9628,,,12.0061,,91,481,419,,,0,logs/C.edit1.r2.vxmtpdraft11.txt,2026-11-25T15:10:30,2026-11-25T15:12:32,0,bash,0,True,1768 +C,heldout/edit1,edit,3,llama-completion,,1668,1668,4228.9700,,,26.2400,511,,,,on,4,0,logs/C.edit1.r3.completion.txt,2026-11-25T19:17:29,2026-11-25T19:17:56,0,com.apple.AppleUserHIDDrivers,0,, +C,heldout/edit1,edit,3,llama.cpp draft-mtp,3,1668,1668,4395.0000,,,15.5368,516,,405,381,on,4,0,logs/C.edit1.r3.mtp3.txt,2026-11-25T19:19:32,2026-11-25T19:19:47,0,bash,0,True,1768 +C,heldout/edit1,edit,3,llama.cpp ngram-mod,,1668,1668,4187.0000,,,20.3528,513,,233,233,on,4,0,logs/C.edit1.r3.ngram.txt,2026-11-25T19:18:36,2026-11-25T19:18:52,0,bash,0,True,1768 +C,heldout/edit1,edit,3,qwen-vx,,1668,,3409.4727,,,22.4536,,,,,,,0,logs/C.edit1.r3.vx.txt,2026-11-25T19:06:24,2026-11-25T19:08:41,0,com.apple.AppleUserHIDDrivers,0,, +C,heldout/edit1,edit,3,qwen-vx --draft,11,1668,,3412.9529,,,13.9119,,107,404,337,,,0,logs/C.edit1.r3.vxdraft11.txt,2026-11-25T19:09:31,2026-11-25T19:11:32,0,WindowServer,0,True,1768 +C,heldout/edit1,edit,3,qwen-vx --mtp,,1668,,3507.8199,,,13.5409,,134,428,376,,,0,logs/C.edit1.r3.vxmtp.txt,2026-11-25T19:12:12,2026-11-25T19:14:16,0,WindowServer,0,True,1768 +C,heldout/edit1,edit,3,qwen-vx --mtp --draft,11,1668,,3507.7875,,,12.0302,,91,481,419,,,0,logs/C.edit1.r3.vxmtpdraft11.txt,2026-11-25T19:14:56,2026-11-25T19:16:48,0,WindowServer,0,True,1768 +C,heldout/edit2,edit,1,llama-completion,,1286,1286,3212.9800,,,26.2900,511,,,,on,4,0,logs/C.edit2.r1.completion.txt,2026-11-25T13:23:47,2026-11-25T13:24:14,0,com.apple.AppleUserHIDDrivers,0,, +C,heldout/edit2,edit,1,llama.cpp draft-mtp,3,1286,1286,3332.0000,,,15.0796,515,,390,385,on,4,0,logs/C.edit2.r1.mtp3.txt,2026-11-25T13:25:43,2026-11-25T13:25:56,0,dasd,0,True,2049 +C,heldout/edit2,edit,1,llama.cpp ngram-mod,,1286,1286,3177.0000,,,6.9081,577,,544,544,on,4,0,logs/C.edit2.r1.ngram.txt,2026-11-25T13:24:54,2026-11-25T13:25:03,0,com.apple.DriverKit-AppleBCMWLAN,0,True,2049 +C,heldout/edit2,edit,1,qwen-vx,,1286,,2651.1338,,,22.3422,,,,,,,0,logs/C.edit2.r1.vx.txt,2026-11-25T13:12:45,2026-11-25T13:14:54,0,com.apple.AppleUserHIDDrivers,0,, +C,heldout/edit2,edit,1,qwen-vx --draft,11,1286,,2650.1749,,,9.0659,,48,462,462,,,0,logs/C.edit2.r1.vxdraft11.txt,2026-11-25T13:15:34,2026-11-25T13:17:35,0,com.apple.AppleUserHIDDrivers,0,True,2049 +C,heldout/edit2,edit,1,qwen-vx --mtp,,1286,,2726.0008,,,12.2403,,109,417,401,,,0,logs/C.edit2.r1.vxmtp.txt,2026-11-25T13:18:15,2026-11-25T13:20:16,0,bash,0,True,2049 +C,heldout/edit2,edit,1,qwen-vx --mtp --draft,11,1286,,2726.2435,,,9.5114,,48,467,462,,,0,logs/C.edit2.r1.vxmtpdraft11.txt,2026-11-25T13:20:56,2026-11-25T13:23:07,0,bash,0,True,2049 +C,heldout/edit2,edit,2,llama-completion,,1286,1286,3190.9000,,,26.5300,511,,,,on,4,0,logs/C.edit2.r2.completion.txt,2026-11-25T16:16:35,2026-11-25T16:16:53,0,com.apple.AppleUserHIDDrivers,0,, +C,heldout/edit2,edit,2,llama.cpp draft-mtp,3,1286,1286,3358.0000,,,15.3903,515,,390,385,on,4,0,logs/C.edit2.r2.mtp3.txt,2026-11-25T16:14:44,2026-11-25T16:15:06,0,xprotectd,0,True,2049 +C,heldout/edit2,edit,2,llama.cpp ngram-mod,,1286,1286,3170.0000,,,7.1421,577,,544,544,on,4,0,logs/C.edit2.r2.ngram.txt,2026-11-25T16:15:46,2026-11-25T16:15:55,0,com.apple.AppleUserHIDDrivers,0,True,2049 +C,heldout/edit2,edit,2,qwen-vx,,1286,,2646.5898,,,22.3142,,,,,,,0,logs/C.edit2.r2.vx.txt,2026-11-25T16:25:37,2026-11-25T16:27:42,0,com.apple.AppleUserHIDDrivers,0,, +C,heldout/edit2,edit,2,qwen-vx --draft,11,1286,,2648.7257,,,9.0513,,48,462,462,,,0,logs/C.edit2.r2.vxdraft11.txt,2026-11-25T16:22:56,2026-11-25T16:24:57,0,bash,0,True,2049 +C,heldout/edit2,edit,2,qwen-vx --mtp,,1286,,2723.2914,,,12.2388,,109,417,401,,,0,logs/C.edit2.r2.vxmtp.txt,2026-11-25T16:20:16,2026-11-25T16:22:16,0,ZoomUpdater,0,True,2049 +C,heldout/edit2,edit,2,qwen-vx --mtp --draft,11,1286,,2723.5990,,,9.4726,,48,467,462,,,0,logs/C.edit2.r2.vxmtpdraft11.txt,2026-11-25T16:17:33,2026-11-25T16:19:36,0,xprotectd,0,True,2049 +C,heldout/edit2,edit,3,llama-completion,,1286,1286,3217.5300,,,26.4200,511,,,,on,4,0,logs/C.edit2.r3.completion.txt,2026-11-25T20:14:17,2026-11-25T20:14:43,0,com.apple.AppleUserHIDDrivers,0,, +C,heldout/edit2,edit,3,llama.cpp draft-mtp,3,1286,1286,3348.0000,,,15.3184,515,,390,385,on,4,0,logs/C.edit2.r3.mtp3.txt,2026-11-25T20:16:12,2026-11-25T20:16:25,0,com.apple.AppleUserHIDDrivers,0,True,2049 +C,heldout/edit2,edit,3,llama.cpp ngram-mod,,1286,1286,3180.0000,,,6.9307,577,,544,544,on,4,0,logs/C.edit2.r3.ngram.txt,2026-11-25T20:15:23,2026-11-25T20:15:32,0,bash,0,True,2049 +C,heldout/edit2,edit,3,qwen-vx,,1286,,2657.9332,,,22.3211,,,,,,,0,logs/C.edit2.r3.vx.txt,2026-11-25T20:03:05,2026-11-25T20:05:21,0,WindowServer,0,, +C,heldout/edit2,edit,3,qwen-vx --draft,11,1286,,2660.9807,,,9.1284,,48,462,462,,,0,logs/C.edit2.r3.vxdraft11.txt,2026-11-25T20:06:02,2026-11-25T20:08:03,0,com.apple.DriverKit-AppleBCMWLAN,0,True,2049 +C,heldout/edit2,edit,3,qwen-vx --mtp,,1286,,2733.3550,,,12.2611,,109,417,401,,,0,logs/C.edit2.r3.vxmtp.txt,2026-11-25T20:08:53,2026-11-25T20:10:55,0,mdworker_shared,0,True,2049 +C,heldout/edit2,edit,3,qwen-vx --mtp --draft,11,1286,,2729.7268,,,9.5413,,48,467,462,,,0,logs/C.edit2.r3.vxmtpdraft11.txt,2026-11-25T20:11:35,2026-11-25T20:13:36,0,WindowServer,0,True,2049 +C,heldout/edit3,edit,1,llama-completion,,1605,1605,4070.3700,,,26.1500,511,,,,on,4,0,logs/C.edit3.r1.completion.txt,2026-11-25T14:21:58,2026-11-25T14:22:26,0,secd,0,, +C,heldout/edit3,edit,1,llama.cpp draft-mtp,3,1605,1605,4240.0000,,,15.6957,516,,398,383,on,4,0,logs/C.edit3.r1.mtp3.txt,2026-11-25T14:23:57,2026-11-25T14:24:11,0,bash,0,True,1909 +C,heldout/edit3,edit,1,llama.cpp ngram-mod,,1605,1605,4026.0000,,,10.6082,513,,422,422,on,4,0,logs/C.edit3.r1.ngram.txt,2026-11-25T14:23:06,2026-11-25T14:23:16,0,com.apple.AppleUserHIDDrivers,0,True,1909 +C,heldout/edit3,edit,1,qwen-vx,,1605,,3278.2621,,,22.3999,,,,,,,0,logs/C.edit3.r1.vx.txt,2026-11-25T14:11:02,2026-11-25T14:13:11,0,loginwindow,0,, +C,heldout/edit3,edit,1,qwen-vx --draft,11,1605,,3277.6890,,,10.5243,,51,437,422,,,0,logs/C.edit3.r1.vxdraft11.txt,2026-11-25T14:13:51,2026-11-25T14:15:53,0,launchd,0,True,1870 +C,heldout/edit3,edit,1,qwen-vx --mtp,,1605,,3371.6421,,,13.0523,,120,430,389,,,0,logs/C.edit3.r1.vxmtp.txt,2026-11-25T14:16:33,2026-11-25T14:18:34,0,com.apple.AppleUserHIDDrivers,0,True,1870 +C,heldout/edit3,edit,1,qwen-vx --mtp --draft,11,1605,,3373.2078,,,10.4564,,65,470,445,,,0,logs/C.edit3.r1.vxmtpdraft11.txt,2026-11-25T14:19:14,2026-11-25T14:21:18,0,0.7 sleep,0,True,1870 +C,heldout/edit3,edit,2,llama-completion,,1605,1605,4038.0100,,,26.3200,511,,,,on,4,0,logs/C.edit3.r2.completion.txt,2026-11-25T22:43:05,2026-11-25T22:43:23,0,mediaanalysisd,0,, +C,heldout/edit3,edit,2,llama.cpp draft-mtp,3,1605,1605,4227.0000,,,15.3101,516,,398,383,on,4,0,logs/C.edit3.r2.mtp3.txt,2026-11-25T22:41:20,2026-11-25T22:41:34,0,com.apple.AppleUserHIDDrivers,0,True,1909 +C,heldout/edit3,edit,2,llama.cpp ngram-mod,,1605,1605,4004.0000,,,10.6121,513,,422,422,on,4,0,logs/C.edit3.r2.ngram.txt,2026-11-25T22:42:14,2026-11-25T22:42:25,0,bash,0,True,1909 +C,heldout/edit3,edit,2,qwen-vx,,1605,,3284.4131,,,22.3932,,,,,,,0,logs/C.edit3.r2.vx.txt,2026-11-25T17:46:40,2026-11-25T17:48:59,0,com.apple.AppleUserHIDDrivers,0,, +C,heldout/edit3,edit,2,qwen-vx --draft,11,1605,,3281.4114,,,10.5544,,51,437,422,,,0,logs/C.edit3.r2.vxdraft11.txt,2026-11-25T17:43:46,2026-11-25T17:46:00,0,bash,0,True,1870 +C,heldout/edit3,edit,2,qwen-vx --mtp,,1605,,3372.4318,,,13.0750,,120,430,389,,,0,logs/C.edit3.r2.vxmtp.txt,2026-11-25T17:40:54,2026-11-25T17:43:05,0,dasd,0,True,1870 +C,heldout/edit3,edit,2,qwen-vx --mtp --draft,11,1605,,3379.4837,,,10.4934,,65,470,445,,,0,logs/C.edit3.r2.vxmtpdraft11.txt,2026-11-25T17:36:59,2026-11-25T17:39:14,0,15.1 agy,0,True,1870 +C,heldout/edit3,edit,3,llama-completion,,1605,1605,4071.9000,,,26.5200,511,,,,on,4,0,logs/C.edit3.r3.completion.txt,2026-11-25T21:12:10,2026-11-25T21:12:37,0,com.apple.DriverKit-AppleBCMWLAN,0,, +C,heldout/edit3,edit,3,llama.cpp draft-mtp,3,1605,1605,4238.0000,,,16.1124,516,,398,383,on,4,0,logs/C.edit3.r3.mtp3.txt,2026-11-25T21:14:08,2026-11-25T21:14:23,0,WindowServer,0,True,1909 +C,heldout/edit3,edit,3,llama.cpp ngram-mod,,1605,1605,4028.0000,,,10.7641,513,,422,422,on,4,0,logs/C.edit3.r3.ngram.txt,2026-11-25T21:13:17,2026-11-25T21:13:28,0,bash,0,True,1909 +C,heldout/edit3,edit,3,qwen-vx,,1605,,3280.9324,,,22.4747,,,,,,,0,logs/C.edit3.r3.vx.txt,2026-11-25T21:00:53,2026-11-25T21:02:59,0,dasd,0,, +C,heldout/edit3,edit,3,qwen-vx --draft,11,1605,,3282.0396,,,10.5480,,51,437,422,,,0,logs/C.edit3.r3.vxdraft11.txt,2026-11-25T21:03:39,2026-11-25T21:05:51,0,com.apple.AppleUserHIDDrivers,0,True,1870 +C,heldout/edit3,edit,3,qwen-vx --mtp,,1605,,3376.5440,,,13.0639,,120,430,389,,,0,logs/C.edit3.r3.vxmtp.txt,2026-11-25T21:06:41,2026-11-25T21:08:46,0,PerfPowerServices,0,True,1870 +C,heldout/edit3,edit,3,qwen-vx --mtp --draft,11,1605,,3375.7653,,,10.4853,,65,470,445,,,0,logs/C.edit3.r3.vxmtpdraft11.txt,2026-11-25T21:09:26,2026-11-25T21:11:29,0,bash,0,True,1870 +C,heldout/explain1,explain,1,llama-completion,,1503,1503,3644.3300,,,26.2100,511,,,,on,4,0,logs/C.explain1.r1.completion.txt,2026-11-25T13:09:43,2026-11-25T13:10:10,0,xprotectd,0,, +C,heldout/explain1,explain,1,llama.cpp draft-mtp,3,1503,1503,3773.0000,,,20.3721,516,,529,339,on,4,0,logs/C.explain1.r1.mtp3.txt,2026-11-25T13:11:49,2026-11-25T13:12:05,0,cfprefsd,0,True,1943 +C,heldout/explain1,explain,1,llama.cpp ngram-mod,,1503,1503,3603.0000,,,26.3996,513,,0,0,on,4,0,logs/C.explain1.r1.ngram.txt,2026-11-25T13:10:50,2026-11-25T13:11:09,0,bash,0,True,1943 +C,heldout/explain1,explain,1,qwen-vx,,1503,,3049.3157,,,22.3532,,,,,,,0,logs/C.explain1.r1.vx.txt,2026-11-25T12:58:30,2026-11-25T13:00:37,0,bash,0,, +C,heldout/explain1,explain,1,qwen-vx --draft,11,1503,,3049.6187,,,21.8011,,96,105,55,,,0,logs/C.explain1.r1.vxdraft11.txt,2026-11-25T13:01:17,2026-11-25T13:03:24,0,com.apple.AppleUserHIDDrivers,0,True,1902 +C,heldout/explain1,explain,1,qwen-vx --mtp,,1503,,3137.5952,,,17.1786,,245,353,264,,,0,logs/C.explain1.r1.vxmtp.txt,2026-11-25T13:04:04,2026-11-25T13:06:09,0,secd,0,True,1902 +C,heldout/explain1,explain,1,qwen-vx --mtp --draft,11,1503,,3138.1412,,,17.2024,,245,353,264,,,0,logs/C.explain1.r1.vxmtpdraft11.txt,2026-11-25T13:06:50,2026-11-25T13:09:03,0,airportd,0,True,1902 +C,heldout/explain1,explain,2,llama-completion,,1503,1503,3613.3400,,,26.3600,511,,,,on,4,0,logs/C.explain1.r2.completion.txt,2026-11-25T16:02:19,2026-11-25T16:02:37,0,bash,0,, +C,heldout/explain1,explain,2,llama.cpp draft-mtp,3,1503,1503,3813.0000,,,20.2558,516,,529,339,on,4,0,logs/C.explain1.r2.mtp3.txt,2026-11-25T15:50:22,2026-11-25T15:50:47,0,launchd,0,True,1943 +C,heldout/explain1,explain,2,llama.cpp ngram-mod,,1503,1503,3581.0000,,,26.5341,513,,0,0,on,4,0,logs/C.explain1.r2.ngram.txt,2026-11-25T16:01:20,2026-11-25T16:01:38,0,xprotectd,0,True,1943 +C,heldout/explain1,explain,2,qwen-vx,,1503,,3047.5409,,,22.3728,,,,,,,0,logs/C.explain1.r2.vx.txt,2026-11-25T16:11:58,2026-11-25T16:14:04,0,com.apple.AppleUserHIDDrivers,0,, +C,heldout/explain1,explain,2,qwen-vx --draft,11,1503,,3045.5558,,,21.7079,,96,105,55,,,0,logs/C.explain1.r2.vxdraft11.txt,2026-11-25T16:08:59,2026-11-25T16:11:18,0,com.apple.AppleUserHIDDrivers,0,True,1902 +C,heldout/explain1,explain,2,qwen-vx --mtp,,1503,,3131.1727,,,17.1932,,245,353,264,,,0,logs/C.explain1.r2.vxmtp.txt,2026-11-25T16:06:14,2026-11-25T16:08:19,0,bash,0,True,1902 +C,heldout/explain1,explain,2,qwen-vx --mtp --draft,11,1503,,3130.3205,,,17.1823,,245,353,264,,,0,logs/C.explain1.r2.vxmtpdraft11.txt,2026-11-25T16:03:17,2026-11-25T16:05:34,0,WindowServer,0,True,1902 +C,heldout/explain1,explain,3,llama-completion,,1503,1503,3663.2800,,,26.2400,511,,,,on,4,0,logs/C.explain1.r3.completion.txt,2026-11-25T20:00:03,2026-11-25T20:00:30,0,WindowServer,0,, +C,heldout/explain1,explain,3,llama.cpp draft-mtp,3,1503,1503,3790.0000,,,20.0911,516,,529,339,on,4,0,logs/C.explain1.r3.mtp3.txt,2026-11-25T20:02:08,2026-11-25T20:02:24,0,WindowServer,0,True,1943 +C,heldout/explain1,explain,3,llama.cpp ngram-mod,,1503,1503,3618.0000,,,26.5302,513,,0,0,on,4,0,logs/C.explain1.r3.ngram.txt,2026-11-25T20:01:10,2026-11-25T20:01:28,0,WindowServer,0,True,1943 +C,heldout/explain1,explain,3,qwen-vx,,1503,,3055.8681,,,22.4812,,,,,,,0,logs/C.explain1.r3.vx.txt,2026-11-25T19:48:37,2026-11-25T19:50:55,0,networkserviceproxy,0,, +C,heldout/explain1,explain,3,qwen-vx --draft,11,1503,,3058.0268,,,21.7976,,96,105,55,,,0,logs/C.explain1.r3.vxdraft11.txt,2026-11-25T19:51:35,2026-11-25T19:53:43,0,WindowServer,0,True,1902 +C,heldout/explain1,explain,3,qwen-vx --mtp,,1503,,3144.3477,,,17.2131,,245,353,264,,,0,logs/C.explain1.r3.vxmtp.txt,2026-11-25T19:54:23,2026-11-25T19:56:28,0,AXVisualSupportAgent,0,True,1902 +C,heldout/explain1,explain,3,qwen-vx --mtp --draft,11,1503,,3151.3653,,,17.2578,,245,353,264,,,0,logs/C.explain1.r3.vxmtpdraft11.txt,2026-11-25T19:57:08,2026-11-25T19:59:22,0,com.apple.AppleUserHIDDrivers,0,True,1902 +C,heldout/explain2,explain,1,llama-completion,,1330,1330,3309.3600,,,26.5500,511,,,,on,4,0,logs/C.explain2.r1.completion.txt,2026-11-25T14:08:01,2026-11-25T14:08:28,0,loginwindow,0,, +C,heldout/explain2,explain,1,llama.cpp draft-mtp,3,1330,1330,3430.0000,,,19.0000,516,,483,355,on,4,0,logs/C.explain2.r1.mtp3.txt,2026-11-25T14:10:07,2026-11-25T14:10:22,0,airportd,0,True,2000 +C,heldout/explain2,explain,1,llama.cpp ngram-mod,,1330,1330,3270.0000,,,27.6823,513,,19,19,on,4,0,logs/C.explain2.r1.ngram.txt,2026-11-25T14:09:08,2026-11-25T14:09:27,0,identityservicesd,0,True,2000 +C,heldout/explain2,explain,1,qwen-vx,,1330,,2697.1352,,,22.3364,,,,,,,0,logs/C.explain2.r1.vx.txt,2026-11-25T13:56:42,2026-11-25T13:58:48,0,bash,0,, +C,heldout/explain2,explain,1,qwen-vx --draft,11,1330,,2698.3886,,,20.4039,,108,176,110,,,0,logs/C.explain2.r1.vxdraft11.txt,2026-11-25T13:59:28,2026-11-25T14:01:35,0,com.apple.AppleUserHIDDrivers,0,True,2034 +C,heldout/explain2,explain,1,qwen-vx --mtp,,1330,,2775.3668,,,15.7067,,201,388,309,,,0,logs/C.explain2.r1.vxmtp.txt,2026-11-25T14:02:15,2026-11-25T14:04:28,0,bash,0,True,2034 +C,heldout/explain2,explain,1,qwen-vx --mtp --draft,11,1330,,2776.6137,,,16.0164,,202,406,307,,,0,logs/C.explain2.r1.vxmtpdraft11.txt,2026-11-25T14:05:09,2026-11-25T14:07:21,0,WindowServer,0,True,2034 +C,heldout/explain2,explain,2,llama-completion,,1330,1330,3265.4300,,,26.1400,511,,,,on,4,0,logs/C.explain2.r2.completion.txt,2026-11-25T17:01:10,2026-11-25T17:01:27,0,PerfPowerServices,0,, +C,heldout/explain2,explain,2,llama.cpp draft-mtp,3,1330,1330,3434.0000,,,18.8391,516,,483,355,on,4,0,logs/C.explain2.r2.mtp3.txt,2026-11-25T16:56:56,2026-11-25T16:57:20,0,bash,0,True,2000 +C,heldout/explain2,explain,2,llama.cpp ngram-mod,,1330,1330,3264.0000,,,27.5789,513,,19,19,on,4,0,logs/C.explain2.r2.ngram.txt,2026-11-25T16:58:00,2026-11-25T16:58:19,0,loginwindow,0,True,2000 +C,heldout/explain2,explain,2,qwen-vx,,1330,,2697.5098,,,22.3569,,,,,,,0,logs/C.explain2.r2.vx.txt,2026-11-25T17:10:33,2026-11-25T17:12:50,0,airportd,0,, +C,heldout/explain2,explain,2,qwen-vx --draft,11,1330,,2697.3882,,,20.4133,,108,176,110,,,0,logs/C.explain2.r2.vxdraft11.txt,2026-11-25T17:07:47,2026-11-25T17:09:53,0,bash,0,True,2034 +C,heldout/explain2,explain,2,qwen-vx --mtp,,1330,,2772.5029,,,15.7262,,201,388,309,,,0,logs/C.explain2.r2.vxmtp.txt,2026-11-25T17:04:53,2026-11-25T17:07:07,0,clocksyncd,0,True,2034 +C,heldout/explain2,explain,2,qwen-vx --mtp --draft,11,1330,,2773.1552,,,16.0371,,202,406,307,,,0,logs/C.explain2.r2.vxmtpdraft11.txt,2026-11-25T17:02:08,2026-11-25T17:04:12,0,airportd,0,True,2034 +C,heldout/explain2,explain,3,llama-completion,,1330,1330,3307.1700,,,26.2000,511,,,,on,4,0,logs/C.explain2.r3.completion.txt,2026-11-25T20:57:52,2026-11-25T20:58:19,0,biomesyncd,0,, +C,heldout/explain2,explain,3,llama.cpp draft-mtp,3,1330,1330,3427.0000,,,18.1085,516,,483,355,on,4,0,logs/C.explain2.r3.mtp3.txt,2026-11-25T20:59:58,2026-11-25T21:00:13,0,bash,0,True,2000 +C,heldout/explain2,explain,3,llama.cpp ngram-mod,,1330,1330,3269.0000,,,27.3528,513,,19,19,on,4,0,logs/C.explain2.r3.ngram.txt,2026-11-25T20:58:59,2026-11-25T20:59:18,0,dasd,0,True,2000 +C,heldout/explain2,explain,3,qwen-vx,,1330,,2724.4759,,,22.5825,,,,,,,0,logs/C.explain2.r3.vx.txt,2026-11-25T20:46:18,2026-11-25T20:48:24,0,WindowServer,0,, +C,heldout/explain2,explain,3,qwen-vx --draft,11,1330,,2700.2499,,,20.4105,,108,176,110,,,0,logs/C.explain2.r3.vxdraft11.txt,2026-11-25T20:49:05,2026-11-25T20:51:12,0,0.3 agy,0,True,2034 +C,heldout/explain2,explain,3,qwen-vx --mtp,,1330,,2805.6397,,,16.1541,,201,388,309,,,0,logs/C.explain2.r3.vxmtp.txt,2026-11-25T20:51:52,2026-11-25T20:53:55,0,WindowServer,0,True,2034 +C,heldout/explain2,explain,3,qwen-vx --mtp --draft,11,1330,,2778.8503,,,16.0408,,202,406,307,,,0,logs/C.explain2.r3.vxmtpdraft11.txt,2026-11-25T20:55:06,2026-11-25T20:57:12,0,WindowServer,0,True,2034 +C,heldout/explain3,explain,1,llama-completion,,1257,1257,3157.8500,,,26.1000,511,,,,on,4,0,logs/C.explain3.r1.completion.txt,2026-11-25T15:04:30,2026-11-25T15:04:57,0,com.apple.AppleUserHIDDrivers,0,, +C,heldout/explain3,explain,1,llama.cpp draft-mtp,3,1257,1257,3275.0000,,,20.0916,513,,526,337,on,4,0,logs/C.explain3.r1.mtp3.txt,2026-11-25T15:06:45,2026-11-25T15:07:01,0,airportd,0,False,457 +C,heldout/explain3,explain,1,llama.cpp ngram-mod,,1257,1257,3118.0000,,,26.3704,513,,0,0,on,4,0,logs/C.explain3.r1.ngram.txt,2026-11-25T15:05:47,2026-11-25T15:06:05,0,com.apple.AppleUserHIDDrivers,0,False,457 +C,heldout/explain3,explain,1,qwen-vx,,1257,,2559.6418,,,22.3159,,,,,,,0,logs/C.explain3.r1.vx.txt,2026-11-25T14:53:17,2026-11-25T14:55:33,0,airportd,0,, +C,heldout/explain3,explain,1,qwen-vx --draft,11,1257,,2560.4732,,,22.4699,,43,43,14,,,0,logs/C.explain3.r1.vxdraft11.txt,2026-11-25T14:56:13,2026-11-25T14:58:20,0,WindowServer,0,True,2144 +C,heldout/explain3,explain,1,qwen-vx --mtp,,1257,,2632.3977,,,17.1259,,246,350,263,,,0,logs/C.explain3.r1.vxmtp.txt,2026-11-25T14:59:00,2026-11-25T15:01:04,0,loginwindow,0,True,2144 +C,heldout/explain3,explain,1,qwen-vx --mtp --draft,11,1257,,2633.4457,,,17.1306,,246,350,263,,,0,logs/C.explain3.r1.vxmtpdraft11.txt,2026-11-25T15:01:44,2026-11-25T15:03:50,0,com.apple.AppleUserHIDDrivers,0,True,2144 +C,heldout/explain3,explain,2,llama-completion,,1257,1257,3143.8900,,,26.2200,511,,,,on,4,0,logs/C.explain3.r2.completion.txt,2026-11-25T18:53:59,2026-11-25T18:54:17,0,bash,0,, +C,heldout/explain3,explain,2,llama.cpp draft-mtp,3,1257,1257,3297.0000,,,20.1520,513,,526,337,on,4,0,logs/C.explain3.r2.mtp3.txt,2026-11-25T18:51:46,2026-11-25T18:52:11,0,airportd,0,False,457 +C,heldout/explain3,explain,2,llama.cpp ngram-mod,,1257,1257,3116.0000,,,26.4366,513,,0,0,on,4,0,logs/C.explain3.r2.ngram.txt,2026-11-25T18:53:01,2026-11-25T18:53:19,0,bash,0,False,457 +C,heldout/explain3,explain,2,qwen-vx,,1257,,2566.1280,,,22.2896,,,,,,,0,logs/C.explain3.r2.vx.txt,2026-11-25T19:03:36,2026-11-25T19:05:43,0,com.apple.AppleUserHIDDrivers,0,, +C,heldout/explain3,explain,2,qwen-vx --draft,11,1257,,2564.3876,,,22.5365,,43,43,14,,,0,logs/C.explain3.r2.vxdraft11.txt,2026-11-25T19:00:48,2026-11-25T19:02:56,0,PowerUIAgent,0,True,2144 +C,heldout/explain3,explain,2,qwen-vx --mtp,,1257,,2633.5731,,,17.1099,,246,350,263,,,0,logs/C.explain3.r2.vxmtp.txt,2026-11-25T18:58:01,2026-11-25T19:00:08,0,WindowServer,0,True,2144 +C,heldout/explain3,explain,2,qwen-vx --mtp --draft,11,1257,,2634.1031,,,17.1508,,246,350,263,,,0,logs/C.explain3.r2.vxmtpdraft11.txt,2026-11-25T18:54:57,2026-11-25T18:57:10,0,bash,0,True,2144 +C,heldout/explain3,explain,3,llama-completion,,1257,1257,3169.4000,,,26.1400,511,,,,on,4,0,logs/C.explain3.r3.completion.txt,2026-11-25T22:31:49,2026-11-25T22:32:16,0,airportd,0,, +C,heldout/explain3,explain,3,llama.cpp draft-mtp,3,1257,1257,3289.0000,,,20.3860,513,,526,337,on,4,0,logs/C.explain3.r3.mtp3.txt,2026-11-25T22:33:54,2026-11-25T22:34:10,0,bash,0,False,457 +C,heldout/explain3,explain,3,llama.cpp ngram-mod,,1257,1257,3130.0000,,,26.3489,513,,0,0,on,4,0,logs/C.explain3.r3.ngram.txt,2026-11-25T22:32:56,2026-11-25T22:33:14,0,bash,0,False,457 +C,heldout/explain3,explain,3,qwen-vx,,1257,,2570.4012,,,22.3472,,,,,,,0,logs/C.explain3.r3.vx.txt,2026-11-25T22:20:46,2026-11-25T22:22:51,0,com.apple.AppleUserHIDDrivers,0,, +C,heldout/explain3,explain,3,qwen-vx --draft,11,1257,,2570.0867,,,22.5746,,43,43,14,,,0,logs/C.explain3.r3.vxdraft11.txt,2026-11-25T22:23:32,2026-11-25T22:25:40,0,bash,0,True,2144 +C,heldout/explain3,explain,3,qwen-vx --mtp,,1257,,2641.2733,,,17.1771,,246,350,263,,,0,logs/C.explain3.r3.vxmtp.txt,2026-11-25T22:26:20,2026-11-25T22:28:15,0,bash,0,True,2144 +C,heldout/explain3,explain,3,qwen-vx --mtp --draft,11,1257,,2640.9259,,,17.5767,,246,350,263,,,0,logs/C.explain3.r3.vxmtpdraft11.txt,2026-11-25T22:28:55,2026-11-25T22:31:09,0,com.apple.DriverKit-AppleBCMWLAN,0,True,2144 +C,heldout/write1,write,1,llama-completion,,44,44,240.5800,,,25.6800,511,,,,on,4,0,logs/C.write1.r1.completion.txt,2026-11-25T12:55:40,2026-11-25T12:56:04,0,com.apple.AppleUserHIDDrivers,0,, +C,heldout/write1,write,1,llama.cpp draft-mtp,3,44,44,251.0000,,,16.7529,514,,434,369,on,4,0,logs/C.write1.r1.mtp3.txt,2026-11-25T12:57:39,2026-11-25T12:57:49,0,airportd,0,False,773 +C,heldout/write1,write,1,llama.cpp ngram-mod,,44,44,234.0000,,,25.8908,513,,0,0,on,4,0,logs/C.write1.r1.ngram.txt,2026-11-25T12:56:44,2026-11-25T12:56:58,0,bash,0,False,773 +C,heldout/write1,write,1,qwen-vx,,44,,252.4635,,,22.1728,,,,,,,0,logs/C.write1.r1.vx.txt,2026-11-25T12:44:48,2026-11-25T12:46:53,0,1.7 agy,0,, +C,heldout/write1,write,1,qwen-vx --draft,11,44,,249.7835,,,20.8352,,101,114,73,,,0,logs/C.write1.r1.vxdraft11.txt,2026-11-25T12:47:34,2026-11-25T12:49:38,0,com.apple.AppleUserHIDDrivers,0,True,1764 +C,heldout/write1,write,1,qwen-vx --mtp,,44,,256.2283,,,15.1538,,198,382,312,,,0,logs/C.write1.r1.vxmtp.txt,2026-11-25T12:50:18,2026-11-25T12:52:18,0,com.apple.AppleUserHIDDrivers,0,True,1764 +C,heldout/write1,write,1,qwen-vx --mtp --draft,11,44,,256.5742,,,15.1512,,198,382,312,,,0,logs/C.write1.r1.vxmtpdraft11.txt,2026-11-25T12:52:58,2026-11-25T12:55:00,0,bash,0,True,1764 +C,heldout/write1,write,2,llama-completion,,44,44,238.7700,,,25.6500,511,,,,on,4,0,logs/C.write1.r2.completion.txt,2026-11-25T15:38:05,2026-11-25T15:38:19,0,bash,0,, +C,heldout/write1,write,2,llama.cpp draft-mtp,3,44,44,254.0000,,,16.1459,514,,434,369,on,4,0,logs/C.write1.r2.mtp3.txt,2026-11-25T15:36:11,2026-11-25T15:36:30,0,PerfPowerServices,0,False,773 +C,heldout/write1,write,2,llama.cpp ngram-mod,,44,44,235.0000,,,26.0409,513,,0,0,on,4,0,logs/C.write1.r2.ngram.txt,2026-11-25T15:37:10,2026-11-25T15:37:25,0,com.apple.AppleUserHIDDrivers,0,False,773 +C,heldout/write1,write,2,qwen-vx,,44,,249.2174,,,22.0482,,,,,,,0,logs/C.write1.r2.vx.txt,2026-11-25T15:47:28,2026-11-25T15:49:31,0,secd,0,, +C,heldout/write1,write,2,qwen-vx --draft,11,44,,250.7617,,,20.7818,,101,114,73,,,0,logs/C.write1.r2.vxdraft11.txt,2026-11-25T15:44:31,2026-11-25T15:46:47,0,secd,0,True,1764 +C,heldout/write1,write,2,qwen-vx --mtp,,44,,256.4156,,,15.1602,,198,382,312,,,0,logs/C.write1.r2.vxmtp.txt,2026-11-25T15:41:51,2026-11-25T15:43:51,0,launchd,0,True,1764 +C,heldout/write1,write,2,qwen-vx --mtp --draft,11,44,,257.2377,,,15.1459,,198,382,312,,,0,logs/C.write1.r2.vxmtpdraft11.txt,2026-11-25T15:39:00,2026-11-25T15:41:11,0,airportd,0,True,1764 +C,heldout/write1,write,3,llama-completion,,44,44,240.6100,,,25.7300,511,,,,on,4,0,logs/C.write1.r3.completion.txt,2026-11-25T19:45:48,2026-11-25T19:46:11,0,com.apple.AppleUserHIDDrivers,0,, +C,heldout/write1,write,3,llama.cpp draft-mtp,3,44,44,249.0000,,,16.1401,514,,434,369,on,4,0,logs/C.write1.r3.mtp3.txt,2026-11-25T19:47:46,2026-11-25T19:47:56,0,cfprefsd,0,False,773 +C,heldout/write1,write,3,llama.cpp ngram-mod,,44,44,235.0000,,,26.0058,513,,0,0,on,4,0,logs/C.write1.r3.ngram.txt,2026-11-25T19:46:51,2026-11-25T19:47:06,0,launchd,0,False,773 +C,heldout/write1,write,3,qwen-vx,,44,,249.9455,,,22.1700,,,,,,,0,logs/C.write1.r3.vx.txt,2026-11-25T19:34:25,2026-11-25T19:36:38,0,bash,0,, +C,heldout/write1,write,3,qwen-vx --draft,11,44,,250.5453,,,20.8593,,101,114,73,,,0,logs/C.write1.r3.vxdraft11.txt,2026-11-25T19:37:19,2026-11-25T19:39:35,0,com.apple.AppleUserHIDDrivers,0,True,1764 +C,heldout/write1,write,3,qwen-vx --mtp,,44,,258.2385,,,15.2092,,198,382,312,,,0,logs/C.write1.r3.vxmtp.txt,2026-11-25T19:40:15,2026-11-25T19:42:26,0,com.apple.AppleUserHIDDrivers,0,True,1764 +C,heldout/write1,write,3,qwen-vx --mtp --draft,11,44,,257.0762,,,15.2071,,198,382,312,,,0,logs/C.write1.r3.vxmtpdraft11.txt,2026-11-25T19:43:06,2026-11-25T19:45:07,0,WindowServer,0,True,1764 +C,heldout/write2,write,1,llama-completion,,52,52,250.8300,,,25.8400,511,,,,on,4,0,logs/C.write2.r1.completion.txt,2026-11-25T13:53:53,2026-11-25T13:54:16,0,clocksyncd,0,, +C,heldout/write2,write,1,llama.cpp draft-mtp,3,52,52,267.0000,,,16.4457,516,,443,368,on,4,0,logs/C.write2.r1.mtp3.txt,2026-11-25T13:55:51,2026-11-25T13:56:02,0,launchd,0,False,1581 +C,heldout/write2,write,1,llama.cpp ngram-mod,,52,52,244.0000,,,25.8129,513,,0,0,on,4,0,logs/C.write2.r1.ngram.txt,2026-11-25T13:54:56,2026-11-25T13:55:11,0,com.apple.AppleUserHIDDrivers,0,False,1600 +C,heldout/write2,write,1,qwen-vx,,52,,257.5855,,,22.0798,,,,,,,0,logs/C.write2.r1.vx.txt,2026-11-25T13:42:24,2026-11-25T13:44:30,0,mdworker_shared,0,, +C,heldout/write2,write,1,qwen-vx --draft,11,52,,256.8762,,,21.7088,,115,115,51,,,0,logs/C.write2.r1.vxdraft11.txt,2026-11-25T13:45:10,2026-11-25T13:47:32,0,bash,0,True,1661 +C,heldout/write2,write,1,qwen-vx --mtp,,52,,265.4873,,,13.6362,,156,413,354,,,0,logs/C.write2.r1.vxmtp.txt,2026-11-25T13:48:12,2026-11-25T13:50:22,0,WiFiAgent,0,True,1661 +C,heldout/write2,write,1,qwen-vx --mtp --draft,11,52,,265.1375,,,13.6293,,156,413,354,,,0,logs/C.write2.r1.vxmtpdraft11.txt,2026-11-25T13:51:02,2026-11-25T13:53:12,0,loginwindow,0,True,1661 +C,heldout/write2,write,2,llama-completion,,52,52,248.9500,,,25.6500,511,,,,on,4,0,logs/C.write2.r2.completion.txt,2026-11-25T16:44:35,2026-11-25T16:44:50,0,airportd,0,, +C,heldout/write2,write,2,llama.cpp draft-mtp,3,52,52,268.0000,,,17.0058,516,,443,368,on,4,0,logs/C.write2.r2.mtp3.txt,2026-11-25T16:42:40,2026-11-25T16:43:00,0,mdworker_shared,0,False,1581 +C,heldout/write2,write,2,llama.cpp ngram-mod,,52,52,244.0000,,,26.1384,513,,0,0,on,4,0,logs/C.write2.r2.ngram.txt,2026-11-25T16:43:40,2026-11-25T16:43:55,0,secd,0,False,1600 +C,heldout/write2,write,2,qwen-vx,,52,,258.2448,,,22.0335,,,,,,,0,logs/C.write2.r2.vx.txt,2026-11-25T16:54:12,2026-11-25T16:56:16,0,bash,0,, +C,heldout/write2,write,2,qwen-vx --draft,11,52,,257.0325,,,21.7833,,115,115,51,,,0,logs/C.write2.r2.vxdraft11.txt,2026-11-25T16:51:29,2026-11-25T16:53:31,0,com.apple.DriverKit-AppleBCMWLAN,0,True,1661 +C,heldout/write2,write,2,qwen-vx --mtp,,52,,266.7265,,,13.6815,,156,413,354,,,0,logs/C.write2.r2.vxmtp.txt,2026-11-25T16:48:10,2026-11-25T16:50:09,0,bash,0,True,1661 +C,heldout/write2,write,2,qwen-vx --mtp --draft,11,52,,267.2539,,,13.7725,,156,413,354,,,0,logs/C.write2.r2.vxmtpdraft11.txt,2026-11-25T16:45:30,2026-11-25T16:47:30,0,cfprefsd,0,True,1661 +C,heldout/write2,write,3,llama-completion,,52,52,250.5700,,,25.6600,511,,,,on,4,0,logs/C.write2.r3.completion.txt,2026-11-25T20:42:48,2026-11-25T20:43:11,0,com.apple.DriverKit-AppleBCMWLAN,0,, +C,heldout/write2,write,3,llama.cpp draft-mtp,3,52,52,277.0000,,,16.7733,516,,443,368,on,4,0,logs/C.write2.r3.mtp3.txt,2026-11-25T20:44:46,2026-11-25T20:44:57,0,WindowServer,3,False,1581 +C,heldout/write2,write,3,llama.cpp ngram-mod,,52,52,244.0000,,,25.9805,513,,0,0,on,4,0,logs/C.write2.r3.ngram.txt,2026-11-25T20:43:51,2026-11-25T20:44:06,0,launchd,0,False,1600 +C,heldout/write2,write,3,qwen-vx,,52,,258.4810,,,22.1067,,,,,,,0,logs/C.write2.r3.vx.txt,2026-11-25T20:31:01,2026-11-25T20:33:06,0,WindowServer,0,, +C,heldout/write2,write,3,qwen-vx --draft,11,52,,258.4373,,,21.8187,,115,115,51,,,0,logs/C.write2.r3.vxdraft11.txt,2026-11-25T20:33:46,2026-11-25T20:35:51,0,bash,0,True,1661 +C,heldout/write2,write,3,qwen-vx --mtp,,52,,266.0921,,,13.6430,,156,413,354,,,0,logs/C.write2.r3.vxmtp.txt,2026-11-25T20:37:31,2026-11-25T20:39:28,0,bash,0,True,1661 +C,heldout/write2,write,3,qwen-vx --mtp --draft,11,52,,268.6160,,,13.8713,,156,413,354,,,0,logs/C.write2.r3.vxmtpdraft11.txt,2026-11-25T20:40:09,2026-11-25T20:42:08,0,networkserviceproxy,0,True,1661 +C,heldout/write3,write,1,llama-completion,,35,35,214.6800,,,25.6400,511,,,,on,4,0,logs/C.write3.r1.completion.txt,2026-11-25T14:50:29,2026-11-25T14:50:52,0,com.apple.AppleUserHIDDrivers,0,, +C,heldout/write3,write,1,llama.cpp draft-mtp,3,35,35,234.0000,,,14.8760,516,,404,381,on,4,0,logs/C.write3.r1.mtp3.txt,2026-11-25T14:52:27,2026-11-25T14:52:37,0,com.apple.DriverKit-AppleBCMWLAN,0,True,1924 +C,heldout/write3,write,1,llama.cpp ngram-mod,,35,35,208.0000,,,26.6374,513,,15,15,on,4,0,logs/C.write3.r1.ngram.txt,2026-11-25T14:51:32,2026-11-25T14:51:47,0,com.apple.DriverKit-AppleBCMWLAN,0,True,1924 +C,heldout/write3,write,1,qwen-vx,,35,,231.2130,,,22.0347,,,,,,,0,logs/C.write3.r1.vx.txt,2026-11-25T14:39:11,2026-11-25T14:41:25,0,com.apple.AppleUserHIDDrivers,0,, +C,heldout/write3,write,1,qwen-vx --draft,11,35,,231.2503,,,19.4956,,95,176,123,,,0,logs/C.write3.r1.vxdraft11.txt,2026-11-25T14:42:05,2026-11-25T14:44:28,0,bash,0,True,1942 +C,heldout/write3,write,1,qwen-vx --mtp,,35,,238.3590,,,13.5392,,149,427,361,,,0,logs/C.write3.r1.vxmtp.txt,2026-11-25T14:45:09,2026-11-25T14:47:09,0,UserEventAgent,0,True,1942 +C,heldout/write3,write,1,qwen-vx --mtp --draft,11,35,,238.7589,,,13.5754,,143,453,367,,,0,logs/C.write3.r1.vxmtpdraft11.txt,2026-11-25T14:47:49,2026-11-25T14:49:48,0,xprotectd,0,True,1942 +C,heldout/write3,write,2,llama-completion,,35,35,213.3800,,,25.7200,511,,,,on,4,0,logs/C.write3.r2.completion.txt,2026-11-25T18:33:42,2026-11-25T18:33:57,0,airportd,0,, +C,heldout/write3,write,2,llama.cpp draft-mtp,3,35,35,231.0000,,,15.4961,516,,404,381,on,4,0,logs/C.write3.r2.mtp3.txt,2026-11-25T18:31:48,2026-11-25T18:32:07,0,com.apple.AppleUserHIDDrivers,0,True,1924 +C,heldout/write3,write,2,llama.cpp ngram-mod,,35,35,209.0000,,,26.7914,513,,15,15,on,4,0,logs/C.write3.r2.ngram.txt,2026-11-25T18:32:47,2026-11-25T18:33:02,0,bash,0,True,1924 +C,heldout/write3,write,2,qwen-vx,,35,,232.5422,,,22.1629,,,,,,,0,logs/C.write3.r2.vx.txt,2026-11-25T18:48:52,2026-11-25T18:51:06,0,WindowServer,0,, +C,heldout/write3,write,2,qwen-vx --draft,11,35,,232.2731,,,19.5489,,95,176,123,,,0,logs/C.write3.r2.vxdraft11.txt,2026-11-25T18:46:09,2026-11-25T18:48:12,0,WindowServer,0,True,1942 +C,heldout/write3,write,2,qwen-vx --mtp,,35,,239.3553,,,13.5829,,149,427,361,,,0,logs/C.write3.r2.vxmtp.txt,2026-11-25T18:37:28,2026-11-25T18:39:26,0,com.apple.AppleUserHIDDrivers,0,True,1942 +C,heldout/write3,write,2,qwen-vx --mtp --draft,11,35,,240.0632,,,13.5890,,143,453,367,,,0,logs/C.write3.r2.vxmtpdraft11.txt,2026-11-25T18:34:37,2026-11-25T18:36:48,0,bash,0,True,1942 +C,heldout/write3,write,3,llama-completion,,35,35,214.4300,,,25.6500,511,,,,on,4,0,logs/C.write3.r3.completion.txt,2026-11-25T22:55:14,2026-11-25T22:55:37,0,bash,0,, +C,heldout/write3,write,3,llama.cpp draft-mtp,3,35,35,241.0000,,,14.9671,516,,404,381,on,4,0,logs/C.write3.r3.mtp3.txt,2026-11-25T22:19:56,2026-11-25T22:20:06,0,com.apple.AppleUserHIDDrivers,0,True,1924 +C,heldout/write3,write,3,llama.cpp ngram-mod,,35,35,210.0000,,,26.7641,513,,15,15,on,4,0,logs/C.write3.r3.ngram.txt,2026-11-25T22:18:54,2026-11-25T22:19:16,0,bash,0,True,1924 +C,heldout/write3,write,3,qwen-vx,,35,,234.7096,,,22.2838,,,,,,,0,logs/C.write3.r3.vx.txt,2026-11-25T21:29:55,2026-11-25T21:32:04,0,com.apple.AppleUserHIDDrivers,0,, +C,heldout/write3,write,3,qwen-vx --draft,11,35,,232.2784,,,19.5272,,95,176,123,,,0,logs/C.write3.r3.vxdraft11.txt,2026-11-25T22:47:00,2026-11-25T22:49:02,0,loginwindow,0,True,1942 +C,heldout/write3,write,3,qwen-vx --mtp,,35,,238.7506,,,13.5427,,149,427,361,,,0,logs/C.write3.r3.vxmtp.txt,2026-11-25T22:49:42,2026-11-25T22:51:52,0,contextstored,0,True,1942 +C,heldout/write3,write,3,qwen-vx --mtp --draft,11,35,,238.6567,,,13.5874,,143,453,367,,,0,logs/C.write3.r3.vxmtpdraft11.txt,2026-11-25T22:52:32,2026-11-25T22:54:34,0,bash,0,True,1942 +P,context/ctx2048,ctx,1,llama-completion,,2048,2048,5086.7300,,,0.0000,1,,,,on,4,0,logs/P.llama.ctx2048.r1.txt,2026-11-25T11:45:25,2026-11-25T11:45:40,0,WindowServer,0,, +P,context/ctx2048,ctx,2,llama-completion,,2048,2048,5072.6500,,,0.0000,1,,,,on,4,0,logs/P.llama.ctx2048.r2.txt,2026-11-25T11:54:54,2026-11-25T11:55:09,0,com.apple.AppleUserHIDDrivers,0,, +P,context/ctx2048,ctx,3,llama-completion,,2048,2048,5069.7300,,,0.0000,1,,,,on,4,0,logs/P.llama.ctx2048.r3.txt,2026-11-25T12:10:25,2026-11-25T12:10:40,0,bash,0,, +P,context/ctx512,ctx,1,llama-completion,,512,512,1224.5000,,,0.0000,1,,,,on,4,0,logs/P.llama.ctx512.r1.txt,2026-11-25T11:41:49,2026-11-25T11:42:00,0,com.apple.AppleUserHIDDrivers,0,, +P,context/ctx512,ctx,2,llama-completion,,512,512,1220.5500,,,0.0000,1,,,,on,4,0,logs/P.llama.ctx512.r2.txt,2026-11-25T11:51:25,2026-11-25T11:51:28,0,com.apple.AppleUserHIDDrivers,0,, +P,context/ctx512,ctx,3,llama-completion,,512,512,1219.6000,,,0.0000,1,,,,on,4,0,logs/P.llama.ctx512.r3.txt,2026-11-25T12:06:18,2026-11-25T12:06:29,0,com.apple.AppleUserHIDDrivers,0,, +P,context/ctx8192,ctx,1,llama-completion,,8192,8192,23057.4300,,,0.0000,1,,,,on,4,0,logs/P.llama.ctx8192.r1.txt,2026-11-25T11:50:02,2026-11-25T11:50:35,0,bash,0,, +P,context/ctx8192,ctx,2,llama-completion,,8192,8192,22695.7100,,,0.0000,1,,,,on,4,0,logs/P.llama.ctx8192.r2.txt,2026-11-25T11:58:45,2026-11-25T11:59:17,0,PerfPowerServices,0,, +P,context/ctx8192,ctx,3,llama-completion,,8192,8192,22984.7400,,,0.0000,1,,,,on,4,0,logs/P.llama.ctx8192.r3.txt,2026-11-25T12:14:53,2026-11-25T12:15:25,0,configd,0,, +P,context/ctx2048,ctx,1,qwen-vx,,2048,,4208.2429,4118.7291,4169.2 4208.2,,,,,,,,0,logs/P.vx.ctx2048.r1.txt,2026-11-25T11:42:40,2026-11-25T11:44:45,0,AXVisualSupportAgent,0,, +P,context/ctx2048,ctx,2,qwen-vx,,2048,,4186.1730,4111.4521,4158.8 4186.2,,,,,,,,0,logs/P.vx.ctx2048.r2.txt,2026-11-25T11:55:49,2026-11-25T11:58:05,0,bash,0,, +P,context/ctx2048,ctx,3,qwen-vx,,2048,,4181.4628,4107.7361,4155.5 4181.5,,,,,,,,0,logs/P.vx.ctx2048.r3.txt,2026-11-25T12:07:39,2026-11-25T12:09:45,0,airportd,0,, +P,context/ctx512,ctx,1,qwen-vx,,512,,1143.9018,1132.8037,1140.0 1143.9,,,,,,,,0,logs/P.vx.ctx512.r1.txt,2026-11-25T11:39:09,2026-11-25T11:41:09,0,airportd,0,, +P,context/ctx512,ctx,2,qwen-vx,,512,,1135.0738,1121.9127,1130.2 1135.1,,,,,,,,0,logs/P.vx.ctx512.r2.txt,2026-11-25T11:52:18,2026-11-25T11:54:14,0,com.apple.AppleUserHIDDrivers,0,, +P,context/ctx512,ctx,3,qwen-vx,,512,,1136.7702,1122.1888,1132.9 1136.8,,,,,,,,0,logs/P.vx.ctx512.r3.txt,2026-11-25T12:03:40,2026-11-25T12:05:38,0,bash,0,, +P,context/ctx8192,ctx,1,qwen-vx,,8192,,20783.7791,19019.1174,20352.1 20783.8,,,,,,,,0,logs/P.vx.ctx8192.r1.txt,2026-11-25T11:46:31,2026-11-25T11:49:22,0,com.apple.DriverKit-AppleBCMWLAN,0,, +P,context/ctx8192,ctx,2,qwen-vx,,8192,,20703.3863,19022.7470,20323.1 20703.4,,,,,,,,0,logs/P.vx.ctx8192.r2.txt,2026-11-25T11:59:57,2026-11-25T12:03:00,0,com.apple.AppleUserHIDDrivers,0,, +P,context/ctx8192,ctx,3,qwen-vx,,8192,,20690.5193,18923.0289,20169.5 20690.5,,,,,,,,0,logs/P.vx.ctx8192.r3.txt,2026-11-25T12:11:20,2026-11-25T12:14:12,0,airportd,0,, +fa,context/ctx2048,ctx,1,llama-completion,,2048,2048,5027.8200,,,27.6100,255,,,,off,4,0,logs/fa-off.ctx2048.r1.txt,2026-11-25T09:54:48,2026-11-25T09:55:01,0,com.apple.AppleUserHIDDrivers,0,, +fa,context/ctx2048,ctx,2,llama-completion,,2048,2048,5038.3600,,,28.4500,255,,,,off,4,0,logs/fa-off.ctx2048.r2.txt,2026-11-25T09:55:41,2026-11-25T09:55:55,0,cfprefsd,0,, +fa,context/ctx2048,ctx,3,llama-completion,,2048,2048,5039.1300,,,27.8800,255,,,,off,4,0,logs/fa-off.ctx2048.r3.txt,2026-11-25T09:58:21,2026-11-25T09:58:35,0,launchd,0,, +fa,context/ctx2048,ctx,1,llama-completion,,2048,2048,4991.8800,,,26.6800,255,,,,on,4,0,logs/fa-on.ctx2048.r1.txt,2026-11-25T09:53:45,2026-11-25T09:54:08,0,mediaanalysisd,0,, +fa,context/ctx2048,ctx,2,llama-completion,,2048,2048,5003.1300,,,26.2900,255,,,,on,4,0,logs/fa-on.ctx2048.r2.txt,2026-11-25T09:56:35,2026-11-25T09:56:48,0,com.apple.AppleUserHIDDrivers,0,, +fa,context/ctx2048,ctx,3,llama-completion,,2048,2048,5008.7200,,,26.3100,255,,,,on,4,0,logs/fa-on.ctx2048.r3.txt,2026-11-25T09:57:28,2026-11-25T09:57:41,0,com.apple.AppleUserHIDDrivers,0,, diff --git a/docs/benchmarks/2026-11-25-qwen36-m4-mtp/summary.md b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/summary.md new file mode 100644 index 0000000..916c44b --- /dev/null +++ b/docs/benchmarks/2026-11-25-qwen36-m4-mtp/summary.md @@ -0,0 +1,111 @@ +flash attention: on 26.31 ms, off 27.88 ms (medians at 2,048 tokens); chosen: on +draft lengths given: DRAFT=11 MTP_N=3 +flash attention: given by FA; chosen: on + +## Table A: generated tokens after a prompt + +ms for each generated token: the median of the runs, and the fastest and slowest run. The prompt time is that of the first prompt of a process. + +| Prompt tokens | qwen-vx ms | llama.cpp ms | qwen-vx tok/s | llama.cpp tok/s | llama.cpp ms / qwen-vx ms | qwen-vx prompt ms | llama.cpp prompt ms | +| ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| 64 | 22.05 (22.03-22.08) | 25.82 (25.67-25.90) | 45.4 | 38.7 | 1.171 | 262 (262-263) | 252 (250-252) | +| 512 | 22.20 (22.16-22.20) | 26.03 (25.82-26.49) | 45.1 | 38.4 | 1.173 | 1122 (1121-1122) | 1219 (1216-1219) | +| 2,048 | 22.62 (22.62-22.63) | 26.26 (26.26-26.28) | 44.2 | 38.1 | 1.161 | 4109 (4109-4111) | 5066 (5062-5068) | +| 8,192 | 24.16 (24.11-24.16) | 28.02 (27.88-28.11) | 41.4 | 35.7 | 1.160 | 18947 (18890-18990) | 22709 (22632-22766) | +| 16,384 | 26.60 (26.59-26.76) | 32.27 (32.26-32.31) | 37.6 | 31.0 | 1.213 | 46196 (45968-46380) | 54128 (53659-54465) | +| 32,768 | 50.49 (48.66-51.41) | 58.90 (58.00-65.10) | 19.8 | 17.0 | 1.167 | 147674 (141011-150820) | 161094 (149761-163903) | + +## Table P: the prompt + +Tokens of the prompt each second: the median of the runs, and the slowest and fastest run. qwen-vx ran the prompt several times in one process. The first run includes the first launch of each kernel. llama-completion ran the prompt once, after its warm-up. + +| Prompt tokens | qwen-vx first run | qwen-vx later runs | llama-completion | +| ---: | ---: | ---: | ---: | +| 512 | 456 (452-456) | 451 (448-453) | 419 (418-420) | +| 2,048 | 498 (497-499) | 490 (487-493) | 404 (403-404) | +| 8,192 | 431 (431-433) | 399 (394-406) | 356 (355-361) | + +## Table C: the 12 held-out prompts + +ms for each generated token: the geometric mean over the prompts of each kind, and the fastest and slowest run. + +| Kind | Prompt tokens | qwen-vx | qwen-vx --draft | qwen-vx --mtp | qwen-vx --mtp --draft | llama-completion | llama.cpp ngram-mod | llama.cpp draft-mtp | +| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| edit | 1286, 1605, 1668 | 22.40 (22.31-22.48) | 11.00 (9.05-13.91) | 12.94 (12.24-13.54) | 10.62 (9.47-12.03) | 26.36 (26.15-26.53) | 11.48 (6.91-20.37) | 15.62 (15.08-16.21) | +| complete | 1044, 1086, 1288 | 22.33 (22.23-22.40) | 20.28 (18.36-21.42) | 15.46 (13.97-16.78) | 15.37 (13.78-16.83) | 26.14 (26.03-26.35) | 27.66 (26.29-30.30) | 17.35 (16.42-18.10) | +| write | 35, 44, 52 | 22.12 (22.03-22.28) | 20.69 (19.50-21.82) | 14.11 (13.54-15.21) | 14.15 (13.58-15.21) | 25.69 (25.64-25.84) | 26.23 (25.81-26.79) | 16.05 (14.88-17.01) | +| explain | 1257, 1330, 1503 | 22.38 (22.29-22.58) | 21.55 (20.40-22.57) | 16.72 (15.71-17.21) | 16.83 (16.02-17.58) | 26.24 (26.10-26.55) | 26.80 (26.35-27.68) | 19.68 (18.11-20.39) | +| all 12 | | 22.31 (22.03-22.58) | 17.76 (9.05-22.57) | 14.74 (12.24-17.21) | 14.04 (9.47-17.58) | 26.10 (25.64-26.55) | 21.74 (6.91-30.30) | 17.10 (14.88-20.39) | + +- qwen-vx against llama-completion: 1.170, faster on 12 of 12 prompts (1.16 to 1.18) +- qwen-vx --draft against qwen-vx: 1.256, faster on 11 of 12 prompts (0.99 to 2.46) +- qwen-vx --draft against llama-completion: 1.470, faster on 12 of 12 prompts (1.16 to 2.91) +- qwen-vx --draft against llama.cpp ngram-mod: 1.224, faster on 11 of 12 prompts (0.77 to 1.64) +- qwen-vx --draft against llama.cpp draft-mtp: 0.963, faster on 3 of 12 prompts (0.77 to 1.68) +- qwen-vx --mtp against qwen-vx: 1.514, faster on 12 of 12 prompts (1.30 to 1.82) +- qwen-vx --mtp against qwen-vx --draft: 1.205, faster on 10 of 12 prompts (0.74 to 1.59) +- qwen-vx --mtp against llama-completion: 1.771, faster on 12 of 12 prompts (1.53 to 2.16) +- qwen-vx --mtp against llama.cpp ngram-mod: 1.475, faster on 10 of 12 prompts (0.57 to 2.15) +- qwen-vx --mtp against llama.cpp draft-mtp: 1.161, faster on 12 of 12 prompts (1.06 to 1.25) +- qwen-vx --mtp --draft against qwen-vx: 1.589, faster on 12 of 12 prompts (1.29 to 2.35) +- qwen-vx --mtp --draft against qwen-vx --draft: 1.265, faster on 11 of 12 prompts (0.96 to 1.58) +- qwen-vx --mtp --draft against qwen-vx --mtp: 1.050, faster on 6 of 12 prompts (0.99 to 1.29) +- qwen-vx --mtp --draft against llama-completion: 1.859, faster on 12 of 12 prompts (1.51 to 2.78) +- qwen-vx --mtp --draft against llama.cpp ngram-mod: 1.548, faster on 11 of 12 prompts (0.74 to 2.19) +- qwen-vx --mtp --draft against llama.cpp draft-mtp: 1.218, faster on 12 of 12 prompts (1.06 to 1.61) +- llama.cpp ngram-mod against llama-completion: 1.201, faster on 3 of 12 prompts (0.87 to 3.78) +- llama.cpp draft-mtp against llama-completion: 1.526, faster on 12 of 12 prompts (1.29 to 1.73) + +### Drafts, table C, round 1 + +| Kind | qwen-vx --draft accepted / drafted | qwen-vx --mtp accepted / drafted | qwen-vx --mtp --draft accepted / drafted | llama.cpp ngram-mod accepted / drafted | llama.cpp draft-mtp accepted / drafted | +| --- | ---: | ---: | ---: | ---: | ---: | +| edit | 1221 / 1303 (94%), 5.93 per check | 1166 / 1275 (91%), 3.21 per check | 1326 / 1418 (94%), 6.50 per check | 1199 / 1199 (100%) | 1149 / 1193 (96%) | +| complete | 357 / 599 (60%), 0.91 per check | 934 / 1156 (81%), 1.57 per check | 953 / 1211 (79%), 1.65 per check | 41 / 41 (100%) | 1096 / 1348 (81%) | +| write | 247 / 405 (61%), 0.79 per check | 1027 / 1222 (84%), 2.04 per check | 1033 / 1248 (83%), 2.08 per check | 15 / 15 (100%) | 1118 / 1281 (87%) | +| explain | 179 / 324 (55%), 0.72 per check | 836 / 1091 (77%), 1.21 per check | 834 / 1109 (75%), 1.20 per check | 19 / 19 (100%) | 1031 / 1538 (67%) | +| all 12 | 2004 / 2631 (76%), 1.73 per check | 3963 / 4744 (84%), 1.84 per check | 4146 / 4986 (83%), 2.10 per check | 1274 / 1274 (100%) | 4394 / 5360 (82%) | + +- qwen-vx --draft: the text of qwen-vx in 36 of 36 runs +- qwen-vx --mtp: the text of qwen-vx in 36 of 36 runs +- qwen-vx --mtp --draft: the text of qwen-vx in 36 of 36 runs +- llama.cpp ngram-mod: the text of llama-completion in 24 of 36 runs. Other text, in the summary (the number of equal characters at the start): logs/C.complete3.r1.ngram.txt (1395), logs/C.complete3.r2.ngram.txt (1395), logs/C.complete3.r3.ngram.txt (1395), logs/C.explain3.r1.ngram.txt (457), logs/C.explain3.r2.ngram.txt (457), logs/C.explain3.r3.ngram.txt (457), logs/C.write1.r1.ngram.txt (773), logs/C.write1.r2.ngram.txt (773), logs/C.write1.r3.ngram.txt (773), logs/C.write2.r1.ngram.txt (1600), logs/C.write2.r2.ngram.txt (1600), logs/C.write2.r3.ngram.txt (1600) +- llama.cpp draft-mtp: the text of llama-completion in 21 of 36 runs. Other text, in the summary (the number of equal characters at the start): logs/C.complete1.r1.mtp3.txt (1055), logs/C.complete1.r2.mtp3.txt (1055), logs/C.complete1.r3.mtp3.txt (1055), logs/C.complete3.r1.mtp3.txt (1395), logs/C.complete3.r2.mtp3.txt (1395), logs/C.complete3.r3.mtp3.txt (1395), logs/C.explain3.r1.mtp3.txt (457), logs/C.explain3.r2.mtp3.txt (457), logs/C.explain3.r3.mtp3.txt (457), logs/C.write1.r1.mtp3.txt (773), logs/C.write1.r2.mtp3.txt (773), logs/C.write1.r3.mtp3.txt (773), logs/C.write2.r1.mtp3.txt (1581), logs/C.write2.r2.mtp3.txt (1581), logs/C.write2.r3.mtp3.txt (1581) + +### qwen-vx and llama-completion: where the text starts to differ + +The characters at the start of the generated text that are the same, round 1. The weight files differ in the token embedding and the output matrix, so the greedy text of the two programs can differ. + +| Prompt | Same characters | Characters of llama-completion | +| --- | ---: | ---: | +| complete1 | 104 | 2085 | +| complete2 | 0 | 1938 | +| complete3 | 12 | 1427 | +| edit1 | 1768 | 1768 | +| edit2 | 2049 | 2049 | +| edit3 | 1807 | 1909 | +| explain1 | 87 | 1943 | +| explain2 | 5 | 2000 | +| explain3 | 281 | 2121 | +| write1 | 1764 | 1764 | +| write2 | 1077 | 1732 | +| write3 | 419 | 1924 | + +## llama-bench-pp + +| model | size | params | backend | threads | fa | test | t/s | +| ------------------------------ | ---------: | ---------: | ---------- | ------: | --: | --------------: | -------------------: | +| qwen35moe 35B.A3B Q4_0 | 18.35 GiB | 34.66 B | MTL,BLAS | 4 | 1 | pp512 | 424.84 ± 3.43 | +| qwen35moe 35B.A3B Q4_0 | 18.35 GiB | 34.66 B | MTL,BLAS | 4 | 1 | pp2048 | 403.30 ± 3.33 | +| qwen35moe 35B.A3B Q4_0 | 18.35 GiB | 34.66 B | MTL,BLAS | 4 | 1 | pp8192 | 335.23 ± 12.78 | + +## llama-bench-tg + +| model | size | params | backend | threads | fa | test | t/s | +| ------------------------------ | ---------: | ---------: | ---------- | ------: | --: | --------------: | -------------------: | +| qwen35moe 35B.A3B Q4_0 | 18.35 GiB | 34.66 B | MTL,BLAS | 4 | 1 | tg128 | 39.05 ± 0.21 | +| qwen35moe 35B.A3B Q4_0 | 18.35 GiB | 34.66 B | MTL,BLAS | 4 | 1 | tg128 @ d2048 | 38.08 ± 0.29 | +| qwen35moe 35B.A3B Q4_0 | 18.35 GiB | 34.66 B | MTL,BLAS | 4 | 1 | tg128 @ d8192 | 35.26 ± 0.51 | +| qwen35moe 35B.A3B Q4_0 | 18.35 GiB | 34.66 B | MTL,BLAS | 4 | 1 | tg128 @ d16384 | 25.98 ± 0.36 | +| qwen35moe 35B.A3B Q4_0 | 18.35 GiB | 34.66 B | MTL,BLAS | 4 | 1 | tg128 @ d32768 | 18.86 ± 0.11 | + diff --git a/docs/checks.md b/docs/checks.md new file mode 100644 index 0000000..e9a91a9 --- /dev/null +++ b/docs/checks.md @@ -0,0 +1,50 @@ +# The checks of the program + +How the Vx program and the NumPy reference were checked. + +## The check of the Vx program + +`compare.py` compared the Vx program with `reference.py` over 64 greedy steps, after the prompt +`def fibonacci(n):` and a new line. Both chose the same tokens. + +| Model | Largest logit difference | +| --- | --- | +| tiny model | 4.7e-05, over 16 steps | +| tiny model, Q4_0 | 4.8e-05, over 16 steps | +| tiny MoE model | 4.7e-05, over 16 steps | +| tiny MoE model, Q4_0 | 5.0e-05, over 16 steps | +| Qwen2.5-Coder-0.5B-Instruct | 5.3e-05 | +| Qwen2.5-Coder-7B-Instruct | 6.0e-05 | + +The tiny model runs in CI with `tests/generate.vx`. That test fails when RoPE uses another theta, +when a token runs at the wrong position, and when the two norms of a layer swap their weights. +For the tiny MoE model, it fails when the router reads the hidden state before its norm, when a +token uses one expert in place of two, and when the Q and K norms are missing or swapped. + +## The check of the reference + +`check_against_mlx.py` compared the reference with MLX in float32 over a 5-token prompt and 32 +greedy steps. Both chose the same tokens. + +| Model | Largest logit difference | Time on an M4 | Peak memory | +| --- | --- | --- | --- | +| Qwen2.5-Coder-0.5B-Instruct | 8.7e-05 | 7 s | 5 GB | +| Qwen2.5-Coder-7B-Instruct | 6.3e-05 | 19 min | 15 GB | + +The check fails, as it should, when RoPE uses another theta, when the causal mask lets a token +see the next one, when the program does not add the Q, K and V bias, and when the converter swaps +K and V. + +For the tiny MoE model, `make_tiny_model.py --moe --hugging-face DIR` also writes the model as a +Hugging Face folder, which MLX reads: + +```sh +python3 scripts/make_tiny_model.py --moe --hugging-face tiny-moe tiny-moe.vxw +python3 scripts/check_against_mlx.py --tokens 17,200,3,95,41 tiny-moe tiny-moe.vxw +``` + +Over 32 greedy steps, both chose the same tokens, and the largest logit difference was 8.7e-06. +The check fails when the router chooses the smallest experts or one expert too few, or when it +does not scale the weights of the chosen experts to sum to 1. It also fails when an expert uses +the down matrix of the next expert, when the converter puts the up rows before the gate rows, or +when the Q and K norms are missing, swapped or after RoPE. diff --git a/docs/internals.md b/docs/internals.md new file mode 100644 index 0000000..c01e33c --- /dev/null +++ b/docs/internals.md @@ -0,0 +1,106 @@ +# How the program works + +The prompt in chunks, the attention of long contexts, the tokenizer, and the rights of the program. + +## The prompt in chunks + +A generated token reads every weight that it uses, so it waits for memory. The prompt has all its +tokens at the start, so the program runs it in chunks of up to 2048 tokens. A chunk reads each +weight once for all its tokens. `src/prefill.vx` has the kernels of a chunk: + +- One product for each weight format. A block decodes 128 rows of the matrix and 32 columns at a + time into shared memory, and multiplies them with the inputs of 16 tokens, with a matmul of + tiles (`@`). +- For the experts of a MoE layer, the CPU sorts the tokens of the chunk by expert. Then a tile of + 16 tokens reads the weights of one expert. +- Attention in three passes: the scores, as a matmul of the queries and the keys; their softmax; + and the sum of the values, as a matmul of the weights and the values. The rows of the matmuls + are the query heads of one key-value head for two tokens, so a tile of the cache serves 16 + rows. The matmuls skip the positions after the tokens of their tile. Attention takes 128 + tokens of the chunk at a time, so that its scratch tensor of scores does not grow with the + chunk. + +The time of each prompt token, on an M4 with 32 GB, with the prompt as the first tokens of the +README of that time: + +| Model | Prompt | One token at a time | In chunks | +| --- | --- | --- | --- | +| Qwen2.5-Coder-0.5B-Instruct, bf16 | 600 tokens | 11.1 ms | 1.15 ms | +| Qwen3-Coder-30B-A3B-Instruct, Q4_0 | 1000 tokens | 46.7 ms | 10.8 ms | +| Qwen3-Coder-30B-A3B-Instruct, Q4_0 | 2000 tokens | | 8.1 ms | + +Both ways chose the same tokens after the prompt. On the 0.5B model, `compare.py` compared 32 steps +with `reference.py`, and the largest logit difference was 5.5e-05. The times include the first +compile of the kernels of a chunk, about 4 seconds. Without it, the prompt of 2000 tokens takes +7.0 ms a token. + +Before the attention in tiles, each block did one token, and so each chunk read the whole cache +once for each token in each layer. Then the prompts of 1000 and 2000 tokens took 15.1 ms and +16.2 ms a token. Now the products of the experts take most of the time of a chunk. Their `@` +loads its sum from shared memory and stores it back for each 32 columns, and the 32 KB of shared +memory does not hold larger tiles +([#19](https://github.com/vx-lang/qwen-vx/issues/19)). + +`tests/prefill.vx` runs a prompt of 40 tokens through each tiny model one token at a time, and in +chunks of 16 tokens. The logits of the last token must be within 0.0001, and the next 8 tokens +equal. + +## Long contexts + +A generated token attends to every position before it. The `nn_attention` of Vx v0.0.4 has one +block for each query head, so its time grows with the number of positions. The `nn_attention` of +Vx main splits the positions among blocks +([vx-lang/Vx#3216](https://github.com/vx-lang/Vx/pull/3216)). `src/attention.vx` is a copy of it, +until a Vx release has it ([#4](https://github.com/vx-lang/qwen-vx/issues/4)). + +The time of a generated token of Qwen3-Coder-30B-A3B in Q4_0, on an M4 with 32 GB, after a prompt +of the first tokens of the README of that time: + +| Positions | One block for each head | Positions split among blocks | +| --- | --- | --- | +| 5 | 26.7 ms | 25.4 ms | +| 1000 | 40.7 ms | 27.5 ms | +| 2000 | 57.3 ms | 30.8 ms | + +Both chose the same tokens. On Qwen2.5-Coder-0.5B, 100 tokens after a prompt of 600 went past +position 640, where a block takes 64 positions in place of 32. `compare.py` gave the same tokens +as `reference.py`, with each logit within 5.3e-05. `tests/generate.vx` also runs the tiny models +with 1024 positions after a prompt of 700 tokens. + +## The tokenizer + +`src/tokenizer.vx` is the byte-level BPE tokenizer of Qwen2, Qwen3 and Qwen3.5. It splits out the added +tokens, such as `<|im_start|>`, and applies Unicode NFC to the text between them. Then it splits +the text with the regex of the pre-tokenizer, and merges the bytes of each piece by the ranks of +tokenizer.json. `convert_tokenizer.py` describes the file and the steps. The file holds sorted +tables, so each lookup is a binary search in the mapped file. + +The tokenizer gives the ids of the `tokenizers` package of Hugging Face. On 21.5 MB of text, +`test_tokenizer.py` found the same ids for each of 4783 texts, with both the Qwen2.5-Coder and the +Qwen3-Coder tokenizer. The texts were this repository, Python, Rust and C++ sources, and 3000 texts +of random Unicode characters, marks, Hangul, emoji, white space and added tokens. The Vx program +encoded 3 MB of source files, 820,000 tokens, in about 2.4 seconds. + +The NFC step of `tokenizers` has the data of an old Unicode version. It does not know the +combining class of 120 marks that later versions added, and it does not make 21 newer composites. +`convert_tokenizer.py` leaves both out of its tables, so that the ids are the same. +`test_tokenizer.py` measures the two lists again, and fails when they change. The tables come from +the `unicodedata` module of Python, so `convert_tokenizer.py` needs the Unicode version of +`tokenizers`, 16.0, which Python 3.14 has. It refuses another version. + +`tests/tokenize.vx` checks a tiny tokenizer from `make_tiny_tokenizer.py` against the ids that +`tokenizers` gave for it. So CI checks the tokenizer without a download. To compare with +`tokenizers` on a large corpus: + +```sh +QWEN_TOKENIZER_CORPUS_MB=40 python3 scripts/test_tokenizer.py +``` + +## The rights of the program + +`main` takes the rights of the program from Vx: `fn main(root : Root, args : Vec)`. It +passes `&root.files`, the right to open files, to the functions that open the weight file, the +tokenizer file, a prompt file and a cache file. It passes `root.stdout`, the right to print, to the +functions that print the tokens. Safe code can open a file only with a `&Files`. The `print!` and +`println!` of Vx still need no right. The program declares no `extern` function. It still calls +`malloc` and `free` of `std::libc` for its buffers. diff --git a/docs/optimizations.md b/docs/optimizations.md index a181788..2f39cb1 100644 --- a/docs/optimizations.md +++ b/docs/optimizations.md @@ -317,6 +317,136 @@ more than plain steps; with them, nothing (write prompts, two runs of each in tu The text is the same as without drafts in all 24 pairs of these runs. +### 15. Expert launches in an order that overlaps (#34) + +**Problem.** A GPU trace of a generated token (Metal System Trace with the GPU counters, 512 +positions) shows the GPU idle for about 3.4 ms of a 22.8 ms token, mostly between a kernel and the +kernel that reads its output. The concurrent encoder of Vx puts a barrier only where a launch +reads what an earlier launch wrote, so launches that do not depend on each other can run at the +same time. But in a layer of experts, each launch read the output of the one just before it. + +**Change.** `add_experts_shared` now starts the SwiGLU of the shared expert first, which needs only +`xn`. So it runs with the router; the gate of the shared expert runs with top-k; and the down +product of the shared expert runs with the SwiGLU of the chosen experts. The shared expert is now +added to `x` before the chosen experts. The rounds of `--draft` use the same order, so they still +give the same bits as one position. + +**Result.** 22.36 to 22.22 ms a token at 512 positions, faster in 4 of 4 interleaved runs. + +### 16. Drafts from the MTP layer of Qwen3.6 (#109) + +**Problem.** Drafts from the context (entry 14) help only when the output repeats text of the +prompt. Qwen3.6-35B-A3B has one more layer for drafts, the MTP layer (multi-token prediction). It +takes h of the model at position p (after `final_norm`) and the token at position p + 1, and gives +logits for position p + 2. llama.cpp uses this layer for its drafts. + +**Change.** + +- `convert.py` writes the MTP layer at the end of the weight file. The other tensors keep their + order and bytes. The config integer `mtp_layers` takes slot 25 of the version 2 header, so an + older file reads 0 and loads as before. +- `src/mtp35.vx` runs the MTP layer: a layer with full attention and its own KV cache. The prompt + fills the rows of the MTP layer one chunk at a time, after each chunk of the model. +- `--mtp K` drafts with this layer, one MTP row for each draft token, and checks the drafts with + the rounds of entry 14. So the text is the same as without drafts. +- A draft scores only the tokens with ids below 65,536 (`--mtp-vocab N`), a quarter of the rows of + `lm_head`. +- A round drafts K tokens while a running mean of the kept drafts is at least 0.85, and 1 token + otherwise. +- After a round, the rows of the kept tokens run again with the true h of the model. These rows, + and the row of the first draft of the next round, have all their inputs after the round, so + `mtp35_rows` runs them in one pass with the kernels of the round. +- With `--mtp K,L`, a round drafts L tokens while the running mean of the kept drafts is at least + 0.95, and K tokens while it is at least 0.85. Long drafts pay in edits, where almost all drafts + are kept. + +**Result.** In the run of 2026-11-25 ([`docs/benchmarks/2026-11-25-qwen36-m4-mtp/`](benchmarks/2026-11-25-qwen36-m4-mtp/README.md)), on the 12 +held-out prompts, `--mtp 3,5` took 14.74 ms a generated token against 22.31 ms without drafts +(1.51×, faster on 12 of 12 prompts, 1.30× to 1.82×). It kept 84% of its drafts, 1.84 tokens for +each check, and gave the text without drafts in 36 of 36 runs. Against llama.cpp with its MTP +drafts (3 tokens, 17.10 ms), it is 1.16× (faster on 12 of 12 prompts). The run has entries 17 to 19 +too. + +### 17. The attention and the lm_head of a round, for all positions at once (#110) + +**Problem.** With the MTP drafts of entry 16, a round of Qwen3.6 has 2 to 4 positions. Two parts +of a round did more work for each position than they must: + +- Each full attention layer ran 5 kernels for each position of the round. +- `matvec_q6_rows` does 2 vectors in each block, so the 6-bit `lm_head` of 3 or 4 positions read + each weight twice. + +**Change.** + +- The full attention layers of a round run 3 kernels for all n positions: + `pf_gated_norm_rope_and_store` (the kernel of the prompt chunks) stores the k and v rows of all + positions, and `gated_attention_parts_rows` and `gated_attention_merge_rows` do the attention of + each position over the rows up to its own position. Each position computes its own number of + parts, as `gated_attention` does, so a round can cross position 2048. +- `matvec_q6_rows4` does 4 vectors in each block, and runs for rounds of 3 or more positions. To + keep 16 values of x for each vector, and not 32, a lane keeps only x scaled for the low bits, and + multiplies the high bits of weight t by 16 * 4^-t over that scale. Both factors are powers of 2, + so each product and each step of each sum is that of `matvec_q6`. + +Each position keeps the bits of a plain step (`tests/round35.vx`, `tests/round.vx`). + +**Result.** The run of 2026-11-25 ([`docs/benchmarks/2026-11-25-qwen36-m4-mtp/`](benchmarks/2026-11-25-qwen36-m4-mtp/README.md)) measures this change +only together with entries 16, 18 and 19 (entry 16 has the numbers). + +### 18. The lm_head of a round: only the rows that can be the greedy token (#111) + +**Problem.** A round needs only the greedy token of each position and its logit. But it computed +all 248,320 logits of each position exactly, and the arithmetic of the 6-bit weights grows with +the number of positions. A profile by subtraction of a round cannot show the `lm_head`, because +without it nothing waits for the round. A separate bench showed the arithmetic, not the bytes, as +the limit of `matvec_q6_rows4` at 4 positions and more. + +**Change.** For 2 or more positions, `run_round35` runs three kernels (`src/q6.vx`): + +- `lm_rough_q6` computes rough logits a for up to 8 positions at once, with f16 weights and inputs + on the simdgroup matrices. +- `lm_pick_threshold` finds, for each position, M = the largest a - B over the rows. B is a bound + of |a - e|, where e is the exact logit. It comes from the norms of x and of the rows of + `lm_head`, and `src/q6.vx` gives each of its terms. `lm_q6_norms` computes the norms of the rows + in the first round. +- `matvec_q6_rows4_pick` computes the exact logit of each row that does not have a + B < M, bit for + bit as `matvec_q6` does. The other rows get the lowest f32, and cannot be the greedy token. A + block with no such row reads no weights. + +The true error is about 3% of B. In the rounds of a bench on the real model, at most 3 of the +248,320 rows of a position needed the exact logit. The greedy tokens and their logits are those +of the plain steps (`tests/round35.vx`). Only the other logits of a round change, and the app does +not read them. + +**Result.** The run of 2026-11-25 ([`docs/benchmarks/2026-11-25-qwen36-m4-mtp/`](benchmarks/2026-11-25-qwen36-m4-mtp/README.md)) measures this change +only together with entries 16, 17 and 19 (entry 16 has the numbers). + +### 19. Drafts from the context in the rounds of the MTP drafts (#113) + +**Problem.** In an edit, the output repeats long parts of the prompt. The drafts from the context +(entry 14) then give long rounds whose drafts are all kept. The MTP drafts (entry 16) give at most +L tokens in a round. But `--draft` and `--mtp` could not run together. + +**Change.** + +- With `--mtp` and `--draft D`, each round first finds the longest match in the context, as + `generate_with_drafts35` does. When the match has at least 16 tokens, the round drafts up to D + tokens of the context after the match. Otherwise it drafts from the MTP layer as before. +- `--draft D,M` sets the shortest match to M. On the tuning prompts, matches of 12 to 15 tokens + often gave drafts that the round did not keep, and such a round costs more than the MTP round + that it replaces. So the default is 16, the longest match that `longest_match` finds. +- Only the MTP rounds change the running mean of the kept MTP drafts. +- The MTP rows of the kept tokens still run after each round, so the next MTP draft is ready. + +The text is the same as without drafts (`tests/generate_qwen35.vx`). + +**Result.** In the run of 2026-11-25 ([`docs/benchmarks/2026-11-25-qwen36-m4-mtp/`](benchmarks/2026-11-25-qwen36-m4-mtp/README.md)), +`--mtp 3,5 --draft 11` took 10.62 ms a generated token on the edit prompts, against 12.94 ms for +`--mtp 3,5` (1.22×). On the other kinds, the two differ by 1% or less (0.99× to 1.01×). Over the 12 +held-out prompts, it is 1.05× `--mtp 3,5` (faster on 6 of 12, 0.99× to 1.29×), 1.59× the app +without drafts, and 1.22× llama.cpp with its MTP drafts (14.04 against 17.10 ms, faster on 12 of +12 prompts). + ## What did not help - **Other tile shapes for the Q4_0 products of a chunk, in Vx v0.0.4** (#19). Tiles of 32 tokens, @@ -340,9 +470,18 @@ The text is the same as without drafts in all 24 pairs of these runs. round kernels of Vx main and drafts only when they pay, edits are 1.84 times as fast (entry 14). A draft model may still pay on a Mac with matrix units, or for a model where a token costs more. +- **The norm before the experts merged into the router and the SwiGLUs** (#34). Each block found + the scale of the norm from all of `x`, then read `x` times the scale. This removed 40 launches + from a token, but only 6 of its 417 barriers: the router and the SwiGLUs must still wait for the + product that writes `x`. With each block reading all of `x` again, the token was about 0.55 ms + slower (4 of 4 interleaved runs). So the idle gaps between small kernels are waits for data, + not the cost of a launch. Only work that does not depend on the kernel before it fills a gap. - **Weights decoded once into registers for several tokens.** In Vx v0.0.4 these kernels were slower than the kernels that decode each weight with masks for each token. Their 64 to 128 floats a lane likely leave the registers. +- **The router of a round with 4 positions in each block.** A bf16 kernel for the router of 4 + positions, as `matvec_q6_rows4` does for `lm_head`, was no faster than the router of each + position in turn. The router of a round is not limited by the reads of its weights. ## Open work @@ -351,9 +490,10 @@ The text is the same as without drafts in all 24 pairs of these runs. - **The start of a session** (#27): the load of the weights takes about 10.5 s since entry 11. The compile of the program at -O0 is the next part to measure. - **Small kernels** (#34): the 336 kernels of a token other than the products (7 in each layer) - take about 2.5 ms for about 0.7 ms of bytes. Each one reads what the kernel before it wrote, so - running kernels at the same time does not help; fewer kernels do. Merge the norms into the - products after them, and the router into top-k. + take about 2.5 ms for about 0.7 ms of bytes. Each one reads what the kernel before it wrote. + Fewer launches alone do not help (see "What did not help"); work that runs at the same time + does (entry 15). A next step: the product that writes `x` also writes the sum of squares of each + block, so the kernels after it need not read all of `x` for the norm. - **Fewer bytes for a token** (#33): lm_head in Q4_0 (#9) would save about 1.3 ms, after a check of the perplexity. - **Attention at a long context** (#38): about 4 ms of a token at 8,000 positions, above the diff --git a/docs/usage.md b/docs/usage.md new file mode 100644 index 0000000..fcd25e9 --- /dev/null +++ b/docs/usage.md @@ -0,0 +1,245 @@ +# Using the program + +How to install Vx, prepare a model, run the program, use a session, and run the tests. + +## Install Vx + +The program needs a Mac with Apple Silicon for the GPU, and the Vx release that the file +[`VX_VERSION`](../VX_VERSION) names (now v0.0.6). CI tests that release. On a Mac, the Vx toolchain +also needs LLVM 22 and z3 from Homebrew: + +```sh +brew install llvm@22 z3 +curl -fsSL https://vxlang.org/install.sh | VX_VERSION=$(cat VX_VERSION) sh +``` + +The toolchain goes in `~/.vx/current`. The commands below call `vxc`, so put the toolchain on +`PATH`, as the installer says: + +```sh +export PATH="$HOME/.vx/bin:$PATH" +``` + +To install Vx in another folder, give it as `VX_HOME`, and keep `VX_HOME` set: + +```sh +export VX_HOME="$HOME/tools/vx" +curl -fsSL https://vxlang.org/install.sh | sh +export PATH="$VX_HOME/bin:$PATH" +``` + +The commands below then name `$VX_HOME` in place of `~/.vx`, as in +`--machine $VX_HOME/current/fleet/m4-uma.vx`. + +[Getting started](https://vxlang.org/docs/getting-started.html) has the details. On a computer +with no Apple GPU, the same program runs on the CPU. + +## Prepare a model + +The scripts need Python 3.12 or later and the packages of [`requirements.txt`](../requirements.txt), +at the versions that it pins. `check_against_mlx.py` also needs those of +[`requirements-mlx.txt`](../requirements-mlx.txt). The Python of Homebrew takes no packages of its +own, so put them in a virtual environment: + +```sh +python3 -m venv .venv +. .venv/bin/activate +pip install -r requirements.txt +``` + +1. Download a model from Hugging Face, for example + [Qwen2.5-Coder-0.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-Coder-0.5B-Instruct), which + is 1 GB: + + ```sh + hf download Qwen/Qwen2.5-Coder-0.5B-Instruct --local-dir ~/models/Qwen2.5-Coder-0.5B-Instruct + ``` + +1. Convert it into the weight file and the tokenizer file that the Vx program reads: + + ```sh + python3 scripts/convert.py ~/models/Qwen2.5-Coder-0.5B-Instruct qwen-0.5b.vxw + python3 scripts/convert_tokenizer.py ~/models/Qwen2.5-Coder-0.5B-Instruct qwen.vxt + ``` + +1. Generate text with the Vx program, on the GPU: + + ```sh + vxc -O2 src/main.vx --package qwen=src --host default \ + --machine ~/.vx/current/fleet/m4-uma.vx -- qwen-0.5b.vxw \ + --tokenizer qwen.vxt --prompt "def fibonacci(n):" --steps 64 + ``` + + `-O2` optimizes the code that runs on the CPU, which vxc compiles at `-O0` by default. The + kernels are the same, but the prompt is faster: the CPU makes the tensors of a chunk in about + 1 ms in place of about 50 ms for each 100 MB. Use `-O2` for every run that you time. + + `vxc` first warns that it cannot check the memory of some functions with a dynamic shape + (W1029). These warnings are expected. The program then prints the prompt, the text that the + model writes, and the time of a token, about 11 ms on an M4. + + With `--chat`, the prompt is a request to the Instruct model. The program prints only the + reply, and it stops at the end of the reply. `--prompt-file FILE` reads the prompt from a file: + + ```sh + vxc -O2 src/main.vx --package qwen=src --host default \ + --machine ~/.vx/current/fleet/m4-uma.vx -- qwen-0.5b.vxw \ + --tokenizer qwen.vxt --chat --prompt "Write a C++ function that reverses a string." --steps 300 + ``` + + With `--draft 7`, the program checks drafts from the context: the tokens after the longest + earlier match of the last tokens. When the model keeps a draft, several tokens come from one + read of the weights, and the text is the same as without `--draft`. This helps most when the + reply repeats the prompt, as an edit of a file does: about 1.8 times as fast with the 30B + model (`docs/optimizations.md`, entry 14). It needs the 30B model in Q4_0 with the 6-bit + `lm_head` (`scripts/convert.py --q4 --q6-lm-head`), and `--steps` of at least 16. With Qwen3.6, + use `--draft 11`: its rule (`draft_length35` in `src/speculate.vx`) drafts up to 11 tokens. + + With `--mtp 3`, a Qwen3.6 model drafts tokens with its multi-token prediction (MTP) layer, and + checks them as `--draft` does, so the text is the same as without `--mtp`. This helps also when + the reply is new text. A round drafts up to 3 tokens while the model keeps most drafts, and 1 + token otherwise. The drafts come from the 65,536 tokens of the lowest ids; `--mtp-vocab N` + gives another number, a multiple of 8. It needs a weight file with the MTP layer, which + `scripts/convert.py --q4 --q6-lm-head` writes for Qwen3.6-35B-A3B. + + `--mtp 3,5` drafts up to 5 tokens while the model keeps almost all drafts. With + `--mtp 3,5 --draft 11`, a round drafts up to 11 tokens from the context when the context has a + match of 16 tokens, and from the MTP layer otherwise. This helps in edits. + +1. Generate a few tokens with the NumPy reference. It prints the prompt as token ids: + + ```sh + python3 scripts/reference.py qwen-0.5b.vxw \ + --tokenizer ~/models/Qwen2.5-Coder-0.5B-Instruct --prompt "def fibonacci(n):" --steps 8 + ``` + +1. Generate the same tokens with the Vx program. With `--tokens`, the prompt is token ids, and the + program prints the lines of `reference.py`. `--lines` prints the same lines for a text prompt: + + ```sh + vxc -O2 src/main.vx --package qwen=src --host default \ + --machine ~/.vx/current/fleet/m4-uma.vx -- qwen-0.5b.vxw --tokens 750,75698,1445,1648 --steps 8 + vxc -O2 src/main.vx --package qwen=src --host default \ + --machine ~/.vx/current/fleet/m4-uma.vx -- qwen-0.5b.vxw \ + --tokenizer qwen.vxt --prompt "def fibonacci(n):" --lines --steps 8 + ``` + + `compare.py` checks the output of `reference.py` and of the Vx program, when each is saved in a + file: + + ```sh + python3 scripts/compare.py reference.txt vx.txt + ``` + +`make_tiny_model.py` writes a model with the same layers and random weights. It is small enough +for tests that cannot download a real model. With `--moe`, it writes a tiny model with the layers +of Qwen3-Coder-30B-A3B. + +## Sessions and the prompt cache + +`scripts/chat.py` keeps the model and its KV cache between turns. It runs `src/main.vx --session`, +and sends each turn the whole conversation. The session finds the longest prefix of tokens that the +cache holds, and runs only the tokens after it: + +```sh +python3 scripts/convert_tokenizer.py ~/models/Qwen3-Coder-30B-A3B-Instruct qwen3.vxt +python3 scripts/chat.py qwen3-30b-q4.vxw qwen3.vxt --system-file SYSTEM.md --cache system.kv +``` + +With `--cache`, the first session runs the system prompt once and saves its KV cache to the file. +Later sessions load the file, so the system prompt does not run again. A cache file fits only the +model and the weight file that made it. + +vxc does not give its standard input to the program, and it keeps the standard output of the +program until the program ends. So a session reads its requests from one named pipe and writes its +replies to another. The comment at the start of `src/session.vx` describes the requests. + +On an M4 with 32 GB, with a system prompt of the first 8000 characters of the README of that +time, and Qwen3-Coder-30B-A3B in Q4_0: + +| Turn | Prompt | Tokens that ran | Time of the prompt | +| --- | --- | --- | --- | +| The first, with no cache | 2465 tokens | 2465 | 50.0 s | +| The second, in the same session | 2539 tokens | 29 | 2.3 s | +| The first, in a new session that loaded the cache of the system prompt | 2465 tokens | 20 | 2.5 s | + +The KV cache holds f16 values, 98 KB for each token of Qwen3-Coder-30B-A3B, so the cache file of +the 2445 tokens of the system prompt takes 240 MB. With f32 values it took 481 MB, 0.4 s to save +and 1.9 s to load, and the reply after the load was the same text as the reply with no cache. A session +takes about a minute to start, to compile the program and to load the weights. + +[`docs/vx-guides`](vx-guides) has system prompts that teach Qwen3-Coder to write Vx, which +it never learned. Each one is a set of chapters of the Vx book for one kind of program, such as +kernels on the GPU of a Mac, of about 13000 tokens. With `--cache`, it runs once. + +`tests/session.vx` runs a conversation of three turns on the tiny model with +`scripts/chat.py --check`. Each turn must give the text of a fresh run, and a saved cache must give +the same text in a new session. + +## The scripts + +| Script | What it does | +| --- | --- | +| `scripts/convert.py` | Converts a Hugging Face Qwen2, Qwen3 MoE or Qwen3.5 MoE folder into a weight file. | +| `scripts/reference.py` | Computes the logits and the greedy tokens with NumPy, in float32. | +| `scripts/check_against_mlx.py` | Compares `reference.py` with MLX on the same model. | +| `scripts/compare.py` | Compares the output of the Vx program with the output of `reference.py`. | +| `scripts/make_tiny_model.py` | Writes a tiny model with random weights: dense, `--moe`, or `--qwen35` with the layers of Qwen3.6-35B-A3B. | +| `scripts/qwen_weights.py` | Reads and writes the weight file. Its first comment describes the format. | +| `scripts/test_qwen_weights.py` | Tests the f8e4m3, Q4_0 and 6-bit codes, their scales, the quantized weight files and the files of Qwen3.5 MoE models. | +| `scripts/importance.py` | Measures the importance matrix of a bf16 model, for `convert.py --importance`. | +| `scripts/test_importance.py` | Tests `importance.py`. | +| `scripts/convert_tokenizer.py` | Converts a tokenizer.json into a tokenizer file. Its first comment describes the format. | +| `scripts/make_tiny_tokenizer.py` | Writes a tiny tokenizer.json, and texts that test each step of the tokenizer. | +| `scripts/test_tokenizer.py` | Compares the tokenizer in Vx with the `tokenizers` package. | +| `scripts/chat.py` | Chats with a model through a session, with a cache of the system prompt. | +| `scripts/make_vx_guides.py` | Makes the guides of `docs/vx-guides` from the Vx book. | +| `scripts/make_draft_prompts.py` | Writes the 12 code prompts that measure decoding with drafts. | +| `scripts/record_experts.cpp` | Records the greedy output and the experts of every position, with llama.cpp. Its first comment says how to build it. | +| `scripts/simulate_drafts.py` | Replays the recorded outputs as rounds of decoding with drafts, and estimates the speedup of each draft policy. | +| `scripts/test_simulate_drafts.py` | Tests `simulate_drafts.py`. | + +[`examples/`](../examples/README.md) asks the 30B model for programs in Rust, C++ and Python. It +compiles each one and checks its output. + +## The Vx code + +| File | What it does | +| --- | --- | +| `src/weights.vx` | Loads a weight file into GPU memory, for the kernels of `std::nn`. | +| `src/model.vx` | Makes the tensors and the KV cache once, and runs one token through all layers. | +| `src/prefill.vx` | Runs the prompt through all layers in chunks of tokens. | +| `src/attention.vx` | The attention of a generated token, with the positions split among blocks. | +| `src/tokenizer.vx` | Turns text into token ids and token ids into text, with a tokenizer file. | +| `src/session.vx` | Keeps the model and the KV cache, and answers the requests of `scripts/chat.py`. | +| `src/main.vx` | Generates tokens with greedy decoding, and prints text or the lines of `reference.py`. | + +A program imports the modules as `qwen::weights`, `qwen::model`, `qwen::attention`, `qwen::prefill`, +`qwen::tokenizer` and `qwen::session`, with `vxc --package qwen=src`. A program in another folder +names the `src` folder of this repository. + +The tests are in `tests/`. They need the packages of [`requirements-test.txt`](../requirements-test.txt) +(`pip install -r requirements-test.txt`): NumPy, ml_dtypes, and the Python port of `FileCheck`. +A `FileCheck` of LLVM on `PATH` comes first. `tests/run.sh` takes `vxc` and the +machine files from `$VX_HOME/current` when `VX_HOME` is set, else from the `vxc` on `PATH`, else +from `~/.vx/current`: + +```sh +tests/run.sh +``` + +`tests/print_weights.vx` also checks a real model. Its lines must equal those of +`reference.py --tensors`: + +```sh +vxc tests/print_weights.vx --package qwen=src --host default \ + --machine ~/.vx/current/fleet/m4-uma.vx -- qwen-0.5b.vxw +python3 scripts/reference.py qwen-0.5b.vxw --tensors +``` + +## The licenses of the models + +The repository has no model weights or tokenizer files. `scripts/convert.py` and +`scripts/convert_tokenizer.py` make them from a model of Hugging Face, which has its own license: +see the model card, for example +[Qwen3-Coder-30B-A3B-Instruct](https://huggingface.co/Qwen/Qwen3-Coder-30B-A3B-Instruct). diff --git a/docs/weights.md b/docs/weights.md new file mode 100644 index 0000000..1561792 --- /dev/null +++ b/docs/weights.md @@ -0,0 +1,135 @@ +# The weight formats + +The fp8, Q4_0 and 6-bit formats of `scripts/convert.py`, and the measurements of the MoE model. + +## fp8 weights + +`convert.py --fp8` stores each weight matrix as f8e4m3 codes, one byte for each weight, with one f32 +scale for each block of 128 x 128. A weight is the value of its code times the scale of its block. +The norms, the biases and the embedding table stay bf16, so a token reads about half the bytes of +bf16. The Vx program reads an fp8 file like a bf16 file, and runs the fp8 kernels of `std::nn` for +it. + +`reference.py` widens the codes and scales exactly to float32. With `--perplexity`, it measures +how well a model predicts a text. On the first 512 tokens of `scripts/tools/gen_error_index.py` in the Vx repository: + +| Model | bf16 perplexity | fp8 perplexity | Greedy tokens of fp8 | +| --- | --- | --- | --- | +| Qwen2.5-Coder-0.5B-Instruct | 20.054 | 20.030 | the same 64 as bf16 | +| Qwen2.5-Coder-7B-Instruct | 10.072 | 10.085 | the same 64 as bf16 | + +On the fp8 file, the Vx program chose the same 64 greedy tokens as `reference.py`, with each logit +within 6e-05. One token of the 7B model took 95 ms in fp8 and 156 ms in bf16 on a quiet M4, which +is about 10.5 and 6.4 tokens per second. + +## Q4_0 weights + +`convert.py --q4` stores each weight matrix except `lm_head` in the Q4_0 format of llama.cpp. A +row has one f16 scale for each 32 weights, and each weight is a 4-bit code from 0 to 15. The +weight is (code - 8) times its scale. The codes round as llama.cpp rounds them, and a test checks +them against the loop of llama.cpp. For Qwen2.5-Coder-7B-Instruct, the codes and scales of all +197 Q4_0 tensors were the same bits as in the Q4_0 GGUF file that Qwen publishes. `lm_head` is fp8, as llama.cpp also keeps its output matrix +above 4 bits. + +`convert.py --q4 --importance FILE` rounds each group of 32 weights with an importance matrix, as +llama.cpp does with one. `importance.py` measures it: the mean square of each input of each +matrix over a sample text, for each expert on its own tokens. The converter then tries 19 scales +for each group, and keeps the one with the smallest error, where the error of a weight counts as +much as its input matters. A test checks the codes and scales against the loops of llama.cpp. + +`convert.py --q4 --q6-lm-head` stores `lm_head` in 6 bits in place of fp8: a code from 0 to 63 for +each weight, and an f16 scale for each 32 weights of a row. The weight is (code - 32) times its +scale. That is 6.5 bits for each weight, as in the Q6_K of llama.cpp, and the codes round as its +`make_qx_quants` rounds them. The `lm_head` of Qwen3-Coder-30B-A3B is then 253 MB in place of +311 MB, and `src/q6.vx` reads it. See [the MoE model](#the-moe-model) for its cost in perplexity. + +The Vx program reads a Q4_0 file like the others, and runs the Q4_0 kernels of `std::nn` for it. +Of four 4-bit formats, Q4_0 was the closest to bf16 on the 7B model. The measurement is in +[#6](https://github.com/vx-lang/qwen-vx/issues/6#issuecomment-6879596230). + +## The MoE model + +Qwen3-Coder-30B-A3B is 61 GB in bf16, so this Mac runs it in Q4_0, at 17.8 GB: + +```sh +python3 scripts/convert.py --q4 ~/models/Qwen3-Coder-30B-A3B-Instruct qwen3-30b-q4.vxw +vxc -O2 src/main.vx --package qwen=src --host default \ + --machine ~/.vx/current/fleet/m4-uma.vx -- qwen3-30b-q4.vxw --tokens 750,75698,1445,982,257 --steps 64 +``` + +The conversion took 3.4 minutes and 18.6 GB of memory on an M4 with 32 GB. The tokens are +`def fibonacci(n):` and a new line with 4 spaces. The tokenizer of the 30B model gives the same +tokens for that text, so `--tokenizer qwen3.vxt --prompt "$(printf 'def fibonacci(n):\n ')"` is +the same prompt, after `convert_tokenizer.py ~/models/Qwen3-Coder-30B-A3B-Instruct qwen3.vxt`. The Vx program wrote a recursive +and an iterative `fibonacci` in the 64 steps. `reference.py` on the same file chose the same 64 +tokens, with each logit within 5.4e-05. + +The program gives the GPU the pages of the mapped weight file, with no copy. Vx has this since +v0.0.5 ([vx-lang/Vx#3606](https://github.com/vx-lang/Vx/pull/3606)). On +an M4 with 32 GB, the load takes about 10.5 s, and the program has 0.3 GB of private memory at +a short context and 2.1 GB at 8,000 tokens of context. When it copied the weights, the load took +29 to 38 s and 18.9 to 20.4 GB. The file cache keeps one copy of the weights for all the runs, and +macOS can drop those pages when other programs need memory. + +An importance matrix makes the Q4_0 file closer to bf16. `importance.py` needs the bf16 file, and +took 110 minutes for 150 chunks of 512 tokens on an M4 with 32 GB: + +```sh +python3 scripts/convert.py ~/models/Qwen3-Coder-30B-A3B-Instruct qwen3-30b.vxw +python3 scripts/importance.py qwen3-30b.vxw --tokenizer ~/models/Qwen3-Coder-30B-A3B-Instruct \ + --out importance.npz --chunks-per-text 8 TEXT... +python3 scripts/convert.py --q4 --importance importance.npz \ + ~/models/Qwen3-Coder-30B-A3B-Instruct qwen3-30b-q4.vxw +``` + +The sample text below was the first 8 chunks of each of 19 files: + +- `SmallVector.h` and `DenseMap.h` of LLVM 22. +- `argparse.py`, `subprocess.py`, `asyncio/base_events.py`, `http/client.py` and + `pydoc_data/topics.py` of Python 3.13. +- `src/ahocorasick.rs` of aho-corasick 1.1.4, `src/map.rs` of indexmap 2.14.0, `src/expr.rs` of + syn 2.0.118, and `src/parser/parser.rs` of clap_builder 4.6.0. +- `src/runtime/scheduler/multi_thread/worker.rs` and `CHANGELOG.md` of tokio 1.52.3. +- `lib/compress/zstd_compress.c` of zstd 1.5.7, and `lib/commands/ls.js` and + `lib/utils/display.js` of npm 11.16.0. +- `stdlib/std/nn.vx`, `www/book/src/tasks.md` and `www/book/src/ownership.md` of the Vx repository. + +Both programs measured the perplexity as `llama-perplexity -c 512 --chunks 8 --no-escape` +measures it, on three files of the Vx repository that are not in the sample: +`src/dialect/MetalImage.cpp` at vx-lang/Vx@7e3cf6a3, `src/hir/check/calls.rs` at +vx-lang/Vx@4df81bf6, and `docs/parallel_compiler_architecture.md` at vx-lang/Vx@f2415488. + +| Weights | Program | MetalImage.cpp | calls.rs | architecture.md | +| --- | --- | --- | --- | --- | +| bf16 | `reference.py` | 3.6813 | 5.9254 | 5.6790 | +| Q4_0 of `convert.py --q4` | `reference.py` | 3.7290 | 6.0010 | 5.7670 | +| Q4_0 of `convert.py --q4 --importance` | `reference.py` | 3.6881 | 5.9664 | 5.7472 | +| The Q4_0 codes of unsloth in a file of `convert.py --q4` | `reference.py` | 3.6918 | 5.9535 | 5.7516 | +| Q4_0 of unsloth with an importance matrix | `llama-perplexity` | 3.7091 | not measured | not measured | + +The importance matrix removed 86% of the gap to bf16 on `MetalImage.cpp`, 46% on `calls.rs` and +23% on the architecture document. + +`lm_head` in 6 bits (`--q6-lm-head`) costs 0 to 0.25% of perplexity. This table has the Q4_0 file of +`convert.py --q4` with three forms of `lm_head`, all measured again with `reference.py` on +2026-11-17. For the bf16 row, the script took `lm_head` from the bf16 file. + +| `lm_head` | Bytes a token | MetalImage.cpp | calls.rs | +| --- | --- | --- | --- | +| bf16 | 622 MB | 3.7395 | 6.0024 | +| fp8 | 311 MB | 3.7283 | 6.0032 | +| 6 bits | 253 MB | 3.7392 | 6.0177 | + +On `MetalImage.cpp`, fp8 happens to score below bf16, and 6 bits scores the same as bf16. +A scale for each 16 weights in place of 32 gave 3.7393 on `MetalImage.cpp`, and rounding to the +largest weight of each group, without the search of `make_qx_quants`, gave 3.7392, so neither helps. + +The fourth file has the codes and scales of the unsloth file for each matrix that is Q4_0 there. +The `experts_down` of the first 6 layers are Q4_1 there, so they stay ours. The unsloth file also +has `lm_head` in Q6_K and the embedding table in Q4_0. So 3.7091 and 3.6918 differ in the program +and in some weights. Compare files with the same program. + +A token took 28.0 ms in Vx with the cheaper kernel launches of +[#3152](https://github.com/vx-lang/Vx/pull/3152) and [#3165](https://github.com/vx-lang/Vx/pull/3165), +and 24.3 ms in llama.cpp. Each token runs about 477 kernels. The details are in +[#6](https://github.com/vx-lang/qwen-vx/issues/6#issuecomment-6879596324). diff --git a/examples/run.sh b/examples/run.sh index 0040ea6..e47e761 100755 --- a/examples/run.sh +++ b/examples/run.sh @@ -30,7 +30,7 @@ for task in "$@"; do [ -z "${SKILLS:-}" ] || [ -n "$skills" ] || continue ids=$(python3 "$here/harness.py" encode "$tokenizer" "$here/prompts/$task.txt" $skills) mkdir -p "$out/$task$suffix" - vxc src/main.vx --package qwen=src --host default \ + vxc -O2 src/main.vx --package qwen=src --host default \ --machine "$VX_HOME/current/fleet/m4-uma.vx" -- "$weights" --tokens "$ids" --steps 700 \ 2> "$out/$task$suffix/vxc.log" > "$out/$task$suffix/vx.txt" printf '%-24s ' "$task$suffix" diff --git a/requirements-mlx.txt b/requirements-mlx.txt new file mode 100644 index 0000000..3a3afdc --- /dev/null +++ b/requirements-mlx.txt @@ -0,0 +1,4 @@ +# The package of scripts/check_against_mlx.py, which compares scripts/reference.py with MLX on the +# same model. It runs only on Apple Silicon, so CI does not install it. +-r requirements.txt +mlx-lm==0.32.2 diff --git a/requirements-test.txt b/requirements-test.txt new file mode 100644 index 0000000..2e502be --- /dev/null +++ b/requirements-test.txt @@ -0,0 +1,5 @@ +# The Python packages of tests/run.sh: the tests in scripts/test_*.py and FileCheck for the RUN +# lines. CI installs this file. FileCheck of LLVM, when it is on PATH, comes first. +numpy==2.5.5 +ml_dtypes==0.7.0 +filecheck==1.0.6 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..0bbf6d7 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,10 @@ +# The Python packages of the scripts in scripts/: convert.py, reference.py, importance.py and the +# prompt tools. Python 3.12 or later. Install them in a virtual environment: +# +# python3 -m venv .venv && . .venv/bin/activate && pip install -r requirements.txt +# +# The versions are the ones that CI and the published results used. Change one only in a PR that +# says why, and run the tests with the new version. +numpy==2.5.5 +tokenizers==0.23.3 +huggingface_hub==2.4.0 diff --git a/scripts/chat.py b/scripts/chat.py index 0fa48c6..61a375d 100644 --- a/scripts/chat.py +++ b/scripts/chat.py @@ -37,7 +37,7 @@ def vxc_command(weights, tokenizer, *program_args): vxc = os.environ.get("VXC", "vxc") - return [vxc, str(ROOT / "src" / "main.vx"), "--package", f"qwen={ROOT / 'src'}", "--host", "default", + return [vxc, "-O2", str(ROOT / "src" / "main.vx"), "--package", f"qwen={ROOT / 'src'}", "--host", "default", "--machine", str(VX_FLEET / "m4-uma.vx"), "--", str(weights), "--tokenizer", str(tokenizer), *program_args] diff --git a/scripts/check_against_mlx.py b/scripts/check_against_mlx.py index 0778f97..a77b5df 100644 --- a/scripts/check_against_mlx.py +++ b/scripts/check_against_mlx.py @@ -3,11 +3,13 @@ python3 scripts/check_against_mlx.py ~/models/Qwen2.5-Coder-0.5B-Instruct qwen-0.5b.vxw python3 scripts/check_against_mlx.py --tokens 1,2,3 TINY_MOE_DIR tiny-moe.vxw + python3 scripts/check_against_mlx.py --tokens 1,2,3 TINY_QWEN35_DIR tiny-qwen35.vxw MLX reads the Hugging Face folder and runs in float32. reference.py reads the converted weight file. So agreement also checks the converter. The script prints the largest difference of the logits and fails when the greedy tokens differ. It needs the `mlx-lm` package. A folder with no -tokenizer, such as the one of `make_tiny_model.py --moe --hugging-face`, needs --tokens. +tokenizer, such as the one of `make_tiny_model.py --moe --hugging-face` or `--qwen35 --hugging-face`, +needs --tokens. Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. See LICENSE for license information. diff --git a/scripts/convert.py b/scripts/convert.py index a9aa48e..475a1ad 100644 --- a/scripts/convert.py +++ b/scripts/convert.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 -"""Convert a Qwen2 or Qwen3 MoE model folder from Hugging Face into the weight file of the Qwen app. +"""Convert a Qwen2, Qwen3 MoE or Qwen3.5 MoE model folder from Hugging Face into the weight file +of the Qwen app. python3 scripts/convert.py ~/models/Qwen2.5-Coder-0.5B-Instruct qwen-0.5b.vxw python3 scripts/convert.py --fp8 ~/models/Qwen2.5-Coder-0.5B-Instruct qwen-0.5b-fp8.vxw @@ -40,9 +41,90 @@ def convert(model_dir): return convert_tensors(qwen_weights.config_from_hugging_face(model_dir), qwen_weights.read_safetensors(model_dir)) +def one_plus(entry): + """1 + w as f32, for an RMSNorm that multiplies by 1 + w. Each bf16 w gives an exact sum.""" + return "f32", qwen_weights.as_f32(entry) + np.float32(1) + + +def f32(entry): + return "f32", qwen_weights.as_f32(entry) + + +def convert_qwen3_5(config, hf): + """The tensors of the weight file of an arch 1 model, from the tensors of a Hugging Face + Qwen3.5 MoE model. The joined matrices are functions, as in `convert_tensors`.""" + src = "model.language_model." + tensors = {"embed": hf[src + "embed_tokens.weight"], "final_norm": one_plus(hf[src + "norm.weight"])} + if not config["tied_embeddings"]: + tensors["lm_head"] = hf["lm_head.weight"] + for layer in range(config["num_layers"]): + source = f"{src}layers.{layer}." + target = f"layers.{layer}." + tensors[target + "attn_norm"] = one_plus(hf[source + "input_layernorm.weight"]) + if qwen_weights.has_full_attention(config, layer): + full_attention(config, hf, source, target, tensors) + else: + linear = source + "linear_attn." + parts = [hf[linear + f"in_proj_{p}.weight"] for p in ("qkv", "z", "b", "a")] + tensors[target + "linear_in"] = lambda parts=parts: joined(parts) + dtype, conv = hf[linear + "conv1d.weight"] + tensors[target + "conv"] = f32((dtype, conv.reshape(conv.shape[0], conv.shape[2]))) + tensors[target + "neg_A"] = ("f32", -np.exp(qwen_weights.as_f32(hf[linear + "A_log"]))) + tensors[target + "dt_bias"] = f32(hf[linear + "dt_bias"]) + tensors[target + "linear_norm"] = f32(hf[linear + "norm.weight"]) + tensors[target + "linear_out"] = hf[linear + "out_proj.weight"] + experts_mlp(config, hf, source, target, tensors) + if config.get("mtp_layers", 0): + tensors["mtp.embed_norm"] = one_plus(hf["mtp.pre_fc_norm_embedding.weight"]) + tensors["mtp.hidden_norm"] = one_plus(hf["mtp.pre_fc_norm_hidden.weight"]) + tensors["mtp.fc"] = hf["mtp.fc.weight"] + tensors["mtp.final_norm"] = one_plus(hf["mtp.norm.weight"]) + source, target = "mtp.layers.0.", "mtp.layers.0." + tensors[target + "attn_norm"] = one_plus(hf[source + "input_layernorm.weight"]) + full_attention(config, hf, source, target, tensors) + experts_mlp(config, hf, source, target, tensors) + return config, tensors + + +def full_attention(config, hf, source, target, tensors): + """Adds the tensors of the attention of a layer with full attention: Hugging Face names from + `source`, names of the weight file from `target`.""" + heads, head_dim, hidden = config["num_q_heads"], config["head_dim"], config["hidden_size"] + attn = source + "self_attn." + dtype, q_and_gate = hf[attn + "q_proj.weight"] + # q_proj gives each head its query rows and then its gate rows. + q_and_gate = q_and_gate.reshape(heads, 2, head_dim, hidden) + parts = [(dtype, q_and_gate[:, 0].reshape(heads * head_dim, hidden)), hf[attn + "k_proj.weight"], + hf[attn + "v_proj.weight"], (dtype, q_and_gate[:, 1].reshape(heads * head_dim, hidden))] + tensors[target + "qkv"] = lambda parts=parts: joined(parts) + tensors[target + "q_norm"] = one_plus(hf[attn + "q_norm.weight"]) + tensors[target + "k_norm"] = one_plus(hf[attn + "k_norm.weight"]) + tensors[target + "attn_out"] = hf[attn + "o_proj.weight"] + + +def experts_mlp(config, hf, source, target, tensors): + """Adds the tensors of the experts and the shared expert of a layer, as `full_attention`.""" + hidden, experts, moe_inter = config["hidden_size"], config["num_experts"], config["moe_intermediate_size"] + mlp = source + "mlp." + tensors[target + "mlp_norm"] = one_plus(hf[source + "post_attention_layernorm.weight"]) + tensors[target + "router"] = joined([hf[mlp + "gate.weight"], hf[mlp + "shared_expert_gate.weight"]]) + # The experts come as one tensor [experts, 2 * inter, hidden], each expert's gate rows and + # then its up rows, and one [experts, hidden, inter]. Reshapes of a memory map copy nothing. + dtype, gate_up = hf[mlp + "experts.gate_up_proj"] + tensors[target + "experts_gate_up"] = (dtype, gate_up.reshape(experts * 2 * moe_inter, hidden)) + dtype, down = hf[mlp + "experts.down_proj"] + tensors[target + "experts_down"] = (dtype, down.reshape(experts * hidden, moe_inter)) + shared = mlp + "shared_expert." + parts = [hf[shared + p + "_proj.weight"] for p in ("gate", "up")] + tensors[target + "shared_gate_up"] = lambda parts=parts: joined(parts) + tensors[target + "shared_down"] = hf[shared + "down_proj.weight"] + + def convert_tensors(config, hf): """The tensors of the weight file, from a dict of the tensors of a Hugging Face model. The matrices of the experts are functions, so that the file joins them when it writes them.""" + if config.get("arch", 0): + return convert_qwen3_5(config, hf) tensors = {"embed": hf["model.embed_tokens.weight"], "final_norm": hf["model.norm.weight"]} if not config["tied_embeddings"]: tensors["lm_head"] = hf["lm_head.weight"] diff --git a/scripts/convert_tokenizer.py b/scripts/convert_tokenizer.py index 8736d74..a4cb674 100644 --- a/scripts/convert_tokenizer.py +++ b/scripts/convert_tokenizer.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Convert the tokenizer.json of a Qwen2 or Qwen3 model into the tokenizer file of the Qwen app. +"""Convert the tokenizer.json of a Qwen2, Qwen3 or Qwen3.5 model into the tokenizer file of the Qwen app. python3 scripts/convert_tokenizer.py ~/models/Qwen2.5-Coder-0.5B-Instruct qwen.vxt @@ -9,14 +9,15 @@ 1. It splits out each added token, such as <|im_start|>, where the text has it. When two added tokens start at the same place, the longer one wins. 2. It applies Unicode NFC normalization to the text between the added tokens. -3. It splits that text with the pre-tokenizer regex of tokenizer.json (below as PATTERN). +3. It splits that text with the pre-tokenizer regex of tokenizer.json (one of PATTERNS below). 4. It turns each piece into its UTF-8 bytes, and each byte into its token. 5. It merges the pair of neighbor tokens with the lowest merge rank, again and again, until no pair of the piece has a merge. Of equal pairs, the leftmost goes first. This script reads only tokenizer.json, with no package beyond the standard library of Python. The Unicode tables come from `unicodedata`. The classes of the regex equal those of the regex engine -of `tokenizers`. Its NFC step has older data, so the NFC tables leave out the marks and composites +of `tokenizers` when Python has the same Unicode version (UNICODE_VERSION), so the script refuses +another version. Its NFC step has older data, so the NFC tables leave out the marks and composites that the older data lacks (OLD_NFC_MARKS and OLD_NFC_COMPOSITES). `scripts/test_tokenizer.py` checks both. @@ -27,7 +28,8 @@ 2 the number of token ids, n_tokens 3 the number of merges 4 the number of added tokens - 5-7 the number of ranges of letters (\\p{L}), numbers (\\p{N}) and white space (\\s) + 5-7 the number of ranges of letters, numbers (\\p{N}) and white space (\\s). Letters are + \\p{L}, and also the marks (\\p{M}) with the regex of Qwen3.5. 8 the number of code points with a canonical decomposition 9 the number of code points in all those decompositions 10 the number of code points with a canonical combining class above 0 @@ -76,10 +78,17 @@ VERSION = 1 HEADER_WORDS = 32 -# The pre-tokenizer regex of the Qwen2 and Qwen3 tokenizers. `tokenizer.vx` matches it with -# hand-written code, so this script refuses a tokenizer with another one. -PATTERN = (r"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*" - r"|\s*[\r\n]+|\s+(?!\S)|\s+") +# The pre-tokenizer regexes of the Qwen2 and Qwen3 tokenizers, and of the Qwen3.5 tokenizers. +# `tokenizer.vx` matches them with hand-written code, so this script refuses another regex. The +# second regex adds the marks (\p{M}) to the class of letters, so the file has them in the table +# of letters. The optional first character of `[^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+` may be a mark, +# but a mark there gives the same piece as a mark in the class. +QWEN2_PATTERN = (r"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*" + r"|\s*[\r\n]+|\s+(?!\S)|\s+") +QWEN35_PATTERN = (r"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+|\p{N}| ?[^\s\p{L}\p{M}\p{N}]+[\r\n]*" + r"|\s*[\r\n]+|\s+(?!\S)|\s+") +# Whether the class of letters of each regex has the marks. +PATTERNS = {QWEN2_PATTERN: False, QWEN35_PATTERN: True} # The code points of the Unicode property White_Space, which \s matches. WHITE_SPACE = [(0x09, 0x0D), (0x20, 0x20), (0x85, 0x85), (0xA0, 0xA0), (0x1680, 0x1680), @@ -88,6 +97,10 @@ HANGUL_FIRST, HANGUL_LAST = 0xAC00, 0xD7A3 +# The Unicode version of the regex engine of `tokenizers` 0.23. Python 3.14 has it. With another +# version, `unicodedata` puts some new characters in other classes, and the two lists below change. +UNICODE_VERSION = "16.0.0" + # The NFC step of `tokenizers` 0.23 has the data of an old version of Unicode. It gives combining # class 0 to these marks, which later versions added, and it does not compose to these # composites. The tables leave out both, so that NFC here gives the text of `tokenizers`. @@ -122,12 +135,13 @@ def bytes_to_unicode(): def check_structure(t): - """Asserts that tokenizer.json describes the tokenizer that `tokenizer.vx` computes.""" + """Asserts that tokenizer.json describes the tokenizer that `tokenizer.vx` computes. Returns + whether the class of letters of its regex has the marks.""" assert t["normalizer"] == {"type": "NFC"}, f"the normalizer must be NFC, not {t['normalizer']}" pre = t["pre_tokenizer"] assert pre["type"] == "Sequence" and len(pre["pretokenizers"]) == 2, "the pre-tokenizer must be a split and a byte-level step" split, byte_level = pre["pretokenizers"] - assert split["type"] == "Split" and split["pattern"] == {"Regex": PATTERN}, "the pre-tokenizer has another regex" + assert split["type"] == "Split" and split["pattern"].get("Regex") in PATTERNS, "the pre-tokenizer has another regex" assert split["behavior"] == "Isolated" and not split["invert"], "the split must keep each match as a piece" assert byte_level["type"] == "ByteLevel" and not byte_level["add_prefix_space"] and not byte_level["use_regex"], "the byte-level step must add no space and use no regex" model = t["model"] @@ -136,6 +150,7 @@ def check_structure(t): assert not model.get("continuing_subword_prefix") and not model.get("end_of_word_suffix"), "the BPE model must have no prefix or suffix" for a in t["added_tokens"]: assert not (a["normalized"] or a["lstrip"] or a["rstrip"] or a["single_word"]), f"the added token {a['content']} must match the text as it is" + return PATTERNS[split["pattern"]["Regex"]] def ranges(points): @@ -149,8 +164,9 @@ def ranges(points): return out -def unicode_tables(): - """The character classes of the regex, and the tables of NFC.""" +def unicode_tables(marks_are_letters=False): + """The character classes of the regex, and the tables of NFC. With `marks_are_letters`, the + class of letters has the marks (\\p{M}).""" letters, numbers = [], [] decomposed, combining, compositions = {}, {}, {} old_marks = {cp for first, last in OLD_NFC_MARKS for cp in range(first, last + 1)} @@ -159,7 +175,7 @@ def unicode_tables(): continue c = chr(cp) category = unicodedata.category(c) - if category.startswith("L"): + if category.startswith("L") or (marks_are_letters and category.startswith("M")): letters.append(cp) elif category.startswith("N"): numbers.append(cp) @@ -179,9 +195,13 @@ def unicode_tables(): return ranges(letters), ranges(numbers), WHITE_SPACE, decomposed, combining, compositions -def build(t): - """The bytes of the tokenizer file for the parsed tokenizer.json `t`.""" - check_structure(t) +def build(t, any_unicode=False): + """The bytes of the tokenizer file for the parsed tokenizer.json `t`. With `any_unicode`, the + Unicode version of Python may differ from UNICODE_VERSION.""" + assert any_unicode or unicodedata.unidata_version == UNICODE_VERSION, ( + f"this Python has Unicode {unicodedata.unidata_version}, but the tables must have Unicode " + f"{UNICODE_VERSION}, as the tokenizers package has. Run the script with Python 3.14.") + marks_are_letters = check_structure(t) to_char = bytes_to_unicode() to_byte = {c: b for b, c in to_char.items()} vocab = t["model"]["vocab"] @@ -204,7 +224,7 @@ def build(t): merges[(vocab[left] << 20) | vocab[right]] = (rank, vocab[left + right]) merge_pairs = sorted(merges) - letters, numbers, spaces, decomposed, combining, compositions = unicode_tables() + letters, numbers, spaces, decomposed, combining, compositions = unicode_tables(marks_are_letters) starts, blob = [], bytearray() for i in range(n_tokens): starts.append(len(blob)) @@ -262,11 +282,13 @@ def main(): parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("model_dir", help="a Hugging Face model folder with tokenizer.json, or the file itself") parser.add_argument("output", help="the tokenizer file to write") + parser.add_argument("--any-unicode", action="store_true", + help="accept any Unicode version of Python, for a test tokenizer with no new characters") args = parser.parse_args() path = Path(args.model_dir).expanduser() if path.is_dir(): path = path / "tokenizer.json" - data = build(json.loads(path.read_text(encoding="utf-8"))) + data = build(json.loads(path.read_text(encoding="utf-8")), args.any_unicode) Path(args.output).write_bytes(data) print(f"wrote {args.output}: {len(data)} bytes") return 0 diff --git a/scripts/deltanet_chunk.py b/scripts/deltanet_chunk.py new file mode 100644 index 0000000..25c27e9 --- /dev/null +++ b/scripts/deltanet_chunk.py @@ -0,0 +1,56 @@ +# Prints pf_dn_recur of src/prefill35.vx: the DeltaNet state update over the tokens of a chunk, with +# 8 values of v for each SIMD group and the 32 values of S of each lane in variables, so that they +# stay in registers. Run: python3 scripts/deltanet_chunk.py, and put the output in src/prefill35.vx. +P = 8 +L = [] +p = L.append +p("/// The update of the state and the output q . S for the n tokens of the chunk, in order. Block (h, vq)") +p("/// is one SIMD group for values vq * 8 to vq * 8 + 7 of v of head h. Lane l owns values 4 l to 4 l + 3") +p("/// of k, and keeps its 32 values of S in registers for the whole chunk: S is read and written once.") +p("/// For each token and value of v, the operations are those of `deltanet_recur`, in the same order.") +p("/// o[t][h][vq][m] is the output of value vq * 8 + m.") +p("fn pf_dn_recur(o : &mut Tensor, state : &mut Tensor, qn : &Tensor, kn : &Tensor, vv : &Tensor, beta : &Tensor, decay : &Tensor, group : i32, n : i32, v_heads : i32) -> void {") +p(" spawn on(Topology::Device) {") +p(" for h in 0..v_heads across blocks {") +p(" for vq in 0..16 across blocks {") +p(" for s in 0..1 across subgroups {") +p(" for l in 0..32 across lanes(32) {") +p(" let g = h / group;") +p(" let d = 4 * l;") +for m in range(P): + for j in range(4): + p(f" let mut s{m}_{j} = state[h][vq * 8 + {m}][d + {j}];") +p(" for t in 0..n {") +for j in range(4): + p(f" let q{j} = qn[t][g][d + {j}];") +for j in range(4): + p(f" let k{j} = kn[t][g][d + {j}];") +p(" let b = beta[t][h];") +p(" let dec = decay[t][h];") +p(" let mut mine : f32 = 0.0;") +for m in range(P): + for j in range(4): + p(f" let a{m}_{j} = s{m}_{j} * dec;") + p(f" let kv{m} = simd_sum(a{m}_0 * k0 + a{m}_1 * k1 + a{m}_2 * k2 + a{m}_3 * k3);") + p(f" let delta{m} = (vv[t][h][vq * 8 + {m}] - kv{m}) * b;") + for j in range(4): + p(f" s{m}_{j} = a{m}_{j} + k{j} * delta{m};") + p(f" let out{m} = simd_sum(s{m}_0 * q0 + s{m}_1 * q1 + s{m}_2 * q2 + s{m}_3 * q3);") + p(f" if l == {m} {{") + p(f" mine = out{m};") + p(" }") +p(" if l < 8 {") +p(" o[t][h][vq][l] = mine;") +p(" }") +p(" }") +for m in range(P): + for j in range(4): + p(f" state[h][vq * 8 + {m}][d + {j}] = s{m}_{j};") +p(" }") +p(" }") +p(" }") +p(" }") +p(" }") +p(" return;") +p("}") +print("\n".join(L)) diff --git a/scripts/make_tiny_model.py b/scripts/make_tiny_model.py index 6091942..c40c7a6 100644 --- a/scripts/make_tiny_model.py +++ b/scripts/make_tiny_model.py @@ -17,6 +17,13 @@ and go through `convert.py`. --hugging-face also writes them as a Hugging Face folder, for `check_against_mlx.py`. +With --qwen35, the model has the layers of Qwen3.6-35B-A3B, and its head sizes, so that it runs the +same kernels: hidden size 256, 4 layers of which the last has full attention and the others a Gated +DeltaNet, 4 query heads and 2 key-value heads of 256, 2 key heads and 4 value heads of 128 in a +DeltaNet, and 8 experts of which each token uses 2, and a shared expert. Its weights come from +splitmix64 too, and --hugging-face works as for --moe. With --mtp, it also has the MTP layer of +Qwen3.6-35B-A3B, whose weights come after all the others, so that the other weights do not change. + Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. See LICENSE for license information. SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception @@ -79,6 +86,49 @@ "rms_norm_eps": 1e-6, "torch_dtype": "bfloat16", } +QWEN35_TEXT_CONFIG = { + "model_type": "qwen3_5_moe_text", + "hidden_size": 256, + "num_hidden_layers": 4, + "num_attention_heads": 4, + "num_key_value_heads": 2, + "head_dim": 256, + "linear_num_key_heads": 2, + "linear_num_value_heads": 4, + "linear_key_head_dim": 128, + "linear_value_head_dim": 128, + "linear_conv_kernel_dim": 4, + "full_attention_interval": 4, + "layer_types": ["linear_attention"] * 3 + ["full_attention"], + "num_experts": 8, + "num_experts_per_tok": 2, + "moe_intermediate_size": 128, + "shared_expert_intermediate_size": 128, + "norm_topk_prob": True, + "vocab_size": 256, + "max_position_embeddings": 64, + "eos_token_id": 255, + "rms_norm_eps": 1e-6, + "hidden_act": "silu", + "attn_output_gate": True, + "attention_bias": False, + "tie_word_embeddings": False, + "partial_rotary_factor": 0.25, + # The sections of the multimodal RoPE add up to half of the 64 rotary values. + "rope_parameters": {"rope_type": "default", "rope_theta": 10000000, "partial_rotary_factor": 0.25, + "mrope_section": [11, 11, 10], "mrope_interleaved": True}, + "dtype": "bfloat16", +} +# The config.json of the tiny Qwen3.5 MoE model, which keeps the text model in text_config. +QWEN35_CONFIG = { + "architectures": ["Qwen3_5MoeForConditionalGeneration"], + "model_type": "qwen3_5_moe", + "tie_word_embeddings": False, + "text_config": QWEN35_TEXT_CONFIG, +} +# The same, with the MTP layer. +QWEN35_MTP_CONFIG = dict(QWEN35_CONFIG, text_config=dict(QWEN35_TEXT_CONFIG, mtp_num_hidden_layers=1, + mtp_use_dedicated_embeddings=False)) SEED = 0x2545F4914F6CDD1D @@ -190,6 +240,77 @@ def tiny_moe_model(): return tensors +def tiny_qwen35_model(mtp=False): + """The tensors of the tiny Qwen3.5 MoE model, as bf16 bits with their Hugging Face names. `mtp` + adds the MTP layer after all the other tensors.""" + c = QWEN35_TEXT_CONFIG + hidden, head_dim, inter = c["hidden_size"], c["head_dim"], c["moe_intermediate_size"] + heads, kv_heads, experts = c["num_attention_heads"], c["num_key_value_heads"], c["num_experts"] + k_total = c["linear_num_key_heads"] * c["linear_key_head_dim"] + v_heads = c["linear_num_value_heads"] + v_total = v_heads * c["linear_value_head_dim"] + shared = c["shared_expert_intermediate_size"] + src = "model.language_model." + shapes = {src + "embed_tokens.weight": (c["vocab_size"], hidden)} + layers = [(f"{src}layers.{layer}.", kind) for layer, kind in enumerate(c["layer_types"])] + for p, kind in layers + ([("mtp.layers.0.", "full_attention")] if mtp else []): + if p.startswith("mtp."): + # The MTP layer comes after lm_head. + shapes[src + "norm.weight"] = (hidden,) + shapes["lm_head.weight"] = (c["vocab_size"], hidden) + shapes["mtp.pre_fc_norm_embedding.weight"] = (hidden,) + shapes["mtp.pre_fc_norm_hidden.weight"] = (hidden,) + shapes["mtp.fc.weight"] = (hidden, 2 * hidden) + shapes[p + "input_layernorm.weight"] = (hidden,) + if kind == "full_attention": + shapes[p + "self_attn.q_proj.weight"] = (heads * head_dim * 2, hidden) + shapes[p + "self_attn.k_proj.weight"] = (kv_heads * head_dim, hidden) + shapes[p + "self_attn.v_proj.weight"] = (kv_heads * head_dim, hidden) + shapes[p + "self_attn.o_proj.weight"] = (hidden, heads * head_dim) + shapes[p + "self_attn.q_norm.weight"] = (head_dim,) + shapes[p + "self_attn.k_norm.weight"] = (head_dim,) + else: + shapes[p + "linear_attn.in_proj_qkv.weight"] = (2 * k_total + v_total, hidden) + shapes[p + "linear_attn.in_proj_z.weight"] = (v_total, hidden) + shapes[p + "linear_attn.in_proj_b.weight"] = (v_heads, hidden) + shapes[p + "linear_attn.in_proj_a.weight"] = (v_heads, hidden) + shapes[p + "linear_attn.conv1d.weight"] = (2 * k_total + v_total, 1, c["linear_conv_kernel_dim"]) + shapes[p + "linear_attn.A_log"] = (v_heads,) + shapes[p + "linear_attn.dt_bias"] = (v_heads,) + shapes[p + "linear_attn.norm.weight"] = (c["linear_value_head_dim"],) + shapes[p + "linear_attn.out_proj.weight"] = (hidden, v_total) + shapes[p + "post_attention_layernorm.weight"] = (hidden,) + shapes[p + "mlp.gate.weight"] = (experts, hidden) + shapes[p + "mlp.experts.gate_up_proj"] = (experts, 2 * inter, hidden) + shapes[p + "mlp.experts.down_proj"] = (experts, hidden, inter) + shapes[p + "mlp.shared_expert.gate_proj.weight"] = (shared, hidden) + shapes[p + "mlp.shared_expert.up_proj.weight"] = (shared, hidden) + shapes[p + "mlp.shared_expert.down_proj.weight"] = (hidden, shared) + shapes[p + "mlp.shared_expert_gate.weight"] = (1, hidden) + shapes[src + "norm.weight"] = (hidden,) + shapes["lm_head.weight"] = (c["vocab_size"], hidden) + if mtp: + shapes["mtp.norm.weight"] = (hidden,) + # The ranges of the weights whose kind needs another one than (-0.1, 0.1). + ranges = {"conv1d.weight": (-0.5, 0.5), "A_log": (-1.0, 1.0), "dt_bias": (-1.0, 1.0), "linear_attn.norm.weight": (0.9, 1.1)} + tensors, start = {}, 0 + for name, shape in shapes.items(): + count = int(np.prod(shape)) + low, high = next((r for suffix, r in ranges.items() if name.endswith(suffix)), (-0.1, 0.1)) + values = splitmix64_uniform(start, count, low, high).reshape(shape) + if name.endswith("norm.weight") and not name.endswith("linear_attn.norm.weight"): + # The model multiplies by 1 + w. MLX adds the 1 in bf16, so keep 1 + w exact there: + # a multiple of 1/128. + values = np.round(values * 128) / np.float32(128) + elif name.endswith("experts.gate_up_proj") or name.endswith("experts.down_proj"): + values *= np.asarray([EXPERT_SIZES[e % len(EXPERT_SIZES)] for e in range(experts)], dtype=np.float32)[:, None, None] + elif name.endswith("mlp.gate.weight"): + values *= np.float32(ROUTER_SIZE) + start += count + tensors[name] = ("bf16", qwen_weights.f32_to_bf16(values.astype(np.float32))) + return tensors + + def write_hugging_face_folder(directory, config, tensors): """Write config.json and model.safetensors, with bf16 tensors given as uint16 bits.""" os.makedirs(directory, exist_ok=True) @@ -216,19 +337,26 @@ def main(): weight_format.add_argument("--q4", action="store_true", help="store the weight matrices as Q4_0 codes") parser.add_argument("--q6-lm-head", action="store_true", help="with --q4, store lm_head as 6-bit codes, not f8e4m3") parser.add_argument("--moe", action="store_true", help="write the tiny mixture-of-experts model") - parser.add_argument("--hugging-face", metavar="DIR", help="also write the MoE model as a Hugging Face folder") + parser.add_argument("--qwen35", action="store_true", help="write the tiny model with the layers of Qwen3.6-35B-A3B") + parser.add_argument("--mtp", action="store_true", help="with --qwen35, add the MTP layer of Qwen3.6-35B-A3B") + parser.add_argument("--hugging-face", metavar="DIR", help="also write the MoE or Qwen3.5 model as a Hugging Face folder") parser.add_argument("--max-positions", type=int, help="the positions of the model, 64 if not given; the weights do not change") parser.add_argument("--vocab-size", type=int, help="the tokens of the dense model, 256 if not given, for a bigger tokenizer; other weights come out") args = parser.parse_args() - assert not (args.moe and args.vocab_size), "--vocab-size is for the dense model" + assert not (args.moe and args.qwen35), "give --moe or --qwen35, not both" + assert not ((args.moe or args.qwen35) and args.vocab_size), "--vocab-size is for the dense model" assert not args.q6_lm_head or args.q4, "--q6-lm-head needs --q4" - if args.moe: - hf = tiny_moe_model() + assert not args.mtp or args.qwen35, "--mtp needs --qwen35" + if args.moe or args.qwen35: + if args.moe: + hf_config, hf = MOE_CONFIG, tiny_moe_model() + else: + hf_config, hf = (QWEN35_MTP_CONFIG if args.mtp else QWEN35_CONFIG), tiny_qwen35_model(args.mtp) if args.hugging_face: - write_hugging_face_folder(args.hugging_face, MOE_CONFIG, hf) - config, tensors = convert.convert_tensors(qwen_weights.config_from_json(MOE_CONFIG), hf) + write_hugging_face_folder(args.hugging_face, hf_config, hf) + config, tensors = convert.convert_tensors(qwen_weights.config_from_json(hf_config), hf) else: - assert not args.hugging_face, "--hugging-face needs --moe" + assert not args.hugging_face, "--hugging-face needs --moe or --qwen35" config = CONFIG if not args.vocab_size else dict(CONFIG, vocab_size=args.vocab_size) config, tensors = config, tiny_model(config) if args.max_positions: diff --git a/scripts/make_tiny_tokenizer.py b/scripts/make_tiny_tokenizer.py index b4946fb..4a527de 100644 --- a/scripts/make_tiny_tokenizer.py +++ b/scripts/make_tiny_tokenizer.py @@ -116,7 +116,7 @@ def tokenizer_json(): ], "normalizer": {"type": "NFC"}, "pre_tokenizer": {"type": "Sequence", "pretokenizers": [ - {"type": "Split", "pattern": {"Regex": convert_tokenizer.PATTERN}, "behavior": "Isolated", "invert": False}, + {"type": "Split", "pattern": {"Regex": convert_tokenizer.QWEN2_PATTERN}, "behavior": "Isolated", "invert": False}, byte_level, ]}, "post_processor": byte_level, diff --git a/scripts/mlir_kernels/expert_product.py b/scripts/mlir_kernels/expert_product.py index 285d2f7..fb98530 100755 --- a/scripts/mlir_kernels/expert_product.py +++ b/scripts/mlir_kernels/expert_product.py @@ -3,16 +3,23 @@ # See LICENSE for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception """Prints pf_mm_q4_mlir of src/prefill.vx: the Q4_0 product of a chunk as one threadgroup mlir! block. +With --bf16, prints pf_mm_bf16_mlir: the same product for a bf16 matrix, whose weights go to f16. The design is that of llama.cpp's kernel_mul_mm_id (ggml/src/ggml-metal/kernels/mul_mm.metal), MIT License, Copyright (c) 2023-2026 The ggml authors. Edit this script, not the generated MLIR: - python3 scripts/mlir_kernels/expert_product.py + python3 scripts/mlir_kernels/expert_product.py [--bf16] prints the function; replace it in src/prefill.vx. """ import sys mode = 'app' +bf16 = '--bf16' in sys.argv[1:] +# Tokens of a block: 32, or 64 with --t64 (Q4_0 only, for the dense products, with no skip of +# padding). With 64, each subgroup makes 32 tokens x 32 rows. +T = 64 if '--t64' in sys.argv[1:] else 32 +NI = T // 16 # rows of 8 tokens of a subgroup +NA = 4 * NI # sums of a subgroup hint = True ACC = '!gpu.mma_matrix<8x8xf32, "COp">' AOP = '!gpu.mma_matrix<8x8xf16, "AOp">' @@ -20,13 +27,19 @@ L = [] e = L.append name = 'pf_mm_q4_mlir' if mode == 'app' else ('mm_mlir2h' if hint else 'mm_mlir2') -e(f'fn {name}(y : &mut Tensor, w : &Tensor, scales : &Tensor, x : &Tensor, list : &Tensor, bases : &Tensor, stride : i32, rows : i32, cols : i32, tiles : i32) -> void {{') +if bf16: + name = 'pf_mm_bf16_mlir' +if T == 64: + name = 'pf_mm_q4_mlir64' +WT = 'w : &Tensor' if bf16 else 'w : &Tensor, scales : &Tensor' +e(f'fn {name}(y : &mut Tensor, {WT}, x : &Tensor, list : &Tensor, bases : &Tensor, stride : i32, rows : i32, cols : i32, tiles : i32) -> void {{') e(' spawn on(Topology::Device) {') -e(' for rb in 0..rows / 64 across blocks {') -e(' for tb in 0..(tiles + 1) / 2 across blocks {' if mode == 'app' else ' for tb in 0..tiles across blocks {') +e(' for rb in 0..(rows + 63) / 64 across blocks {' if bf16 else ' for rb in 0..rows / 64 across blocks {') +e(f' for tb in 0..(tiles + {T // 16 - 1}) / {T // 16} across blocks {{' if mode == 'app' else ' for tb in 0..tiles across blocks {') e(' let mut sw = unsafe { Tensor::uninit() };') -e(' let mut sx = unsafe { Tensor::uninit() };') -e(' let _d = mlir!( threads : 128, inputs : (%sw = &mut sw : memref<2048xf16, 3>, %sx = &mut sx : memref<1024xf16, 3>, %y = y : memref, %w = w : memref, %sc = scales : memref, %x = x : memref, %list = list : memref, %bases = bases : memref, %stride = stride : i32, %cols = cols : i32, %rb = rb : i32, %tb = tb : i32), returns : i32, dialects : ['+('"arith", "memref", "scf", "gpu", "vector", "vx"' if hint else '"arith", "memref", "scf", "gpu", "vector"')+'], ensures : [writes_only(sw), writes_only(sx), reads_only(w), reads_only(scales), reads_only(x), reads_only(list), reads_only(bases), writes_only(y[tb * 32..tb * 32 + 32][rb * 64..rb * 64 + 64])]) {') +e(f' let mut sx = unsafe {{ Tensor::uninit() }};') +SX = f'memref<{T * 32}xf16, 3>' +e(' let _d = mlir!( threads : 128, inputs : (%sw = &mut sw : memref<2048xf16, 3>, %sx = &mut sx : ' + SX + ', %y = y : memref, ' + ('%w = w : memref, %rows = rows : i32' if bf16 else '%w = w : memref, %sc = scales : memref') + ', %x = x : memref, %list = list : memref, %bases = bases : memref, %stride = stride : i32, %cols = cols : i32, %rb = rb : i32, %tb = tb : i32), returns : i32, dialects : ['+('"arith", "memref", "scf", "gpu", "vector", "vx"' if hint else '"arith", "memref", "scf", "gpu", "vector"')+'], ensures : [writes_only(sw), writes_only(sx), reads_only(w), ' + ('' if bf16 else 'reads_only(scales), ') + 'reads_only(x), reads_only(list), reads_only(bases), writes_only(y[tb * ' + str(T) + '..tb * ' + str(T) + ' + ' + str(T) + '][rb * 64..rb * 64 + 64])]) {') b = lambda s: e(' ' + s) consts = {} def c(n): @@ -46,7 +59,7 @@ def c(n): b('%G = arith.divui %colsi, %k32 : index') b('%WPR = arith.divui %colsi, %k8 : index') if mode == 'app': - b('%tbb = arith.muli %tbi, %k2 : index') + b(f'%tbb = arith.muli %tbi, {c(T // 16)} : index') else: b('%tbb = arith.addi %tbi, %k0 : index') b('%base32 = memref.load %bases[%tbb] : memref') @@ -64,10 +77,20 @@ def c(n): b('%r = arith.addi %rb64, %rl : index') b('%bs = arith.muli %base, %stridei : index') b('%row = arith.addi %bs, %r : index') -b('%rw = arith.muli %row, %WPR : index') -b('%kh2 = arith.muli %kh, %k2 : index') -b('%wbase = arith.addi %rw, %kh2 : index') -b('%sbase = arith.muli %row, %G : index') +if bf16: + # A row past the last reads row 0 of the matrix and gets zeros. + b('%rowsi = arith.index_cast %rows : i32 to index') + b('%rok = arith.cmpi ult, %r, %rowsi : index') + b('%rowc = arith.select %rok, %row, %k0 : index') + b('%rw = arith.muli %rowc, %colsi : index') + b('%kh16 = arith.muli %kh, %k16 : index') + b('%wbase = arith.addi %rw, %kh16 : index') + b('%hz = arith.constant dense<0.0> : vector<4xf16>') +else: + b('%rw = arith.muli %row, %WPR : index') + b('%kh2 = arith.muli %kh, %k2 : index') + b('%wbase = arith.addi %rw, %kh2 : index') + b('%sbase = arith.muli %row, %G : index') b(f'%kh1024 = arith.muli %kh, {c(1024)} : index') b('%swd = arith.addi %kh1024, %rl : index') # sw[(kh * 16 + k) * 64 + rl] # inputs: lane copies 8 columns cl = (l % 4) * 8 of token tl = sg * 8 + l / 4 @@ -76,15 +99,22 @@ def c(n): b('%lm4 = arith.remui %l, %k4 : index') b('%tl = arith.addi %sg8, %l4 : index') b('%cl = arith.muli %lm4, %k8 : index') -b('%tb32 = arith.muli %tbi, %k32 : index') -b('%li = arith.addi %tb32, %tl : index') -b('%from32 = memref.load %list[%li] : memref') -b('%live = arith.cmpi sge, %from32, %zi : i32') -b('%fromc = arith.maxsi %from32, %zi : i32') -b('%from = arith.index_cast %fromc : i32 to index') -b('%tl32 = arith.muli %tl, %k32 : index') -b('%sxd = arith.addi %tl32, %cl : index') -b('%sxd4 = arith.addi %sxd, %k4 : index') +b(f'%tb32 = arith.muli %tbi, {c(T)} : index') # the first token of the block +# With 64 tokens, lane l also copies token tl + 32 (suffix _1). +XS = [''] + [f'_{xi}' for xi in range(1, T // 32)] +for xi, u in enumerate(XS): + tlu = '%tl' + if xi: + b(f'%tl{u} = arith.addi %tl, {c(32 * xi)} : index') + tlu = f'%tl{u}' + b(f'%li{u} = arith.addi %tb32, {tlu} : index') + b(f'%from32{u} = memref.load %list[%li{u}] : memref') + b(f'%live{u} = arith.cmpi sge, %from32{u}, %zi : i32') + b(f'%fromc{u} = arith.maxsi %from32{u}, %zi : i32') + b(f'%from{u} = arith.index_cast %fromc{u} : i32 to index') + b(f'%tl32{u} = arith.muli {tlu}, %k32 : index') + b(f'%sxd{u} = arith.addi %tl32{u}, %cl : index') + b(f'%sxd4{u} = arith.addi %sxd{u}, %k4 : index') b('%shl = arith.constant dense<[0, 4, 8, 12]> : vector<4xi32>') b('%shh = arith.constant dense<[16, 20, 24, 28]> : vector<4xi32>') b('%m15 = arith.constant dense<15> : vector<4xi32>') @@ -93,21 +123,44 @@ def c(n): b('%zf = arith.constant 0.0 : f32') b('%z = gpu.subgroup_mma_constant_matrix %zf : ' + ACC) # the MMA operands of this subgroup: tokens th * 16.., rows rh * 32.. -b(f'%th512 = arith.muli %th, {c(512)} : index') # sx[(th * 16) * 32] +b(f'%th512 = arith.muli %th, {c(T * 16)} : index') # sx[(th * T / 2) * 32] +b(f'%th16 = arith.muli %th, {c(T // 2)} : index') b('%rh32 = arith.muli %rh, %k32 : index') # sw[rh * 32] -accs = ', '.join(f'%a{i} = %z' for i in range(8)) -accty = ', '.join([ACC] * 8) -b(f'%res:8 = scf.for %g = %k0 to %Gl step %k1 iter_args({accs}) -> ({accty}) {{') +# The tokens of an expert come first in its tiles, so when token t of the block is padding, so are +# the tokens after it. A subgroup skips the multiplies of its 8 tokens th * 16 + 8 to + 15 when the +# first of them is padding (busy1 false), and all its multiplies when token th * 16 is padding. +if T == 32: + b('%tf0 = arith.addi %tb32, %th16 : index') + b('%tf1 = arith.addi %tf0, %k8 : index') + for i in range(2): + b(f'%from_t{i} = memref.load %list[%tf{i}] : memref') + b(f'%busy{i} = arith.cmpi sge, %from_t{i}, %zi : i32') +accs = ', '.join(f'%a{i} = %z' for i in range(NA)) +accty = ', '.join([ACC] * NA) +b(f'%res:{NA} = scf.for %g = %k0 to %Gl step %k1 iter_args({accs}) -> ({accty}) {{') d = lambda s: e(' ' + s) -d('%g4 = arith.muli %g, %k4 : index') -d('%wa = arith.addi %wbase, %g4 : index') -d('%q = vector.load %w[%wa] {alignment = 8} : memref, vector<2xi32>') -d('%sa = arith.addi %sbase, %g : index') -d('%s = memref.load %sc[%sa] : memref') -d('%m = arith.mulf %s, %m8 : f16') -d('%sv = vector.broadcast %s : f16 to vector<4xf16>') -d('%mv = vector.broadcast %m : f16 to vector<4xf16>') -for wi in range(2): +if bf16: + # Lane l loads columns kh * 16 to + 15 of its row, as 4 vectors of 4. + d('%g32w = arith.muli %g, %k32 : index') + d('%wa = arith.addi %wbase, %g32w : index') + for wi in range(2): + for hi in range(2): + t = f'{wi}{hi}' + d(f'%wa{t} = arith.addi %wa, {c(wi * 8 + hi * 4)} : index') + d(f'%b{t} = vector.load %w[%wa{t}] {{alignment = 8}} : memref, vector<4xbf16>') + d(f'%we{t} = arith.extf %b{t} : vector<4xbf16> to vector<4xf32>') + d(f'%t{t} = arith.truncf %we{t} : vector<4xf32> to vector<4xf16>') + d(f'%d{t} = arith.select %rok, %t{t}, %hz : vector<4xf16>') +if not bf16: + d('%g4 = arith.muli %g, %k4 : index') + d('%wa = arith.addi %wbase, %g4 : index') + d('%q = vector.load %w[%wa] {alignment = 8} : memref, vector<2xi32>') + d('%sa = arith.addi %sbase, %g : index') + d('%s = memref.load %sc[%sa] : memref') + d('%m = arith.mulf %s, %m8 : f16') + d('%sv = vector.broadcast %s : f16 to vector<4xf16>') + d('%mv = vector.broadcast %m : f16 to vector<4xf16>') +for wi in range(0 if bf16 else 2): d(f'%q{wi} = vector.extract %q[{wi}] : i32 from vector<2xi32>') d(f'%qb{wi} = vector.broadcast %q{wi} : i32 to vector<4xi32>') for hi, sh in enumerate(['%shl', '%shh']): @@ -119,12 +172,13 @@ def c(n): d('%g32 = arith.muli %g, %k32 : index') d('%xc = arith.addi %g32, %cl : index') d('%xc4 = arith.addi %xc, %k4 : index') -d('%x0r = vector.load %x[%from, %xc] {alignment = 16} : memref, vector<4xf32>') -d('%x1r = vector.load %x[%from, %xc4] {alignment = 16} : memref, vector<4xf32>') -d('%x0 = arith.select %live, %x0r, %vz : vector<4xf32>') -d('%x1 = arith.select %live, %x1r, %vz : vector<4xf32>') -d('%h0 = arith.truncf %x0 : vector<4xf32> to vector<4xf16>') -d('%h1 = arith.truncf %x1 : vector<4xf32> to vector<4xf16>') +for u in XS: + d(f'%x0r{u} = vector.load %x[%from{u}, %xc] {{alignment = 16}} : memref, vector<4xf32>') + d(f'%x1r{u} = vector.load %x[%from{u}, %xc4] {{alignment = 16}} : memref, vector<4xf32>') + d(f'%x0{u} = arith.select %live{u}, %x0r{u}, %vz : vector<4xf32>') + d(f'%x1{u} = arith.select %live{u}, %x1r{u}, %vz : vector<4xf32>') + d(f'%h0{u} = arith.truncf %x0{u} : vector<4xf32> to vector<4xf16>') + d(f'%h1{u} = arith.truncf %x1{u} : vector<4xf32> to vector<4xf16>') d('gpu.barrier') for k in range(16): wi, rem = divmod(k, 8) @@ -135,39 +189,60 @@ def c(n): else: d(f'%o{k} = arith.addi %swd, {c(k * 64)} : index') d(f'memref.store %e{k}, %sw[%o{k}] : memref<2048xf16, 3>') -d('vector.store %h0, %sx[%sxd] {alignment = 8} : memref<1024xf16, 3>, vector<4xf16>') -d('vector.store %h1, %sx[%sxd4] {alignment = 8} : memref<1024xf16, 3>, vector<4xf16>') +for u in XS: + d(f'vector.store %h0{u}, %sx[%sxd{u}] {{alignment = 8}} : {SX}, vector<4xf16>') + d(f'vector.store %h1{u}, %sx[%sxd4{u}] {{alignment = 8}} : {SX}, vector<4xf16>') d('gpu.barrier') -prev = [f'%a{i}' for i in range(8)] -for k8 in (0, 8, 16, 24): - if hint: - d('vx.subgroup_schedule_barrier') - for j in range(4): - d(f'%bo{j}_{k8} = arith.addi %rh32, {c(k8 * 64 + j * 8)} : index') - d(f'%mb{j}_{k8} = gpu.subgroup_mma_load_matrix %sw[%bo{j}_{k8}] {{leadDimension = 64 : index}} : memref<2048xf16, 3> -> {BOP}') - if hint: - d('vx.subgroup_schedule_barrier') - for i in range(2): - d(f'%ao{i}_{k8} = arith.addi %th512, {c(i * 8 * 32 + k8)} : index') - d(f'%ma{i}_{k8} = gpu.subgroup_mma_load_matrix %sx[%ao{i}_{k8}] {{leadDimension = 32 : index}} : memref<1024xf16, 3> -> {AOP}') - if hint: - d('vx.subgroup_schedule_barrier') - cur = [] - for i in range(2): +def mma(d, tag, rows): + """The multiplies of a step for the token rows `rows` (0: tokens th * 16 to + 7, 1: + 8 to + 15). + Yields the sums; those of the other rows go through as they are.""" + prev = [f'%a{i}' for i in range(NA)] + for k8 in (0, 8, 16, 24): + if hint: + d('vx.subgroup_schedule_barrier') for j in range(4): - n = i * 4 + j - d(f'%r{n}_{k8} = gpu.subgroup_mma_compute %ma{i}_{k8}, %mb{j}_{k8}, {prev[n]} : {AOP}, {BOP} -> {ACC}') - cur.append(f'%r{n}_{k8}') - prev = cur -d('scf.yield ' + ', '.join(prev) + ' : ' + accty) + d(f'%bo{j}_{k8}{tag} = arith.addi %rh32, {c(k8 * 64 + j * 8)} : index') + d(f'%mb{j}_{k8}{tag} = gpu.subgroup_mma_load_matrix %sw[%bo{j}_{k8}{tag}] {{leadDimension = 64 : index}} : memref<2048xf16, 3> -> {BOP}') + if hint: + d('vx.subgroup_schedule_barrier') + for i in rows: + d(f'%ao{i}_{k8}{tag} = arith.addi %th512, {c(i * 8 * 32 + k8)} : index') + d(f'%ma{i}_{k8}{tag} = gpu.subgroup_mma_load_matrix %sx[%ao{i}_{k8}{tag}] {{leadDimension = 32 : index}} : {SX} -> {AOP}') + if hint: + d('vx.subgroup_schedule_barrier') + cur = list(prev) + for i in rows: + for j in range(4): + n = i * 4 + j + d(f'%r{n}_{k8}{tag} = gpu.subgroup_mma_compute %ma{i}_{k8}{tag}, %mb{j}_{k8}{tag}, {prev[n]} : {AOP}, {BOP} -> {ACC}') + cur[n] = f'%r{n}_{k8}{tag}' + prev = cur + d('scf.yield ' + ', '.join(prev) + ' : ' + accty) +if T == 64: + mma(d, '', tuple(range(NI))) +else: + d0 = d + d1 = lambda s: d0(' ' + s) + d2 = lambda s: d0(' ' + s) + d(f'%mm:8 = scf.if %busy1 -> ({accty}) {{') + mma(d1, 'f', (0, 1)) + d('} else {') + d1(f'%mh:8 = scf.if %busy0 -> ({accty}) {{') + mma(d2, 'h', (0,)) + d1('} else {') + d1(' scf.yield ' + ', '.join(f'%a{i}' for i in range(8)) + ' : ' + accty) + d1('}') + d1('scf.yield ' + ', '.join(f'%mh#{i}' for i in range(8)) + ' : ' + accty) + d('}') + d('scf.yield ' + ', '.join(f'%mm#{i}' for i in range(8)) + ' : ' + accty) b('}') -b('%th16 = arith.muli %th, %k16 : index') b('%yr0 = arith.addi %tb32, %th16 : index') -b('%yr1 = arith.addi %yr0, %k8 : index') +for i in range(1, NI): + b(f'%yr{i} = arith.addi %yr0, {c(8 * i)} : index') b('%yc0 = arith.addi %rb64, %rh32 : index') for j in range(1, 4): b(f'%yc{j} = arith.addi %yc0, {c(8 * j)} : index') -for i in range(2): +for i in range(NI): for j in range(4): b(f'gpu.subgroup_mma_store_matrix %res#{i * 4 + j}, %y[%yr{i}, %yc{j}] {{leadDimension = 0 : index}} : {ACC}, memref') b('macro.yield %tb : i32') diff --git a/scripts/mlir_kernels/gated_flash_attention.py b/scripts/mlir_kernels/gated_flash_attention.py new file mode 100644 index 0000000..4a09f04 --- /dev/null +++ b/scripts/mlir_kernels/gated_flash_attention.py @@ -0,0 +1,220 @@ +#!/usr/bin/env python3 +# Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +# See LICENSE for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""Prints pf_gated_flash_attention of src/prefill35.vx: the gated attention of a chunk of Qwen3.5 and +Qwen3.6 (heads of 256 values) as one threadgroup mlir! block. + +It is scripts/mlir_kernels/flash_attention.py for heads of 256 values, with the output gate +sigmoid(gate) in the last step. The design is that of llama.cpp's kernel_flash_attn_ext +(ggml/src/ggml-metal/kernels/fa_common.metal), MIT License, Copyright (c) 2023-2026 The ggml +authors. Edit this script, not the generated MLIR: + + python3 scripts/mlir_kernels/gated_flash_attention.py + +prints the function; replace it in src/prefill35.vx. +""" +D = 256 +ACC = '!gpu.mma_matrix<8x8xf32, "COp">' +AOP = '!gpu.mma_matrix<8x8xf16, "AOp">' +BOP = '!gpu.mma_matrix<8x8xf16, "BOp">' +KV = 'memref>' +SQ = f'memref<{8 * D}xf16, 3>' +SO = f'memref<{8 * D}xf32, 3>' +L = [] +e = L.append +e(f'/// y[t][h * {D} + d] = the attention of query head h of token t (at position start + t) over the') +e('/// positions up to start + t, times sigmoid(qkvg[t][gate_at + h * 256 + d]), for t below n: the') +e('/// gated attention of `gated_attention`. A threadgroup does 8 tokens of one query head, in steps of 64') +e('/// positions, as `pf_flash_attention` and llama.cpp\'s kernel_flash_attn_ext. The caches are') +e(f'/// [position, kv_heads, {D}] f16, with a multiple of 64 positions. K and V go from the cache straight') +e('/// into simdgroup matrices, K transposed; Q (as f16), the scores, the weights (as f16) and the sums') +e('/// of the 8 tokens are in shared memory. The softmax is online, in all the lanes of a subgroup.') +e('///') +e('/// The design is that of llama.cpp (ggml/src/ggml-metal/kernels/fa_common.metal), MIT License,') +e('/// Copyright (c) 2023-2026 The ggml authors.') +e('///') +e('/// scripts/mlir_kernels/gated_flash_attention.py writes this function: change that script, not the') +e('/// MLIR.') +e('fn pf_gated_flash_attention(y : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, qkvg : &Tensor, start : i32, n : i32, q_heads : i32, group : i32, gate_at : i32, scale : f32) -> void {') +e(f' assert(q.extent(2) == {D} && k_cache.extent(2) == {D} && k_cache.extent(0) % 64 == 0 && start + n <= k_cache.extent(0), "pf_gated_flash_attention: heads of {D} values, and a KV cache of a multiple of 64 positions");') +e(' spawn on(Topology::Device) {') +e(' for qb in 0..(n + 7) / 8 across blocks {') +e(' for h in 0..q_heads across blocks {') +e(f' let mut sq = unsafe {{ Tensor::uninit() }};') +e(f' let mut so = unsafe {{ Tensor::uninit() }};') +e(' let mut ss = unsafe { Tensor::uninit() };') +e(' let mut sp = unsafe { Tensor::uninit() };') +e(f' let _d = mlir!( threads : 128, inputs : (%sq = &mut sq : {SQ}, %so = &mut so : {SO}, %ss = &mut ss : memref<512xf32, 3>, %sp = &mut sp : memref<512xf16, 3>, %y = y : memref, %q = q : memref, %k3 = k_cache : memref, %v3 = v_cache : memref, %qkvg = qkvg : memref, %start = start : i32, %n = n : i32, %group = group : i32, %gate_at = gate_at : i32, %scale = scale : f32, %qb = qb : i32, %h = h : i32), returns : i32, dialects : ["arith", "memref", "scf", "gpu", "vector", "math"], ensures : [writes_only(sq), writes_only(so), writes_only(ss), writes_only(sp), reads_only(q), reads_only(k_cache), reads_only(v_cache), reads_only(qkvg), writes_only(y[qb * 8..qb * 8 + 8][h * {D}..h * {D} + {D}])]) {{') +b = lambda s: e(' ' + s) +for c in [0, 1, 2, 4, 8, 12, 16, 32, 64, D]: + b(f'%c{c} = arith.constant {c} : index') +b('%tid = gpu.thread_id x') +b('%sg = arith.divui %tid, %c32 : index') +b('%l = arith.remui %tid, %c32 : index') +b('%qbi = arith.index_cast %qb : i32 to index') +b('%hi = arith.index_cast %h : i32 to index') +b('%ni = arith.index_cast %n : i32 to index') +b('%starti = arith.index_cast %start : i32 to index') +b('%groupi = arith.index_cast %group : i32 to index') +b('%gatei = arith.index_cast %gate_at : i32 to index') +b('%g = arith.divui %hi, %groupi : index') +b(f'%gD = arith.muli %g, %c{D} : index') +b('%P = memref.dim %k3, %c0 : memref') +b('%KH = memref.dim %k3, %c1 : memref') +b(f'%Wd = arith.muli %KH, %c{D} : index') +b(f'%k = memref.reinterpret_cast %k3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to {KV}') +b(f'%v = memref.reinterpret_cast %v3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to {KV}') +b('%t0 = arith.muli %qbi, %c8 : index') +# Q: thread loads 16 floats of row j = tid / 16, columns (tid % 16) * 16, as f16 into sq; zeros so +b('%qj = arith.divui %tid, %c16 : index') +b('%qm = arith.remui %tid, %c16 : index') +b('%qc = arith.muli %qm, %c16 : index') +b('%qt = arith.addi %t0, %qj : index') +b('%nm1 = arith.subi %ni, %c1 : index') +b('%qtc = arith.minui %qt, %nm1 : index') +b('%qlive = arith.cmpi ult, %qt, %ni : index') +b('%vz4 = arith.constant dense<0.0> : vector<4xf32>') +b(f'%sqo = arith.muli %qj, %c{D} : index') +b('%sqa = arith.addi %sqo, %qc : index') +for i in range(4): + b(f'%qc{i} = arith.addi %qc, %c{4 * i} : index') + b(f'%sq{i} = arith.addi %sqa, %c{4 * i} : index') + b(f'%q{i}r = vector.load %q[%qtc, %hi, %qc{i}] : memref, vector<4xf32>') + b(f'%q{i} = arith.select %qlive, %q{i}r, %vz4 : vector<4xf32>') + b(f'%q{i}h = arith.truncf %q{i} : vector<4xf32> to vector<4xf16>') + b(f'vector.store %q{i}h, %sq[%sq{i}] : {SQ}, vector<4xf16>') + b(f'vector.store %vz4, %so[%sq{i}] : {SO}, vector<4xf32>') +b('gpu.barrier') +# the positions: up to the last query of the tile +b('%tl = arith.addi %t0, %c8 : index') +b('%tlc = arith.minui %tl, %ni : index') +b('%lastq = arith.subi %tlc, %c1 : index') +b('%lastp = arith.addi %starti, %lastq : index') +b('%nblk0 = arith.divui %lastp, %c64 : index') +b('%nblk = arith.addi %nblk0, %c1 : index') +# rows of this simdgroup: j0 = sg, j1 = sg + 4; query positions +b('%j0 = arith.addi %sg, %c0 : index') +b('%j1 = arith.addi %sg, %c4 : index') +for jj in range(2): + b(f'%qt{jj} = arith.addi %t0, %j{jj} : index') + b(f'%qp{jj} = arith.addi %starti, %qt{jj} : index') +b('%neg = arith.constant -3.0e38 : f32') +b('%zero = arith.constant 0.0 : f32') +b('%l2 = arith.muli %l, %c2 : index') +b('%l8 = arith.muli %l, %c8 : index') +b('%zacc = gpu.subgroup_mma_constant_matrix %zero : ' + ACC) +b('%st:4 = scf.for %kb = %c0 to %nblk step %c1 iter_args(%M0 = %neg, %S0 = %zero, %M1 = %neg, %S1 = %zero) -> (f32, f32, f32, f32) {') +c = lambda s: e(' ' + s) +d = lambda s: e(' ' + s) +c('%p0 = arith.muli %kb, %c64 : index') +c('%sg8 = arith.muli %sg, %c8 : index') +# Q K^T: simdgroup sg makes the 8 x 8 score tiles at key columns 8 sg and 8 sg + 32 +for nc in range(2): + c(f'%kc{nc} = arith.addi %sg8, %c{32 * nc} : index') + c(f'%kp{nc} = arith.addi %p0, %kc{nc} : index') + c(f'%qk{nc} = scf.for %i = %c0 to %c{D // 8} step %c1 iter_args(%a = %zacc) -> ({ACC}) {{') + d('%d0 = arith.muli %i, %c8 : index') + d(f'%mq = gpu.subgroup_mma_load_matrix %sq[%d0] {{leadDimension = {D} : index}} : {SQ} -> {AOP}') + d('%kd = arith.addi %gD, %d0 : index') + d(f'%mk = gpu.subgroup_mma_load_matrix %k[%kp{nc}, %kd] {{leadDimension = 0 : index, transpose}} : {KV} -> {BOP}') + d(f'%a2 = gpu.subgroup_mma_compute %mq, %mk, %a : {AOP}, {BOP} -> {ACC}') + d(f'scf.yield %a2 : {ACC}') + c('}') + c(f'gpu.subgroup_mma_store_matrix %qk{nc}, %ss[%kc{nc}] {{leadDimension = 64 : index}} : {ACC}, memref<512xf32, 3>') +c('gpu.barrier') +# online softmax: rows j0, j1 of this simdgroup; lane l takes columns 2l, 2l + 1 +outs = [] +for jj in range(2): + c(f'%r{jj} = arith.muli %j{jj}, %c64 : index') + c(f'%ia{jj} = arith.addi %r{jj}, %l2 : index') + c(f'%ib{jj} = arith.addi %ia{jj}, %c1 : index') + c(f'%sa{jj}r = memref.load %ss[%ia{jj}] : memref<512xf32, 3>') + c(f'%sb{jj}r = memref.load %ss[%ib{jj}] : memref<512xf32, 3>') + c(f'%sa{jj}s = arith.mulf %sa{jj}r, %scale : f32') + c(f'%sb{jj}s = arith.mulf %sb{jj}r, %scale : f32') + c(f'%pa{jj} = arith.addi %p0, %l2 : index') + c(f'%pb{jj} = arith.addi %pa{jj}, %c1 : index') + c(f'%oka{jj} = arith.cmpi ule, %pa{jj}, %qp{jj} : index') + c(f'%okb{jj} = arith.cmpi ule, %pb{jj}, %qp{jj} : index') + c(f'%sa{jj} = arith.select %oka{jj}, %sa{jj}s, %neg : f32') + c(f'%sb{jj} = arith.select %okb{jj}, %sb{jj}s, %neg : f32') + c(f'%mx{jj} = arith.maxnumf %sa{jj}, %sb{jj} : f32') + c(f'%bm{jj} = gpu.subgroup_reduce maxnumf %mx{jj} : (f32) -> f32') + c(f'%Mn{jj} = arith.maxnumf %M{jj}, %bm{jj} : f32') + c(f'%dm{jj} = arith.subf %M{jj}, %Mn{jj} : f32') + c(f'%ms{jj} = math.exp %dm{jj} : f32') + c(f'%ea{jj} = arith.subf %sa{jj}, %Mn{jj} : f32') + c(f'%eb{jj} = arith.subf %sb{jj}, %Mn{jj} : f32') + c(f'%xa{jj} = math.exp %ea{jj} : f32') + c(f'%xb{jj} = math.exp %eb{jj} : f32') + c(f'%xs{jj} = arith.addf %xa{jj}, %xb{jj} : f32') + c(f'%bs{jj} = gpu.subgroup_reduce add %xs{jj} : (f32) -> f32') + c(f'%Ss{jj} = arith.mulf %S{jj}, %ms{jj} : f32') + c(f'%Sn{jj} = arith.addf %Ss{jj}, %bs{jj} : f32') + c(f'%ha{jj} = arith.truncf %xa{jj} : f32 to f16') + c(f'%hb{jj} = arith.truncf %xb{jj} : f32 to f16') + c(f'memref.store %ha{jj}, %sp[%ia{jj}] : memref<512xf16, 3>') + c(f'memref.store %hb{jj}, %sp[%ib{jj}] : memref<512xf16, 3>') + # rescale this row of O: lane l takes 8 values + c(f'%or{jj} = arith.muli %j{jj}, %c{D} : index') + c(f'%oi{jj} = arith.addi %or{jj}, %l8 : index') + c(f'%oj{jj} = arith.addi %oi{jj}, %c4 : index') + c(f'%msv{jj} = vector.broadcast %ms{jj} : f32 to vector<4xf32>') + for half, idx in (('a', f'%oi{jj}'), ('b', f'%oj{jj}')): + c(f'%ov{jj}{half} = vector.load %so[{idx}] : {SO}, vector<4xf32>') + c(f'%ow{jj}{half} = arith.mulf %ov{jj}{half}, %msv{jj} : vector<4xf32>') + c(f'vector.store %ow{jj}{half}, %so[{idx}] : {SO}, vector<4xf32>') + outs += [f'%Mn{jj}', f'%Sn{jj}'] +c('gpu.barrier') +# P V: simdgroup sg owns the output columns 8 sg + 32 ii +for ii in range(D // 32): + c(f'%dv{ii}c = arith.constant {32 * ii} : index') + c(f'%dv{ii} = arith.addi %sg8, %dv{ii}c : index') + c(f'%o{ii}i = gpu.subgroup_mma_load_matrix %so[%dv{ii}] {{leadDimension = {D} : index}} : {SO} -> {ACC}') + c(f'%vd{ii} = arith.addi %gD, %dv{ii} : index') + c(f'%o{ii} = scf.for %kk = %c0 to %c8 step %c1 iter_args(%o = %o{ii}i) -> ({ACC}) {{') + d('%k8 = arith.muli %kk, %c8 : index') + d(f'%mp = gpu.subgroup_mma_load_matrix %sp[%k8] {{leadDimension = 64 : index}} : memref<512xf16, 3> -> {AOP}') + d('%vp = arith.addi %p0, %k8 : index') + d(f'%mv = gpu.subgroup_mma_load_matrix %v[%vp, %vd{ii}] {{leadDimension = 0 : index}} : {KV} -> {BOP}') + d(f'%onx = gpu.subgroup_mma_compute %mp, %mv, %o : {AOP}, {BOP} -> {ACC}') + d(f'scf.yield %onx : {ACC}') + c('}') + c(f'gpu.subgroup_mma_store_matrix %o{ii}, %so[%dv{ii}] {{leadDimension = {D} : index}} : {ACC}, {SO}') +c('gpu.barrier') +c('scf.yield ' + ', '.join(outs) + ' : f32, f32, f32, f32') +b('}') +# epilogue: the rows of this simdgroup, divided by their sums, times sigmoid of the gate +b(f'%hD = arith.muli %hi, %c{D} : index') +b('%gh = arith.addi %gatei, %hD : index') +b('%one = arith.constant 1.0 : f32') +b('%one4 = arith.constant dense<1.0> : vector<4xf32>') +for jj in range(2): + b(f'%inv{jj} = arith.divf %one, %st#{2 * jj + 1} : f32') + b(f'%iv{jj} = vector.broadcast %inv{jj} : f32 to vector<4xf32>') + b(f'%fr{jj} = arith.muli %j{jj}, %c{D} : index') + b(f'%live{jj} = arith.cmpi ult, %qt{jj}, %ni : index') + b(f'scf.if %live{jj} {{') + for half, off in (('a', 0), ('b', 4)): + b(f' %fl{jj}{half} = arith.addi %l8, %c{off} : index') + b(f' %fi{jj}{half} = arith.addi %fr{jj}, %fl{jj}{half} : index') + b(f' %fv{jj}{half} = vector.load %so[%fi{jj}{half}] : {SO}, vector<4xf32>') + b(f' %fw{jj}{half} = arith.mulf %fv{jj}{half}, %iv{jj} : vector<4xf32>') + b(f' %gi{jj}{half} = arith.addi %gh, %fl{jj}{half} : index') + b(f' %gv{jj}{half} = vector.load %qkvg[%qt{jj}, %gi{jj}{half}] : memref, vector<4xf32>') + b(f' %gn{jj}{half} = arith.negf %gv{jj}{half} : vector<4xf32>') + b(f' %ge{jj}{half} = math.exp %gn{jj}{half} : vector<4xf32>') + b(f' %gd{jj}{half} = arith.addf %ge{jj}{half}, %one4 : vector<4xf32>') + b(f' %fg{jj}{half} = arith.divf %fw{jj}{half}, %gd{jj}{half} : vector<4xf32>') + b(f' %yc{jj}{half} = arith.addi %hD, %fl{jj}{half} : index') + b(f' vector.store %fg{jj}{half}, %y[%qt{jj}, %yc{jj}{half}] : memref, vector<4xf32>') + b('}') +b('macro.yield %qb : i32') +e(' };') +e(' }') +e(' }') +e(' }') +e(' return;') +e('}') +print('\n'.join(L)) diff --git a/scripts/mlir_kernels/round_attention.py b/scripts/mlir_kernels/round_attention.py deleted file mode 100644 index 942a4b4..0000000 --- a/scripts/mlir_kernels/round_attention.py +++ /dev/null @@ -1,168 +0,0 @@ -#!/usr/bin/env python3 -# Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. -# See LICENSE for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -"""Prints the kernels of `round_attention` in src/round.vx: the attention of n positions in a row, at -start to start + n - 1, as mlir! blocks. - -Each query gets the result of `vec_attention` (src/attention.vx) bit for bit. A block does the same -work for each of its n queries that the block of `vec_attention_parts` does for one, in the same -order, but it reads each row of K and V once for all of them. A query skips the blocks of 32 -positions after its own position, and a row after its position gets the score -3e38 and so the -weight 0, as in `vec_attention_parts`. The rows after the last query are not read. -round_attention_merge, which merges the parts, is Vx code in src/round.vx. - - python3 scripts/mlir_kernels/round_attention.py - -prints the functions; replace them in src/round.vx. -""" -KV = 'memref>' -MAX_N = 8 -L = [] -e = L.append - - -def parts(n): - """The kernel of the parts for n queries.""" - e('') - e(f'/// `vec_attention_parts` for {n} queries in a row: query t is at position pos + t, in q[t0 + t], and its part') - e('/// w goes to part[h][w][132 (t0 + t) ..].') - e(f'fn round_attention_parts_{n}(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, t0 : i32, q_heads : i32, group : i32, nwg : i32, scale : f32) -> void {{') - e(' spawn on(Topology::Device) {') - e(' for h in 0..q_heads across blocks {') - e(' for w in 0..nwg across blocks {') - e(' let g = h / group;') - e(' let _d = mlir!( threads : 32, inputs : (%part = part : memref, %q = q : memref, %k3 = k_cache : memref, %v3 = v_cache : memref, %pos = pos : i32, %t0 = t0 : i32, %nwg = nwg : i32, %scale = scale : f32, %h = h : i32, %w = w : i32, %g = g : i32), returns : i32, dialects : ["arith", "memref", "scf", "gpu", "vector", "math"], ensures : [reads_only(q), reads_only(k_cache), reads_only(v_cache), writes_only(part[h][w])]) {') - b = lambda s: e(' ' + s) - for c in [0, 1, 4, 32, 128, 129, 132]: - b(f'%c{c} = arith.constant {c} : index') - b('%c32i = arith.constant 32 : i32') - b('%neg = arith.constant -3.0e38 : f32') - b('%zero = arith.constant 0.0 : f32') - b('%vz4 = arith.constant dense<0.0> : vector<4xf32>') - b('%l = gpu.thread_id x') - b('%l4 = arith.muli %l, %c4 : index') - for v in ['h', 'w', 'g', 'pos', 'nwg', 't0']: - b(f'%{v}i = arith.index_cast %{v} : i32 to index') - b('%g128 = arith.muli %gi, %c128 : index') - b('%kd = arith.addi %g128, %l4 : index') - b('%P = memref.dim %k3, %c0 : memref') - b('%KH = memref.dim %k3, %c1 : memref') - b('%Wd = arith.muli %KH, %c128 : index') - b(f'%k = memref.reinterpret_cast %k3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to {KV}') - b(f'%v = memref.reinterpret_cast %v3 to offset: [0], sizes: [%P, %Wd], strides: [%Wd, 1] : memref to {KV}') - b('%scv = vector.broadcast %scale : f32 to vector<4xf32>') - for t in range(n): - # the position of query t, its blocks of 32 positions, and its q times the scale - b(f'%ct{t} = arith.constant {t} : index') - b(f'%pos{t} = arith.addi %posi, %ct{t} : index') - b(f'%n{t} = arith.addi %pos{t}, %c32 : index') - b(f'%chunks{t} = arith.divui %n{t}, %c32 : index') - b(f'%qt{t} = arith.addi %t0i, %ct{t} : index') - b(f'%qv{t} = vector.load %q[%qt{t}, %hi, %l4] {{alignment = 16}} : memref, vector<4xf32>') - b(f'%qs{t} = arith.mulf %qv{t}, %scv : vector<4xf32>') - last = n - 1 - init = ', '.join(f'%M{t} = %neg, %S{t} = %zero, %o{t} = %vz4' for t in range(n)) - types = ', '.join('f32, f32, vector<4xf32>' for _ in range(n)) - b(f'%st:{3 * n} = scf.for %ic = %wi to %chunks{last} step %nwgi iter_args({init}) -> ({types}) {{') - c = lambda s: e(' ' + s) - d = lambda s: e(' ' + s) - c('%r0 = arith.muli %ic, %c32 : index') - # the scores of rows r0 to r0 + 31 for each query; lane cc keeps the scores of row r0 + cc. A row past - # the last position reads the row of the last position. - minit = ', '.join(f'%m{t} = %neg' for t in range(n)) - c(f'%my:{n} = scf.for %cc = %c0 to %c32 step %c1 iter_args({minit}) -> ({", ".join("f32" for _ in range(n))}) {{') - d('%row = arith.addi %r0, %cc : index') - d(f'%rowc = arith.minui %row, %pos{last} : index') - d(f'%kh = vector.load %k[%rowc, %kd] {{alignment = 8}} : {KV}, vector<4xf16>') - d('%kf = arith.extf %kh : vector<4xf16> to vector<4xf32>') - d('%mine = arith.cmpi eq, %cc, %l : index') - for t in range(n): - d(f'%pr{t} = arith.mulf %kf, %qs{t} : vector<4xf32>') - d(f'%pl{t} = vector.reduction , %pr{t} : vector<4xf32> into f32') - d(f'%sc{t} = gpu.subgroup_reduce add %pl{t} : (f32) -> f32') - d(f'%live{t} = arith.cmpi ule, %row, %pos{t} : index') - d(f'%scm{t} = arith.select %live{t}, %sc{t}, %neg : f32') - d(f'%mm{t} = arith.select %mine, %scm{t}, %m{t} : f32') - d(f'scf.yield {", ".join(f"%mm{t}" for t in range(n))} : {", ".join("f32" for _ in range(n))}') - c('}') - # the online softmax of each query that this block of positions reaches; p is 0 for the others, so - # that the sum of V leaves them as they are - for t in range(n): - c(f'%act{t} = arith.cmpi ult, %ic, %chunks{t} : index') - c(f'%u{t}:4 = scf.if %act{t} -> (f32, f32, vector<4xf32>, f32) {{') - d(f'%bm{t} = gpu.subgroup_reduce maxnumf %my#{t} : (f32) -> f32') - d(f'%Mn{t} = arith.maxnumf %M{t}, %bm{t} : f32') - d(f'%dm{t} = arith.subf %M{t}, %Mn{t} : f32') - d(f'%ms{t} = math.exp %dm{t} : f32') - d(f'%dp{t} = arith.subf %my#{t}, %Mn{t} : f32') - d(f'%p{t} = math.exp %dp{t} : f32') - d(f'%bs{t} = gpu.subgroup_reduce add %p{t} : (f32) -> f32') - d(f'%Ss{t} = arith.mulf %S{t}, %ms{t} : f32') - d(f'%Sn{t} = arith.addf %Ss{t}, %bs{t} : f32') - d(f'%msv{t} = vector.broadcast %ms{t} : f32 to vector<4xf32>') - d(f'%ox{t} = arith.mulf %o{t}, %msv{t} : vector<4xf32>') - d(f'scf.yield %Mn{t}, %Sn{t}, %ox{t}, %p{t} : f32, f32, vector<4xf32>, f32') - c('} else {') - d(f'scf.yield %M{t}, %S{t}, %o{t}, %zero : f32, f32, vector<4xf32>, f32') - c('}') - # the sum of V: the weight of row r0 + cc for query t is in lane cc - oinit = ', '.join(f'%oa{t} = %u{t}#2' for t in range(n)) - vtypes = ', '.join('vector<4xf32>' for _ in range(n)) - c(f'%ov:{n} = scf.for %cc = %c0 to %c32 step %c1 iter_args({oinit}) -> ({vtypes}) {{') - d('%row = arith.addi %r0, %cc : index') - d(f'%rowc = arith.minui %row, %pos{last} : index') - d(f'%vh = vector.load %v[%rowc, %kd] {{alignment = 8}} : {KV}, vector<4xf16>') - d('%vf = arith.extf %vh : vector<4xf16> to vector<4xf32>') - d('%cci = arith.index_cast %cc : index to i32') - for t in range(n): - d(f'%pc{t}, %pv{t} = gpu.shuffle idx %u{t}#3, %cci, %c32i : f32') - d(f'%pcv{t} = vector.broadcast %pc{t} : f32 to vector<4xf32>') - d(f'%on{t} = vector.fma %vf, %pcv{t}, %oa{t} : vector<4xf32>') - d(f'scf.yield {", ".join(f"%on{t}" for t in range(n))} : {vtypes}') - c('}') - out = ', '.join(f'%u{t}#0, %u{t}#1, %ov#{t}' for t in range(n)) - c(f'scf.yield {out} : {types}') - b('}') - b('%lane0 = arith.cmpi eq, %l, %c0 : index') - for t in range(n): - b(f'%base{t} = arith.muli %qt{t}, %c132 : index') - b(f'%at{t} = arith.addi %base{t}, %l4 : index') - b(f'vector.store %st#{3 * t + 2}, %part[%hi, %wi, %at{t}] : memref, vector<4xf32>') - b(f'%am{t} = arith.addi %base{t}, %c128 : index') - b(f'%as{t} = arith.addi %base{t}, %c129 : index') - b('scf.if %lane0 {') - b(f' memref.store %st#{3 * t}, %part[%hi, %wi, %am{t}] : memref') - b(f' memref.store %st#{3 * t + 1}, %part[%hi, %wi, %as{t}] : memref') - b('}') - b('macro.yield %h : i32') - e(' };') - e(' }') - e(' }') - e(' }') - e(' return;') - e('}') - - -def dispatch(): - """Calls the kernel of the parts for n queries.""" - e('') - e(f'/// The parts of queries t0 to t0 + n - 1, with the kernel for n queries. n is 1 to {MAX_N}.') - e('fn round_attention_parts(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, t0 : i32, n : i32, q_heads : i32, group : i32, nwg : i32, scale : f32) -> void {') - e(f' assert(n >= 1 && n <= {MAX_N}, "round_attention_parts: n must be 1 to {MAX_N}");') - for n in range(1, MAX_N + 1): - word = 'if' if n == 1 else '} else if' - if n == MAX_N: - e(' } else {') - else: - e(f' {word} n == {n} {{') - e(f' round_attention_parts_{n}(part, q, k_cache, v_cache, pos, t0, q_heads, group, nwg, scale);') - e(' }') - e(' return;') - e('}') - - -dispatch() -for n in range(1, MAX_N + 1): - parts(n) -print('\n'.join(L)) diff --git a/scripts/qwen_weights.py b/scripts/qwen_weights.py index 7d5a73f..88f02aa 100644 --- a/scripts/qwen_weights.py +++ b/scripts/qwen_weights.py @@ -4,19 +4,24 @@ and `f64` loads and needs no JSON parser: word 0 magic, the bytes b"VXQWEN01" - word 1 format version, 1 + word 1 format version, 1 or 2 word 2 number of tensors word 3 alignment of each tensor, in bytes word 4 byte offset of the tensor table - words 5-20 the integers of CONFIG_INTS, in that order - words 21-22 rope_theta and rms_norm_eps, as f64 + words 5-20 version 1: the first 16 integers of CONFIG_INTS, in that order + words 21-22 version 1: rope_theta and rms_norm_eps, as f64 + words 5-36 version 2: the integers of CONFIG_INTS, in that order, then zeros + words 37-38 version 2: rope_theta and rms_norm_eps, as f64 + +A model of `arch` 0 (Qwen2, Qwen3 MoE) gets version 1, and a model of `arch` 1 (Qwen3.5 MoE, which +Qwen3.6 also uses) gets version 2. The tensor table has one entry of 16 words (128 bytes) per tensor: the name in words 0-7 (ASCII, padded with zero bytes), the dtype code, the rank, four dimensions (unused ones are 0), the byte offset of the data and its size in bytes. The tensors come in the order of `tensor_names`. `weight_format` says how the file stores the weight matrices of MATRICES. Each other tensor is -bf16 in every format. +bf16 in every format, except the f32 tensors of arch 1 below. 0, bf16 each weight matrix is bf16. 1, fp8 each weight matrix is f8e4m3 codes, one byte for each weight. The tensor after it, @@ -40,6 +45,50 @@ and `down`. These hold expert e after expert e - 1. An expert has 2 * moe_intermediate_size rows in `experts_gate_up`, its gate rows and then its up rows, and hidden_size rows in `experts_down`. +In arch 1, layer l has full attention when (l + 1) % full_attention_interval is 0, and a Gated +DeltaNet (a linear attention) otherwise. Each RMSNorm of the model multiplies by 1 + w, and the file +holds 1 + w as f32, so that a program multiplies by the weight as for arch 0. A layer with full +attention has: + + qkv the rows of q, k and v, then the rows of the gate of each query head. The + attention output of head h is multiplied by sigmoid of gate head h. + q_norm, k_norm, attn_out + as in arch 0. RoPE turns only the first rotary_dim values of each head. + +A Gated DeltaNet layer has, with K = linear_k_heads * linear_k_dim and V = linear_v_heads * +linear_v_dim: + + linear_in rows [q K | k K | v V | z V | b linear_v_heads | a linear_v_heads], one matrix. + conv f32 [2K + V, conv_width], the causal convolution of q, k and v. Column + conv_width - 1 multiplies the current token, and column 0 the oldest. + neg_A f32 [linear_v_heads], -exp(A_log). + dt_bias f32 [linear_v_heads]. + linear_norm f32 [linear_v_dim], the RMSNorm of each head of the output. It multiplies by w, + not by 1 + w. + linear_out [hidden_size, V]. + +Each layer of arch 1 also has a shared expert. Its `router` has one more row, the gate of the +shared expert, and `shared_gate_up` and `shared_down` hold the shared expert as one expert of +`experts_gate_up` and `experts_down`, with shared_expert_intermediate_size in place of +moe_intermediate_size. + +A model of arch 1 can also have mtp_layers = 1: the multi-token prediction (MTP) layer of the model, +which predicts the token after the next one. Its tensors come after all the other tensors, so the +other tensors of a file with them have the same order and bytes as in a file without them, and the +same offsets unless the longer tensor table moves the data to the next 16 KiB page. The +MTP layer uses the `embed` and `lm_head` of the model. At position p + 1, its input is token p + 1 +and the hidden state h of position p, after final_norm (or, for a draft after a draft, the h of +the MTP layer itself). It has: + + mtp.embed_norm f32 [hidden_size], the RMSNorm (1 + w) of the embedding of the token. + mtp.hidden_norm f32 [hidden_size], the RMSNorm (1 + w) of h. + mtp.fc [hidden_size, 2 * hidden_size], a weight matrix. Its input is the normed + embedding, then the normed h. + mtp.layers.0.* the tensors of a layer with full attention, as below. The layer has its own + KV cache. + mtp.final_norm f32 [hidden_size], the RMSNorm (1 + w) after the layer. Its output is the h of + the MTP layer, and lm_head of it gives the logits of position p + 2. + Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. See LICENSE for license information. SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception @@ -54,7 +103,6 @@ import numpy as np MAGIC = b"VXQWEN01" -VERSION = 1 TABLE_OFFSET = 4096 ENTRY_BYTES = 128 # A Metal buffer over mapped file memory must start on a page, and an Apple Silicon page is 16 KiB. @@ -77,10 +125,23 @@ "experts_per_token", "moe_intermediate_size", "qk_norm", + # Version 2 only. A version 1 file reads them as V1_DEFAULTS. + "arch", + "full_attention_interval", + "linear_k_heads", + "linear_v_heads", + "linear_k_dim", + "linear_v_dim", + "conv_width", + "rotary_dim", + "shared_expert_intermediate_size", + "mtp_layers", ] -# The header has room for 16 integers. -CONFIG_INT_SLOTS = 16 -assert len(CONFIG_INTS) <= CONFIG_INT_SLOTS +# The integers that the header of each version has room for. +CONFIG_INT_SLOTS = {1: 16, 2: 32} +assert len(CONFIG_INTS) <= CONFIG_INT_SLOTS[2] +V1_DEFAULTS = dict.fromkeys(CONFIG_INTS[CONFIG_INT_SLOTS[1] :], 0) +ARCHS = {"qwen": 0, "qwen3_5": 1} WEIGHT_FORMATS = {"bf16": 0, "fp8": 1, "q4_0": 2, "q4_0_q6": 3} DTYPE_CODES = {"f32": 0, "bf16": 1, "f8e4m3": 2, "f16": 3, "u4": 4, "u2": 5} @@ -91,7 +152,8 @@ STORAGE = {"f32": np.float32, "bf16": np.uint16, "f8e4m3": np.uint8, "f16": np.float16, "u4": np.uint8, "u2": np.uint8} # The weight matrices that an fp8 or q4_0 file quantizes. The kinds of a layer end the name. -MATRICES = ("qkv", "attn_out", "gate_up", "down", "experts_gate_up", "experts_down", "lm_head") +MATRICES = ("qkv", "attn_out", "gate_up", "down", "experts_gate_up", "experts_down", "lm_head", + "linear_in", "linear_out", "shared_gate_up", "shared_down", "fc") BLOCK = 128 Q4_GROUP = 32 # A 6-bit matrix has one f16 scale for each Q6_GROUP weights of a row. @@ -134,6 +196,31 @@ def matrix_dtype(config, name): return "f8e4m3" if weight_format else "bf16" +def file_version(config): + """The format version of the weight file of a model: 1 for arch 0, and 2 for arch 1.""" + return 2 if config.get("arch", 0) else 1 + + +def has_full_attention(config, layer): + """Whether layer `layer` has full attention, and not a Gated DeltaNet.""" + return not config.get("arch", 0) or (layer + 1) % config["full_attention_interval"] == 0 + + +def layer_names(config, layer, prefix=None): + """The names of the tensors of one layer of an arch 1 model, in file order. `prefix` names the + MTP layer, which has full attention.""" + full = prefix is not None or has_full_attention(config, layer) + prefix = prefix or f"layers.{layer}." + if full: + kinds = ["attn_norm", "qkv", "q_norm", "k_norm", "attn_out"] + else: + kinds = ["attn_norm", "linear_in", "conv", "neg_A", "dt_bias", "linear_norm", "linear_out"] + kinds += ["mlp_norm", "router", "experts_gate_up", "experts_down"] + if config["shared_expert_intermediate_size"]: + kinds += ["shared_gate_up", "shared_down"] + return [prefix + kind for kind in kinds] + + def tensor_names(config): """The names of the tensors in the weight file, in file order.""" assert config["weight_format"] in WEIGHT_FORMATS.values(), f"weight format {config['weight_format']}" @@ -141,6 +228,9 @@ def tensor_names(config): names = ["embed"] for layer in range(config["num_layers"]): prefix = f"layers.{layer}." + if config.get("arch", 0): + names += layer_names(config, layer) + continue names += [prefix + "attn_norm", prefix + "qkv"] if config["qkv_bias"]: names.append(prefix + "qkv_bias") @@ -154,6 +244,7 @@ def tensor_names(config): names.append("final_norm") if not config["tied_embeddings"]: names.append("lm_head") + names += mtp_names(config) if config["weight_format"]: def parts(name): if is_six_bit(config, name): @@ -164,6 +255,14 @@ def parts(name): return names +def mtp_names(config): + """The names of the tensors of the MTP layer, in file order: none when mtp_layers is 0.""" + if not config.get("mtp_layers", 0): + return [] + assert config.get("arch", 0) and config["mtp_layers"] == 1, "only a model of arch 1 can have one MTP layer" + return ["mtp.embed_norm", "mtp.hidden_norm", "mtp.fc"] + layer_names(config, 0, "mtp.layers.0.") + ["mtp.final_norm"] + + def tensor_shapes(config): """The shape of each tensor of the weight file, by name.""" hidden = config["hidden_size"] @@ -177,6 +276,9 @@ def tensor_shapes(config): shapes["lm_head"] = (config["vocab_size"], hidden) for layer in range(config["num_layers"]): prefix = f"layers.{layer}." + if config.get("arch", 0): + shapes.update(arch1_layer_shapes(config, layer)) + continue shapes[prefix + "attn_norm"] = (hidden,) shapes[prefix + "qkv"] = (qkv_rows, hidden) if config["qkv_bias"]: @@ -193,6 +295,10 @@ def tensor_shapes(config): else: shapes[prefix + "gate_up"] = (2 * inter, hidden) shapes[prefix + "down"] = (hidden, inter) + if config.get("mtp_layers", 0): + shapes.update({"mtp.embed_norm": (hidden,), "mtp.hidden_norm": (hidden,), "mtp.fc": (hidden, 2 * hidden), + "mtp.final_norm": (hidden,)}) + shapes.update(arch1_layer_shapes(config, 0, "mtp.layers.0.")) if config["weight_format"]: for name in [n for n in shapes if is_matrix(n)]: rows, cols = shapes[name] @@ -208,6 +314,44 @@ def tensor_shapes(config): return shapes +def arch1_layer_shapes(config, layer, prefix=None): + """The shape of each tensor of one layer of an arch 1 model, by name. `prefix` names the MTP + layer, which has full attention.""" + full = prefix is not None or has_full_attention(config, layer) + prefix = prefix or f"layers.{layer}." + hidden, head_dim, q_heads = config["hidden_size"], config["head_dim"], config["num_q_heads"] + k_total = config["linear_k_heads"] * config["linear_k_dim"] + v_heads = config["linear_v_heads"] + v_total = v_heads * config["linear_v_dim"] + shared = config["shared_expert_intermediate_size"] + shapes = { + "attn_norm": (hidden,), + "mlp_norm": (hidden,), + "router": (config["num_experts"] + (1 if shared else 0), hidden), + "experts_gate_up": (config["num_experts"] * 2 * config["moe_intermediate_size"], hidden), + "experts_down": (config["num_experts"] * hidden, config["moe_intermediate_size"]), + } + if shared: + shapes.update(shared_gate_up=(2 * shared, hidden), shared_down=(hidden, shared)) + if full: + shapes.update( + qkv=(2 * q_heads * head_dim + 2 * config["num_kv_heads"] * head_dim, hidden), + q_norm=(head_dim,), + k_norm=(head_dim,), + attn_out=(hidden, q_heads * head_dim), + ) + else: + shapes.update( + linear_in=(2 * k_total + 2 * v_total + 2 * v_heads, hidden), + conv=(2 * k_total + v_total, config["conv_width"]), + neg_A=(v_heads,), + dt_bias=(v_heads,), + linear_norm=(config["linear_v_dim"],), + linear_out=(hidden, v_total), + ) + return {prefix + kind: shape for kind, shape in shapes.items()} + + def storage_shape(dtype, shape): """The shape of the NumPy array that holds a tensor of this dtype and shape.""" per_byte = {"u4": 2, "u2": 4}.get(dtype, 1) @@ -231,12 +375,16 @@ def write_weight_file(path, config, tensors): # The data starts at the first aligned offset after the tensor table. data_start = -(-(TABLE_OFFSET + ENTRY_BYTES * len(names)) // ALIGNMENT) * ALIGNMENT header = bytearray(data_start) - words = [VERSION, len(names), ALIGNMENT, TABLE_OFFSET] - words += [int(config[field]) for field in CONFIG_INTS] - words += [0] * (CONFIG_INT_SLOTS - len(CONFIG_INTS)) + version = file_version(config) + fields = CONFIG_INTS[: CONFIG_INT_SLOTS[version]] + if version == 1: + assert all(config.get(field, 0) == 0 for field in V1_DEFAULTS), "a version 1 file has no room for these fields" + words = [version, len(names), ALIGNMENT, TABLE_OFFSET] + words += [int(config[field]) for field in fields] + words += [0] * (CONFIG_INT_SLOTS[version] - len(fields)) header[0:8] = MAGIC struct.pack_into(f"<{len(words)}q", header, 8, *words) - struct.pack_into("<2d", header, 8 * (5 + CONFIG_INT_SLOTS), config["rope_theta"], config["rms_norm_eps"]) + struct.pack_into("<2d", header, 8 * (5 + CONFIG_INT_SLOTS[version]), config["rope_theta"], config["rms_norm_eps"]) offset = data_start with open(path, "wb") as out: @@ -266,11 +414,14 @@ def read_weight_file(path): """ data = np.memmap(path, dtype=np.uint8, mode="r") assert bytes(data[0:8]) == MAGIC, f"{path}: not a weight file of the Qwen app" - words = struct.unpack_from(f"<{4 + CONFIG_INT_SLOTS}q", data, 8) - version, count, alignment, table = words[:4] - assert version == VERSION, f"{path}: format version {version}, expected {VERSION}" - config = dict(zip(CONFIG_INTS, words[4 : 4 + len(CONFIG_INTS)])) - config["rope_theta"], config["rms_norm_eps"] = struct.unpack_from("<2d", data, 8 * (5 + CONFIG_INT_SLOTS)) + (version,) = struct.unpack_from("_.npy`, for the stages in DUMP_STAGES. It reads the weight file that `convert.py` writes, so the Vx program and this script use the same bytes. Tests of the Vx program compare with the lines it prints: @@ -19,6 +24,7 @@ """ import argparse +import os import sys import numpy as np @@ -28,6 +34,16 @@ # Below this size, the widened float32 copies of all the weights stay in memory between tokens. CACHE_LIMIT_BYTES = 4 << 30 +# The stages of a Gated DeltaNet layer that --dump-layer writes, for one position each: +# input the layer's input after attn_norm [hidden] +# conv_out q, k and v after the convolution and SiLU [2K + V] +# q, k after the L2 norm of each head, q also times 1 / sqrt(linear_k_dim) [v heads, k dim] +# beta, g [v heads] +# state the state after the update [v heads, k dim, v dim] +# o the output of each head before its RMSNorm [v heads, v dim] +# output the layer's output, after linear_out [hidden] +DUMP_STAGES = ("input", "conv_out", "q", "k", "beta", "g", "state", "o", "output") + class Model: def __init__(self, path): @@ -36,6 +52,8 @@ def __init__(self, path): self.cache = {} if f32_bytes <= CACHE_LIMIT_BYTES else None # A function that gets each input of `product`, as importance.py uses it, or None. self.see_input = None + # The layer and folder of --dump-layer, or None. + self.dump_layer, self.dump_dir = None, None def weight(self, name, rows=None): """The float32 values of a tensor, or of the rows (start, stop) of a matrix.""" @@ -75,15 +93,28 @@ def silu(x): return x / (1 + np.exp(-x)) +def sigmoid(x): + return 1 / (1 + np.exp(-x)) + + +def partial_rope(x, positions, theta, rotary_dim): + """`rope` on the first rotary_dim values of each head of x. The other values stay.""" + if rotary_dim == x.shape[-1]: + return rope(x, positions, theta) + return np.concatenate([rope(x[..., :rotary_dim], positions, theta), x[..., rotary_dim:]], axis=-1) + + def mixture_of_experts(model, prefix, h): """The sum of the experts that the router chooses for each token of h, each times its weight. The router keeps the experts_per_token largest of the softmax over all experts, and scales - their weights to sum to 1. + their weights to sum to 1. A model with a shared expert also adds it for every token, times + sigmoid of the last row of the router. """ c = model.config hidden, inter = c["hidden_size"], c["moe_intermediate_size"] - scores = h @ model.weight(prefix + "router").T + logits = h @ model.weight(prefix + "router").T + scores = logits[:, : c["num_experts"]] scores = np.exp(scores - scores.max(axis=-1, keepdims=True)) scores = scores / scores.sum(axis=-1, keepdims=True) chosen = np.argsort(-scores, axis=-1, kind="stable")[:, : c["experts_per_token"]] @@ -96,21 +127,154 @@ def mixture_of_experts(model, prefix, h): act = silu(gate_up[:, :inter]) * gate_up[:, inter:] down = product(model, act, prefix + "experts_down", (expert * hidden, (expert + 1) * hidden)) out[tokens] += weights[tokens, slots][:, None] * down + shared = c.get("shared_expert_intermediate_size", 0) + if shared: + gate_up = product(model, h, prefix + "shared_gate_up") + act = silu(gate_up[:, :shared]) * gate_up[:, shared:] + out += sigmoid(logits[:, c["num_experts"] :]) * product(model, act, prefix + "shared_down") return out class Cache: - """The keys and values of every position so far, per layer, rounded to f16 as in the Vx program.""" + """The keys and values of every position so far, per layer, rounded to f16 as in the Vx program. + A Gated DeltaNet layer has instead the last conv_width - 1 inputs of its convolution and its + state, in f32.""" def __init__(self, config): - self.keys = [None] * config["num_layers"] - self.values = [None] * config["num_layers"] + layers = config["num_layers"] + self.keys = [None] * layers + self.values = [None] * layers + self.conv = [None] * layers + self.state = [None] * layers self.length = 0 + for layer in range(layers): + if not qwen_weights.has_full_attention(config, layer): + k_total = config["linear_k_heads"] * config["linear_k_dim"] + channels = 2 * k_total + config["linear_v_heads"] * config["linear_v_dim"] + self.conv[layer] = np.zeros((config["conv_width"] - 1, channels), dtype=np.float32) + shape = (config["linear_v_heads"], config["linear_k_dim"], config["linear_v_dim"]) + self.state[layer] = np.zeros(shape, dtype=np.float32) + + +def attend(cache, layer, q, k, v, positions): + """Add k and v to the cache of `layer`, and return the attention of q over all positions so + far, shaped [tokens, query heads * head_dim]. q is [tokens, query heads, head_dim], and k + and v are [tokens, key-value heads, head_dim].""" + count, qh, hd = q.shape + # The KV cache of the Vx program holds f16 values, so round them as it does. + k = k.astype(np.float16).astype(np.float32) + v = v.astype(np.float16).astype(np.float32) + if cache.keys[layer] is None: + cache.keys[layer], cache.values[layer] = k, v + else: + cache.keys[layer] = np.concatenate([cache.keys[layer], k]) + cache.values[layer] = np.concatenate([cache.values[layer], v]) + keys, values = cache.keys[layer], cache.values[layer] + # Query head i uses key-value head i // group: grouped-query attention. + group = qh // k.shape[1] + scores = np.einsum("tgd,sgd->gts", q, np.repeat(keys, group, axis=1)) / np.float32(np.sqrt(hd)) + visible = np.arange(keys.shape[0])[None, :] <= positions[:, None] + scores = np.where(visible[None, :, :], scores, -np.inf) + scores = np.exp(scores - scores.max(axis=-1, keepdims=True)) + scores = scores / scores.sum(axis=-1, keepdims=True) + return np.einsum("gts,sgd->tgd", scores, np.repeat(values, group, axis=1)).reshape(count, qh * hd) + + +def gated_attention(model, prefix, h, positions, cache, layer): + """The full attention of an arch 1 layer: q and k get an RMSNorm per head and RoPE on their + first rotary_dim values, and each head's output is multiplied by sigmoid of its gate.""" + c = model.config + hd, qh, kvh, eps = c["head_dim"], c["num_q_heads"], c["num_kv_heads"], c["rms_norm_eps"] + count = len(h) + qkv = product(model, h, prefix + "qkv") + q = qkv[:, : qh * hd].reshape(count, qh, hd) + k = qkv[:, qh * hd : (qh + kvh) * hd].reshape(count, kvh, hd) + v = qkv[:, (qh + kvh) * hd : (qh + 2 * kvh) * hd].reshape(count, kvh, hd) + gate = qkv[:, (qh + 2 * kvh) * hd :] + q = partial_rope(rms_norm(q, model.weight(prefix + "q_norm"), eps), positions, c["rope_theta"], c["rotary_dim"]) + k = partial_rope(rms_norm(k, model.weight(prefix + "k_norm"), eps), positions, c["rope_theta"], c["rotary_dim"]) + attended = attend(cache, layer, q, k, v, positions) * sigmoid(gate) + return product(model, attended, prefix + "attn_out") + + +def delta_net(model, prefix, h, cache, layer): + """The Gated DeltaNet of an arch 1 layer, one position after the other. + + Each value head j keeps a state S of [k dim, v dim], and reads key head j // (v heads / k heads). + For each position, S decays by exp(g), then takes the part of v that S does not already give + for k, times beta: S += k (beta (v - k S)). The output of the head is q S. + """ + c = model.config + kh, vh, kd, vd = c["linear_k_heads"], c["linear_v_heads"], c["linear_k_dim"], c["linear_v_dim"] + k_total, v_total, width = kh * kd, vh * vd, c["conv_width"] + count = len(h) + mixed = product(model, h, prefix + "linear_in") + z = mixed[:, 2 * k_total + v_total : 2 * k_total + 2 * v_total].reshape(count, vh, vd) + b = mixed[:, 2 * k_total + 2 * v_total : 2 * k_total + 2 * v_total + vh] + a = mixed[:, 2 * k_total + 2 * v_total + vh :] + # The causal convolution of each channel over this position and the width - 1 before it. + conv = model.weight(prefix + "conv") + padded = np.concatenate([cache.conv[layer], mixed[:, : 2 * k_total + v_total]]) + cache.conv[layer] = padded[count:] + conv_out = silu(np.stack([(padded[t : t + width] * conv.T).sum(axis=0) for t in range(count)])) + q = conv_out[:, :k_total].reshape(count, kh, kd) + k = conv_out[:, k_total : 2 * k_total].reshape(count, kh, kd) + v = conv_out[:, 2 * k_total :].reshape(count, vh, vd) + q = q / np.sqrt((q * q).sum(axis=-1, keepdims=True) + np.float32(1e-6)) / np.float32(np.sqrt(kd)) + k = k / np.sqrt((k * k).sum(axis=-1, keepdims=True) + np.float32(1e-6)) + q, k = np.repeat(q, vh // kh, axis=1), np.repeat(k, vh // kh, axis=1) + beta = sigmoid(b) + g = model.weight(prefix + "neg_A") * np.logaddexp(np.float32(0), a + model.weight(prefix + "dt_bias")) + state = cache.state[layer] + out = np.empty((count, vh, vd), dtype=np.float32) + for t in range(count): + state = state * np.exp(g[t])[:, None, None] + delta = (v[t] - np.einsum("hk,hkv->hv", k[t], state)) * beta[t][:, None] + state = state + k[t][:, :, None] * delta[:, None, :] + out[t] = np.einsum("hk,hkv->hv", q[t], state) + if model.dump_layer == layer: + stages = dict(conv_out=conv_out[t], q=q[t], k=k[t], beta=beta[t], g=g[t], state=state, o=out[t]) + dump(model, cache.length + t, stages) + cache.state[layer] = state + normed = rms_norm(out, model.weight(prefix + "linear_norm"), c["rms_norm_eps"]) * silu(z) + return product(model, normed.reshape(count, v_total), prefix + "linear_out") + + +def dump(model, position, stages): + for stage, value in stages.items(): + np.save(os.path.join(model.dump_dir, f"pos{position}_{stage}.npy"), np.asarray(value, dtype=np.float32)) + + +def forward_qwen3_5(model, tokens, cache): + """`forward` for an arch 1 model.""" + c = model.config + eps = c["rms_norm_eps"] + count = len(tokens) + positions = np.arange(cache.length, cache.length + count) + # Widen only the rows of the tokens: the whole table of a real model is 2 GB in f32. + x = np.stack([qwen_weights.widen(model.tensors, "embed", (t, t + 1))[0] for t in tokens]) + for layer in range(c["num_layers"]): + p = f"layers.{layer}." + h = rms_norm(x, model.weight(p + "attn_norm"), eps) + if qwen_weights.has_full_attention(c, layer): + out = gated_attention(model, p, h, positions, cache, layer) + else: + out = delta_net(model, p, h, cache, layer) + if model.dump_layer == layer: + for t in range(count): + dump(model, cache.length + t, dict(input=h[t], output=out[t])) + x = x + out + x = x + mixture_of_experts(model, p, rms_norm(x, model.weight(p + "mlp_norm"), eps)) + cache.length += count + x = rms_norm(x, model.weight("final_norm"), eps) + return product(model, x, "embed" if c["tied_embeddings"] else "lm_head").astype(np.float32) def forward(model, tokens, cache): """Run `tokens` after the `cache.length` tokens already in the cache. Return their logits.""" c = model.config + if c.get("arch", 0): + return forward_qwen3_5(model, tokens, cache) hd, qh, kvh = c["head_dim"], c["num_q_heads"], c["num_kv_heads"] eps = c["rms_norm_eps"] count = len(tokens) @@ -131,24 +295,7 @@ def forward(model, tokens, cache): k = rms_norm(k, model.weight(p + "k_norm"), eps) q = rope(q, positions, c["rope_theta"]) k = rope(k, positions, c["rope_theta"]) - # The KV cache of the Vx program holds f16 values, so round them as it does. - k = k.astype(np.float16).astype(np.float32) - v = v.astype(np.float16).astype(np.float32) - if cache.keys[layer] is None: - cache.keys[layer], cache.values[layer] = k, v - else: - cache.keys[layer] = np.concatenate([cache.keys[layer], k]) - cache.values[layer] = np.concatenate([cache.values[layer], v]) - keys, values = cache.keys[layer], cache.values[layer] - # Query head i uses key-value head i // group: grouped-query attention. - group = qh // kvh - scores = np.einsum("tgd,sgd->gts", q, np.repeat(keys, group, axis=1)) / np.float32(np.sqrt(hd)) - visible = np.arange(keys.shape[0])[None, :] <= positions[:, None] - scores = np.where(visible[None, :, :], scores, -np.inf) - scores = np.exp(scores - scores.max(axis=-1, keepdims=True)) - scores = scores / scores.sum(axis=-1, keepdims=True) - attended = np.einsum("gts,sgd->tgd", scores, np.repeat(values, group, axis=1)).reshape(count, qh * hd) - x = x + product(model, attended, p + "attn_out") + x = x + product(model, attend(cache, layer, q, k, v, positions), p + "attn_out") h = rms_norm(x, model.weight(p + "mlp_norm"), eps) if c["num_experts"]: x = x + mixture_of_experts(model, p, h) @@ -193,8 +340,15 @@ def main(): parser.add_argument("--tensors", action="store_true", help="print the first codes and the sum of the codes of each tensor") parser.add_argument("--perplexity", help="a text file whose perplexity to print; needs --tokenizer") parser.add_argument("--max-tokens", type=int, default=512, help="the number of tokens of --perplexity to use") + parser.add_argument("--dump-layer", type=int, help="a Gated DeltaNet layer whose stages to write; needs --dump-dir") + parser.add_argument("--dump-dir", help="the folder for the files of --dump-layer") args = parser.parse_args() model = Model(args.weights) + if args.dump_layer is not None: + assert args.dump_dir, "--dump-layer needs --dump-dir" + assert not qwen_weights.has_full_attention(model.config, args.dump_layer), "--dump-layer needs a Gated DeltaNet layer" + os.makedirs(args.dump_dir, exist_ok=True) + model.dump_layer, model.dump_dir = args.dump_layer, args.dump_dir if args.tensors: # Bits, not decimals, so that a Vx program can print the same line exactly. A code is the diff --git a/scripts/round_attention.py b/scripts/round_attention.py new file mode 100644 index 0000000..4a46b4f --- /dev/null +++ b/scripts/round_attention.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +# Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +# See LICENSE for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""Prints the kernels of `round_attention` in src/round.vx: the attention of n positions in a row, at +start to start + n - 1, as Vx code. A kernel for n queries keeps the values of each query in variables +of their own, so that they stay in registers. Vx v0.0.5 keeps a tile in threadgroup memory on Metal, +so a kernel with a tile for the n queries would be slower. + +Each query gets the result of `vec_attention` (src/attention.vx) bit for bit. A block does the same +work for each of its n queries that the block of `vec_attention_parts` does for one, in the same +order, but it reads each row of K and V once for all of them. A query skips the blocks of 32 +positions after its own position, and a row after its position gets the score -3e38 and so the +weight 0, as in `vec_attention_parts`. The rows after the last query are not read. The kernels call +the small `mlir!` functions of src/simd.vx, and `fused` of src/attention.vx. + + python3 scripts/round_attention.py + +prints the functions; replace them in src/round.vx, and run vx-format on it. +""" +MAX_N = 8 +L = [] +e = L.append + + +def parts(n): + """The kernel of the parts for n queries.""" + T = range(n) + e('') + e(f'/// `vec_attention_parts` for {n} queries in a row: query t is at position pos + t, in q[t0 + t], and its part') + e('/// w goes to part[h][w][132 (t0 + t) ..].') + e(f'fn round_attention_parts_{n}(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, t0 : i32, q_heads : i32, group : i32, nwg : i32, scale : f32) -> void {{') + e(' spawn on(Topology::Device) {') + e(' for h in 0..q_heads across blocks {') + e(' for w in 0..nwg across blocks {') + e(' let mut stats = unsafe {') + e(f' Tensor::uninit()') + e(' };') + e(' for s in 0..1 across subgroups {') + e(' for l in 0..32 across lanes(32) {') + b = lambda s: e(' ' + s) + b('let g = h / group;') + b('let d = 4 * l;') + b(f'let last = pos + {n - 1};') + for t in T: + for j in range(4): + b(f'let q{t}_{j} = q[t0 + {t}][h][d + {j}] * scale;') + b(f'let mut big{t} : f32 = -3.0e38;') + b(f'let mut total{t} : f32 = 0.0;') + for j in range(4): + b(f'let mut o{t}_{j} : f32 = 0.0;') + b('let chunks = (last + 32) / 32;') + b('let mut c = w;') + b('while c < chunks {') + c = lambda s: e(' ' + s) + d = lambda s: e(' ' + s) + c('let r0 = c * 32;') + # the scores of rows r0 to r0 + 31 for each query; lane r keeps the scores of row r0 + r. A row past + # the last position reads the row of the last position. + for t in T: + c(f'let mut mine{t} : f32 = -3.0e38;') + c('for r in 0..32 {') + d('let row = r0 + r;') + d('let mut kept = row;') + d('if row > last {') + d(' kept = last;') + d('}') + for j in range(4): + d(f'let k{j} = half4_at(k_cache, kept, g, d, {j});') + for t in T: + d(f'let mut score{t} = simd_sum(k0 * q{t}_0 + k1 * q{t}_1 + k2 * q{t}_2 + k3 * q{t}_3);') + d(f'if row > pos + {t} {{') + d(f' score{t} = -3.0e38;') + d('}') + d('if r == l {') + for t in T: + d(f' mine{t} = score{t};') + d('}') + c('}') + # the online softmax of each query that this block of positions reaches; p is 0 for the others, so + # that the sum of V leaves them as they are + for t in T: + c(f'let mut p{t} : f32 = 0.0;') + c(f'if c < (pos + {t} + 32) / 32 {{') + d(f'let top = big{t}.max(simd_max(mine{t}));') + d(f'let shrink = (big{t} - top).fast_exp();') + d(f'p{t} = (mine{t} - top).fast_exp();') + d(f'total{t} = total{t} * shrink + simd_sum(p{t});') + for j in range(4): + d(f'o{t}_{j} = o{t}_{j} * shrink;') + d(f'big{t} = top;') + c('}') + # the sum of V: the weight of row r0 + r for query t is in lane r + c('for r in 0..32 {') + d('let row = r0 + r;') + d('let mut kept = row;') + d('if row > last {') + d(' kept = last;') + d('}') + for t in T: + d(f'let pr{t} = simd_value(p{t}, r);') + for j in range(4): + d(f'o{t}_{j} = fused(half4_at(v_cache, kept, g, d, {j}), pr{t}, o{t}_{j});') + c('}') + c('c = c + nwg;') + b('}') + for t in T: + b(f'let b{t} = 132 * (t0 + {t});') + for j in range(4): + b(f'part[h][w][b{t} + d + {j}] = o{t}_{j};') + b('// Every lane has the same largest score and sum of the weights of a query. Lanes 0 and 1 keep them') + b('// for the next loop.') + b('if l < 2 {') + for t in T: + b(f' let mut x{t} = big{t};') + b(' if l == 1 {') + b(f' x{t} = total{t};') + b(' }') + b(f' stats[s][{t}][l] = x{t};') + b('}') + e(' }') + e(' for l in 0..2 across lanes(32) {') + for t in T: + e(f' part[h][w][132 * (t0 + {t}) + 128 + l] = stats[s][{t}][l];') + e(' }') + e(' }') + e(' }') + e(' }') + e(' }') + e(' return;') + e('}') + + +def dispatch(): + """Calls the kernel of the parts for n queries.""" + e('') + e(f'/// The parts of queries t0 to t0 + n - 1, with the kernel for n queries. n is 1 to {MAX_N}.') + e('fn round_attention_parts(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, t0 : i32, n : i32, q_heads : i32, group : i32, nwg : i32, scale : f32) -> void {') + e(f' assert(n >= 1 && n <= {MAX_N}, "round_attention_parts: n must be 1 to {MAX_N}");') + for n in range(1, MAX_N + 1): + word = 'if' if n == 1 else '} else if' + if n == MAX_N: + e(' } else {') + else: + e(f' {word} n == {n} {{') + e(f' round_attention_parts_{n}(part, q, k_cache, v_cache, pos, t0, q_heads, group, nwg, scale);') + e(' }') + e(' return;') + e('}') + + +dispatch() +for n in range(1, MAX_N + 1): + parts(n) +print('\n'.join(L)) diff --git a/scripts/test_qwen_weights.py b/scripts/test_qwen_weights.py index 40b71fc..071aed3 100644 --- a/scripts/test_qwen_weights.py +++ b/scripts/test_qwen_weights.py @@ -398,5 +398,152 @@ def test_each_expert_of_the_tiny_moe_model_gets_its_own_importance(self): np.testing.assert_array_equal(q.resolve(tensors["layers.1.experts_gate_up.scale"])[1][3 * 512 : 4 * 512], scales) +def header_version(path): + with open(path, "rb") as f: + return int.from_bytes(f.read(16)[8:16], "little") + + +def write_and_read(name, config, tensors): + with tempfile.TemporaryDirectory() as directory: + path = os.path.join(directory, name) + q.write_weight_file(path, config, tensors) + read_config, read = q.read_weight_file(path) + # Copy the arrays out of the memory map before the folder goes away. + return header_version(path), read_config, {n: (dtype, np.array(a)) for n, (dtype, a) in read.items()} + + +class Qwen35Files(unittest.TestCase): + """The weight file of a Qwen3.5 MoE model (arch 1), from the tiny model of make_tiny_model.py.""" + + def setUp(self): + self.hf = make_tiny_model.tiny_qwen35_model() + self.config, self.tensors = convert.convert_tensors(q.config_from_json(make_tiny_model.QWEN35_CONFIG), self.hf) + + def test_an_old_model_keeps_version_1_and_reads_arch_0(self): + config, tensors = convert.convert_tensors(q.config_from_json(make_tiny_model.MOE_CONFIG), make_tiny_model.tiny_moe_model()) + version, read_config, _ = write_and_read("tiny-moe.vxw", config, tensors) + self.assertEqual(version, 1) + self.assertEqual((read_config["arch"], read_config["full_attention_interval"]), (0, 0)) + + def test_the_q4_0_file_has_version_2_and_the_types_of_llama_cpp(self): + config, tensors = q.quantize(self.config, self.tensors, "q4_0_q6") + version, c, read = write_and_read("tiny-qwen35-q4.vxw", config, tensors) + self.assertEqual(version, 2) + self.assertEqual(list(read), q.tensor_names(c)) + self.assertEqual((c["arch"], c["full_attention_interval"], c["rotary_dim"]), (1, 4, 64)) + self.assertEqual((c["linear_k_heads"], c["linear_v_heads"], c["linear_k_dim"], c["linear_v_dim"]), (2, 4, 128, 128)) + self.assertEqual((c["conv_width"], c["shared_expert_intermediate_size"]), (4, 128)) + dtype = {name: d for name, (d, _) in read.items()} + # Layers 0 to 2 have a Gated DeltaNet, and layer 3 full attention. + for name in ("linear_in", "linear_out", "shared_gate_up", "shared_down", "experts_gate_up"): + self.assertEqual(dtype["layers.0." + name], "u4", name) + for name in ("attn_norm", "conv", "neg_A", "dt_bias", "linear_norm", "mlp_norm"): + self.assertEqual(dtype["layers.0." + name], "f32", name) + self.assertEqual((dtype["layers.3.qkv"], dtype["layers.3.q_norm"], dtype["layers.3.router"]), ("u4", "f32", "bf16")) + self.assertNotIn("layers.0.qkv", dtype) + self.assertNotIn("layers.3.linear_in", dtype) + # q, k, v, z, b and a of 2 key heads and 4 value heads of 128; q, k, v and gate of 4 query + # heads and 2 key-value heads of 256; the 8 experts and the gate of the shared expert. + self.assertEqual(read["layers.0.linear_in.scale"][1].shape, (2 * 256 + 2 * 512 + 2 * 4, 256 // 32)) + self.assertEqual(read["layers.3.qkv.scale"][1].shape, (2 * 1024 + 2 * 512, 256 // 32)) + self.assertEqual(read["layers.0.router"][1].shape, (9, 256)) + + def test_the_bf16_file_holds_the_hugging_face_tensors_in_its_order(self): + _, c, read = write_and_read("tiny-qwen35.vxw", self.config, self.tensors) + hf = {name: q.as_f32(entry) for name, entry in self.hf.items()} + p = "model.language_model.layers." + # Each RMSNorm holds 1 + w, except the norm of the DeltaNet output. + np.testing.assert_array_equal(q.as_f32(read["layers.0.attn_norm"]), hf[p + "0.input_layernorm.weight"] + 1) + np.testing.assert_array_equal(q.as_f32(read["layers.3.k_norm"]), hf[p + "3.self_attn.k_norm.weight"] + 1) + np.testing.assert_array_equal(q.as_f32(read["layers.1.linear_norm"]), hf[p + "1.linear_attn.norm.weight"]) + np.testing.assert_array_equal(q.as_f32(read["layers.1.neg_A"]), -np.exp(hf[p + "1.linear_attn.A_log"])) + np.testing.assert_array_equal(q.as_f32(read["layers.1.conv"]), hf[p + "1.linear_attn.conv1d.weight"][:, 0, :]) + # linear_in: q, k and v, then z, b and a. + linear_in = q.as_f32(read["layers.2.linear_in"]) + np.testing.assert_array_equal(linear_in[1536:1540], hf[p + "2.linear_attn.in_proj_b.weight"]) + np.testing.assert_array_equal(linear_in[1540:], hf[p + "2.linear_attn.in_proj_a.weight"]) + # qkv: q_proj gives head h 512 rows, its query and then its gate. The file has the query + # rows of all heads first, and the gate rows of all heads last. + qkv, q_proj = q.as_f32(read["layers.3.qkv"]), hf[p + "3.self_attn.q_proj.weight"] + np.testing.assert_array_equal(qkv[256:512], q_proj[512:768]) + np.testing.assert_array_equal(qkv[2048:2304], q_proj[256:512]) + np.testing.assert_array_equal(qkv[1024:1536], hf[p + "3.self_attn.k_proj.weight"]) + # The router: one row for each expert, then the gate of the shared expert. + np.testing.assert_array_equal(q.as_f32(read["layers.0.router"])[8], hf[p + "0.mlp.shared_expert_gate.weight"][0]) + # Expert 5 of layer 2: its gate rows, then its up rows. + np.testing.assert_array_equal(q.as_f32(read["layers.2.experts_gate_up"])[5 * 256 : 6 * 256], hf[p + "2.mlp.experts.gate_up_proj"][5]) + + +def table_entries(path): + """The name and the 8 words after it (dtype, rank, dims, offset, bytes) of each tensor.""" + with open(path, "rb") as f: + head = f.read(1 << 20) + count, table = int.from_bytes(head[16:24], "little"), int.from_bytes(head[32:40], "little") + entries = {} + for i in range(count): + entry = head[table + 128 * i : table + 128 * (i + 1)] + entries[entry[:64].rstrip(b"\0").decode()] = np.frombuffer(entry[64:], dtype="", "<|im_start|>", "<|im_end|>", "<|fim_prefix|>", "", ""] @@ -114,6 +120,51 @@ def random_texts(count, seed=1): return texts +def unicode_python(): + """A Python with the Unicode version of `tokenizers`: this one, or python3.14. None when there + is none.""" + for python in [sys.executable, shutil.which("python3.14")]: + if python: + out = subprocess.run([python, "-c", "import unicodedata; print(unicodedata.unidata_version)"], + capture_output=True, text=True) + if out.stdout.strip() == convert_tokenizer.UNICODE_VERSION: + return python + return None + + +UNICODE_PYTHON = unicode_python() +NEEDS_UNICODE_PYTHON = f"needs a Python with Unicode {convert_tokenizer.UNICODE_VERSION}, such as python3.14" + + +def with_unicode_python(code): + """The JSON value that `code` prints in UNICODE_PYTHON. The code may use `json`, `unicodedata`, + and this file as `t`.""" + script = (f"import json, sys, unicodedata; sys.path.insert(0, {str(Path(__file__).parent)!r}); " + f"import test_tokenizer as t; {code}") + out = subprocess.run([UNICODE_PYTHON, "-I", "-c", script], capture_output=True, text=True, check=True) + return json.loads(out.stdout) + + +def nfc_cases(): + """For each mark with a combining class, and each code point with a canonical decomposition of + two parts, the code point and its texts: each text with its NFC form in this Python. A mark + of class k > 0 moves before U+0301 (230) when k < 230, and after U+0316 (220) when k > 220. A + mark of class 0 does neither. "#" composes with no mark.""" + marks, composites = [], [] + for c in range(0x110000): + if 0xD800 <= c <= 0xDFFF: + continue + if unicodedata.combining(chr(c)): + texts = ["#\u0301" + chr(c), "#" + chr(c) + "\u0316"] + marks.append([c, [[text, unicodedata.normalize("NFC", text)] for text in texts]]) + mapping = unicodedata.decomposition(chr(c)) + parts = [int(x, 16) for x in mapping.split()] if mapping and not mapping.startswith("<") else [] + if len(parts) == 2: + text = chr(parts[0]) + chr(parts[1]) + composites.append([c, [[text, unicodedata.normalize("NFC", text)]]]) + return marks, composites + + def run_vx(*args): out = subprocess.run(["vxc", str(ROOT / "tests" / "tokenize.vx"), "--package", f"qwen={ROOT / 'src'}", "--host", "default", "--machine", str(vx_fleet() / "m4-uma.vx"), "--", *map(str, args)], @@ -123,6 +174,7 @@ def run_vx(*args): @unittest.skipIf(Tokenizer is None, "needs the tokenizers package") @unittest.skipIf(shutil.which("vxc") is None, "needs vxc on PATH") +@unittest.skipIf(UNICODE_PYTHON is None, NEEDS_UNICODE_PYTHON) class TokenizerAgainstHuggingFace(unittest.TestCase): @classmethod @@ -140,7 +192,8 @@ def check_model(self, model): self.skipTest(f"needs {model}") tmp = Path(self.tmp.name) vxt = tmp / (model.name + ".vxt") - vxt.write_bytes(convert_tokenizer.build(json.loads((model / "tokenizer.json").read_text(encoding="utf-8")))) + subprocess.run([UNICODE_PYTHON, str(ROOT / "scripts" / "convert_tokenizer.py"), str(model), str(vxt)], + capture_output=True, check=True) texts_file = tmp / "texts.bin" texts_file.write_bytes(b"\0".join(t.encode("utf-8") for t in self.texts)) lines = [l for l in run_vx(vxt, texts_file).decode().split("\n") if not l.startswith("[JIT]")] @@ -178,17 +231,77 @@ def test_qwen25_coder(self): def test_qwen3_coder(self): self.check_model(MODELS[1]) + def test_qwen36(self): + self.check_model(MODELS[2]) + + +def letter_ranges(data): + """The ranges of the class of letters in the bytes of a tokenizer file.""" + count, offset = struct.unpack_from(" 0 moves before U+0301 (230) when k < 230, and after U+0316 (220) - # when k > 220. A mark of class 0 does neither. "#" composes with no mark. - marks = [c for c in range(0x110000) if not 0xD800 <= c <= 0xDFFF and unicodedata.combining(chr(c)) - and (differs("#́" + chr(c)) or differs("#" + chr(c) + "̖"))] - composites = [] - for c in range(0x110000): - if 0xD800 <= c <= 0xDFFF: - continue - mapping = unicodedata.decomposition(chr(c)) - parts = [int(x, 16) for x in mapping.split()] if mapping and not mapping.startswith("<") else [] - if len(parts) == 2 and differs(chr(parts[0]) + chr(parts[1])): - composites.append(c) + mark_cases, composite_cases = with_unicode_python("print(json.dumps(t.nfc_cases()))") + marks = [c for c, texts in mark_cases if differs(texts)] + composites = [c for c, texts in composite_cases if differs(texts)] listed = [c for first, last in convert_tokenizer.OLD_NFC_MARKS for c in range(first, last + 1)] self.assertEqual([hex(c) for c in marks], [hex(c) for c in listed]) self.assertEqual([hex(c) for c in composites], [hex(c) for c in convert_tokenizer.OLD_NFC_COMPOSITES]) diff --git a/src/attention.vx b/src/attention.vx index 646a9f0..a7d84a1 100644 --- a/src/attention.vx +++ b/src/attention.vx @@ -13,11 +13,12 @@ // // `vec_attention`, for head_dim 128, has the design of llama.cpp's flash attention for one token // (kernel_flash_attn_ext_vec and kernel_flash_attn_ext_vec_reduce), MIT License, Copyright (c) 2023-2026 -// The ggml authors. Its kernels are Vx code. Small `mlir!` functions do the operations that Vx v0.0.5 -// cannot write in a kernel: a sum, a largest value or a value across the lanes of a SIMD group, a load of -// 4 halves in 8 bytes, and a fused multiply-add. +// The ggml authors. Its kernels are Vx code. The small `mlir!` functions of src/simd.vx do the operations +// that Vx v0.0.5 cannot write in a kernel: a sum, a largest value or a value across the lanes of a SIMD +// group, and a load of 4 halves in 8 bytes. `fused` below does a fused multiply-add. import core::num; import std::nn; +import qwen::simd; /// Attention of the token at position `pos` over rows 0 to `pos` of the KV cache, with a softmax /// of the scores q . k / sqrt(head_dim). `part` is scratch space from `split_attention_scratch`. @@ -25,7 +26,7 @@ import std::nn; /// The blocks of the first kernel split the positions, 32 to a block below position 640 and 64 from /// there on. A block serves the 8 heads of Q that share a head of K and V, so it reads each row of /// the cache once for all 8. A second kernel merges the parts of the blocks for each head. -fn split_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { +pub fn split_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); @@ -52,7 +53,7 @@ fn split_attention(out : &mut Tensor, part : /// (llama.cpp goes on to 4 SIMD groups of 32 a block, but 128 parts are no faster here: their merge costs what /// they save.) `vec_attention_merge` then merges the parts. `part` is scratch space from /// `vec_attention_scratch`. -fn vec_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { +pub fn vec_attention(out : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); nn_check_heads(out.extent(0), out.extent(1), q_heads, head_dim); nn_check_cache(k_cache.extent(0), k_cache.extent(1), k_cache.extent(2), pos, kv_heads, head_dim); @@ -71,89 +72,23 @@ fn vec_attention(out : &mut Tensor, part : &mut Tensor /// The scratch space of `vec_attention`, on the CPU: up to 128 parts for each head of Q, each the sum of V /// (128 values), the largest score, and the sum of the weights. A part has 132 values, so that each starts /// at a multiple of 16 bytes. -fn vec_attention_scratch(q_heads : i32) -> Tensor { +pub fn vec_attention_scratch(q_heads : i32) -> Tensor { return Tensor([q_heads, 128, 132]); } -/// The sum of `x` over the 32 lanes of a SIMD group. Each lane gets the sum. -fn lane_sum(x : f32) on Topology::Device -> f32 -ensures writes_only() -{ - return mlir!( inputs : (%x = x : f32), returns : f32, dialects : ["gpu"], ensures : [writes_only()]) { - %r = gpu.subgroup_reduce add %x : (f32) -> f32 - macro.yield %r : f32 - }; -} -/// The largest `x` over the 32 lanes of a SIMD group. Each lane gets it. -fn lane_max(x : f32) on Topology::Device -> f32 -ensures writes_only() -{ - return mlir!( inputs : (%x = x : f32), returns : f32, dialects : ["gpu"], ensures : [writes_only()]) { - %r = gpu.subgroup_reduce maxnumf %x : (f32) -> f32 - macro.yield %r : f32 - }; -} -/// The value of `x` in lane `src` of the SIMD group. -fn lane_value(x : f32, src : i32) on Topology::Device -> f32 -ensures writes_only() -{ - return mlir!( inputs : (%x = x : f32, %src = src : i32), returns : f32, dialects : ["arith", "gpu"], ensures : [writes_only()]) { - %w = arith.constant 32 : i32 - %r, %ok = gpu.shuffle idx %x, %src, %w : f32 - macro.yield %r : f32 - }; -} - -/// q0 t[row][g][d] + q1 t[row][g][d + 1] + q2 t[row][g][d + 2] + q3 t[row][g][d + 3], with the 4 halves in -/// one 8-byte load. d is a multiple of 4. -fn dot4(t : &Tensor, row : i32, g : i32, d : i32, q0 : f32, q1 : f32, q2 : f32, q3 : f32) on Topology::Device -> f32 -ensures reads_only(t) -{ - return mlir!( inputs : (%t = t : memref, %row = row : i32, %g = g : i32, %d = d : i32, %q0 = q0 : f32, %q1 = q1 : f32, %q2 = q2 : f32, %q3 = q3 : f32), returns : f32, dialects : ["arith", "vector"], ensures : [reads_only(t)]) { - %r = arith.index_cast %row : i32 to index - %gi = arith.index_cast %g : i32 to index - %di = arith.index_cast %d : i32 to index - %h = vector.load %t[%r, %gi, %di] { - alignment = 8 - } : memref, vector<4xf16> - %f = arith.extf %h : vector<4xf16> to vector<4xf32> - %q = vector.from_elements %q0, %q1, %q2, %q3 : vector<4xf32> - %p = arith.mulf %f, %q : vector<4xf32> - %s = vector.reduction , %p : vector<4xf32> into f32 - macro.yield %s : f32 - }; -} -/// t[row][g][d + j] for j 0 to 3, from one 8-byte load of the 4 halves at d, a multiple of 4. The compiler -/// merges the loads of the 4 calls for one d into one. -fn half_at(t : &Tensor, row : i32, g : i32, d : i32, j : i32) on Topology::Device -> f32 -ensures reads_only(t) -{ - return mlir!( inputs : (%t = t : memref, %row = row : i32, %g = g : i32, %d = d : i32, %j = j : i32), returns : f32, dialects : ["arith", "vector"], ensures : [reads_only(t)]) { - %r = arith.index_cast %row : i32 to index - %gi = arith.index_cast %g : i32 to index - %di = arith.index_cast %d : i32 to index - %ji = arith.index_cast %j : i32 to index - %h = vector.load %t[%r, %gi, %di] { - alignment = 8 - } : memref, vector<4xf16> - %x = vector.extract %h[%ji] : f16 from vector<4xf16> - %f = arith.extf %x : f16 to f32 - macro.yield %f : f32 - }; -} -/// a b + c with one rounding. `mul_add` of Vx v0.0.5 does this, but its parallel checker does not know -/// that `mul_add` writes no memory, so a kernel cannot call it. -fn fused(a : f32, b : f32, c : f32) on Topology::Device -> f32 +/// a b + c with one rounding. `mul_add` of Vx v0.0.6 does this, but it does not say `ensures +/// writes_only()`, so a kernel cannot call it (vx-lang/Vx#3456). +pkg fn fused(a : f32, b : f32, c : f32) on Topology::Device -> f32 ensures writes_only() { - return mlir!( inputs : (%a = a : f32, %b = b : f32, %c = c : f32), returns : f32, dialects : ["math"], ensures : [writes_only()]) { + return unsafe { mlir!( inputs : (%a = a : f32, %b = b : f32, %c = c : f32), returns : f32, dialects : ["math"], ensures : [writes_only()]) { %r = math.fma %a, %b, %c : f32 macro.yield %r : f32 - }; + } }; } /// The parts of `vec_attention`, as llama.cpp's kernel_flash_attn_ext_vec. Block (h, w) is a SIMD group for @@ -192,7 +127,11 @@ fn vec_attention_parts(part : &mut Tensor, q : &Ten if row > pos { kept = pos; } - let mut score = lane_sum(dot4(k_cache, kept, g, d, q0, q1, q2, q3)); + let k0 = half4_at(k_cache, kept, g, d, 0); + let k1 = half4_at(k_cache, kept, g, d, 1); + let k2 = half4_at(k_cache, kept, g, d, 2); + let k3 = half4_at(k_cache, kept, g, d, 3); + let mut score = simd_sum(k0 * q0 + k1 * q1 + k2 * q2 + k3 * q3); if row > pos { score = -3.0e38; } @@ -200,10 +139,10 @@ fn vec_attention_parts(part : &mut Tensor, q : &Ten mine = score; } } - let top = big.max(lane_max(mine)); + let top = big.max(simd_max(mine)); let shrink = (big - top).fast_exp(); let p = (mine - top).fast_exp(); - total = total * shrink + lane_sum(p); + total = total * shrink + simd_sum(p); o0 = o0 * shrink; o1 = o1 * shrink; o2 = o2 * shrink; @@ -214,11 +153,11 @@ fn vec_attention_parts(part : &mut Tensor, q : &Ten if row > pos { kept = pos; } - let pr = lane_value(p, r); - o0 = fused(half_at(v_cache, kept, g, d, 0), pr, o0); - o1 = fused(half_at(v_cache, kept, g, d, 1), pr, o1); - o2 = fused(half_at(v_cache, kept, g, d, 2), pr, o2); - o3 = fused(half_at(v_cache, kept, g, d, 3), pr, o3); + let pr = simd_value(p, r); + o0 = fused(half4_at(v_cache, kept, g, d, 0), pr, o0); + o1 = fused(half4_at(v_cache, kept, g, d, 1), pr, o1); + o2 = fused(half4_at(v_cache, kept, g, d, 2), pr, o2); + o3 = fused(half4_at(v_cache, kept, g, d, 3), pr, o3); } big = top; c = c + nwg; @@ -250,7 +189,7 @@ fn vec_attention_parts(part : &mut Tensor, q : &Ten /// Merges the first `parts` parts of `vec_attention_parts` for each head of Q. A block of 32 lanes does 32 /// values of one head, a value for each lane. Each lane adds up the parts in order, from part 0 to the last, /// as `round_attention_merge` does, so a query gives the same bits in both. -fn vec_attention_merge(out : &mut Tensor, part : &Tensor, parts : i32, q_heads : i32) -> void { +pub fn vec_attention_merge(out : &mut Tensor, part : &Tensor, parts : i32, q_heads : i32) -> void { spawn on(Topology::Device) { for h in 0..q_heads across blocks { for dq in 0..4 across blocks { @@ -287,7 +226,7 @@ fn vec_attention_merge(out : &mut Tensor, part : &Tens /// The scratch space of `split_attention` for positions below `max_seq`, on the CPU. Transfer it to the /// memory of the other tensors. Each block of positions writes the weighted sum of V for each of its /// heads, then the largest score and the sum of the weights. -fn split_attention_scratch(max_seq : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> Tensor { +pkg fn split_attention_scratch(max_seq : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> Tensor { // 20 blocks of 32 positions below position 640, and blocks of 64 positions from there on. let mut splits = (max_seq + 63) / 64; if splits < 20 { @@ -790,7 +729,7 @@ fn split_attention_merge(out : &mut Tensor, /// q, turned, to `q_out`, and each head of k, turned, and of v to row `pos` of the cache. Value i /// of a head pairs with value i + head_dim / 2, as in the Llama and Qwen models of Hugging Face. /// Both turn by the angle whose cosine and sine are cos[pos][i] and sin[pos][i]. -fn rope_and_store(q_out : &mut Tensor, k_cache : &mut Tensor, v_cache : &mut Tensor, q : &Tensor, k : &Tensor, v : &Tensor, cos : &Tensor, sin : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { +pkg fn rope_and_store(q_out : &mut Tensor, k_cache : &mut Tensor, v_cache : &mut Tensor, q : &Tensor, k : &Tensor, v : &Tensor, cos : &Tensor, sin : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32) -> void { let half = head_dim / 2; nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); nn_check_heads(q_out.extent(0), q_out.extent(1), q_heads, head_dim); @@ -830,7 +769,7 @@ fn rope_and_store(q_out : &mut Tensor, k_cac /// As `rope_and_store`, after an RMSNorm over each head of q and of k: value i of a head x /// becomes x[i] / sqrt(mean(x^2) + eps) * norm[i], where `norm` is `q_norm` for q and `k_norm` /// for k. Qwen3 has these norms. -fn norm_rope_and_store(q_out : &mut Tensor, k_cache : &mut Tensor, v_cache : &mut Tensor, q : &Tensor, k : &Tensor, v : &Tensor, q_norm : &Tensor, k_norm : &Tensor, cos : &Tensor, sin : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32, eps : f32) -> void { +pub fn norm_rope_and_store(q_out : &mut Tensor, k_cache : &mut Tensor, v_cache : &mut Tensor, q : &Tensor, k : &Tensor, v : &Tensor, q_norm : &Tensor, k_norm : &Tensor, cos : &Tensor, sin : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, head_dim : i32, eps : f32) -> void { let half = head_dim / 2; nn_check_heads(q.extent(0), q.extent(1), q_heads, head_dim); nn_check_heads(q_out.extent(0), q_out.extent(1), q_heads, head_dim); diff --git a/src/deltanet.vx b/src/deltanet.vx new file mode 100644 index 0000000..fb86675 --- /dev/null +++ b/src/deltanet.vx @@ -0,0 +1,225 @@ +//===- deltanet.vx - Qwen app -----------------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// One generated token through the Gated DeltaNet of a linear attention layer of Qwen3.5 and +// Qwen3.6 (#89), after the product `linear_in` and before the product `linear_out`. The math is +// that of `modeling_qwen3_5_moe.py` of transformers: +// +// - `proj`, the output of `linear_in`, has q (k_heads x 128), k (k_heads x 128), v (v_heads x 128), +// z (v_heads x 128), then b and a (v_heads each), at the offsets that the caller gives. +// - q, k and v go through a causal depthwise convolution of width 4 and a SiLU. q and k then get an +// L2 norm for each head (eps 1e-6 inside the square root), and q is multiplied by 1/sqrt(128). +// - beta = sigmoid(b), and the decay exp(g) with g = -exp(A_log) softplus(a + dt_bias). The weight +// file stores -exp(A_log) as `neg_a`. +// - Head h of v uses head h / (v_heads / k_heads) of q and k. Its state S[k][v] decays, then +// S += k (beta (v - k . S)), and the output is q . S. +// - The output gets an RMS norm for each head, times the norm weight, times silu(z). +// +// All the heads have 128 values. The state of a layer is `conv_state` [2 k_heads + v_heads, 128, 3], +// the last 3 inputs of each channel of the convolution, oldest first, and `state` [v_heads, 128, 128] +// as S[v][k]: the 128 values of k for one value of v are next to each other, so that the 32 lanes of +// a SIMD group read them in one load. Both start at zero. +import core::num; +import std::nn; +import qwen::simd; + +/// The scratch tensors of one token, in GPU memory: q and k after the convolution and the norm +/// [k_heads, 128], v after the convolution [v_heads, 128], beta and the decay exp(g) of each head of +/// v, and q . S [v_heads, 128]. +struct DeltaNetScratch { + q : Tensor, + k : Tensor, + v : Tensor, + beta : Tensor, + decay : Tensor, + o : Tensor, +} + +pub fn deltanet_scratch(k_heads : i32, v_heads : i32) -> DeltaNetScratch { + return DeltaNetScratch { + q : transfer(Tensor([k_heads, 128]), Memory::HBM), + k : transfer(Tensor([k_heads, 128]), Memory::HBM), + v : transfer(Tensor([v_heads, 128]), Memory::HBM), + beta : transfer(Tensor([v_heads]), Memory::HBM), + decay : transfer(Tensor([v_heads]), Memory::HBM), + o : transfer(Tensor([v_heads, 128]), Memory::HBM), + }; +} + +/// A tensor of zeros in GPU memory. +fn dn_zeros(a : i32, b : i32, c : i32) -> Tensor { + let mut x = Tensor([a, b, c]); + for i in 0..a { + for j in 0..b { + for k in 0..c { + x[i][j][k] = 0.0; + } + } + } + return transfer(x, Memory::HBM); +} + +/// The state of one layer at the start: zero. +pub fn deltanet_conv_state(k_heads : i32, v_heads : i32) -> Tensor { + return dn_zeros(2 * k_heads + v_heads, 128, 3); +} + +pub fn deltanet_state(v_heads : i32) -> Tensor { + return dn_zeros(v_heads, 128, 128); +} + +/// The Gated DeltaNet of one token: `y` (v_heads x 128 values, the input of `linear_out`) from `proj` +/// (the output of `linear_in`). z starts at `z_at` of `proj`, b at `b_at` and a at `a_at`. `conv` has +/// 4 taps for each of the (2 k_heads + v_heads) x 128 channels, channel c at 4 c, oldest tap +/// first. `neg_a` and `dt_bias` have v_heads values, and `norm` 128. +pub fn deltanet_step(y : &mut Tensor, conv_state : &mut Tensor, state : &mut Tensor, t : &mut DeltaNetScratch, proj : &Tensor, conv : &Tensor, neg_a : &Tensor, dt_bias : &Tensor, norm : &Tensor, z_at : i32, b_at : i32, a_at : i32, k_heads : i32, v_heads : i32, eps : f32) -> void { + let channels = (2 * k_heads + v_heads) * 128; + assert(k_heads > 0 && v_heads % k_heads == 0 && v_heads <= 64, "deltanet_step: v_heads must be a multiple of k_heads, and at most 64"); + assert(conv_state.extent(0) == 2 * k_heads + v_heads && conv_state.extent(1) == 128 && conv_state.extent(2) == 3, "deltanet_step: conv_state must be [2 k_heads + v_heads, 128, 3]"); + assert(state.extent(0) == v_heads && state.extent(1) == 128 && state.extent(2) == 128, "deltanet_step: state must be [v_heads, 128, 128]"); + assert(conv.len() == channels * 4, "deltanet_step: conv must have 4 taps for each channel"); + assert(proj.len() >= channels && proj.len() >= z_at + v_heads * 128 && proj.len() >= b_at + v_heads && proj.len() >= a_at + v_heads, "deltanet_step: proj is too short for its offsets"); + assert(neg_a.len() >= v_heads && dt_bias.len() >= v_heads && norm.len() >= 128 && y.len() >= v_heads * 128, "deltanet_step: a tensor is too short"); + deltanet_conv(&mut t.q, &mut t.k, &mut t.v, conv_state, proj, conv, k_heads, v_heads); + deltanet_gates(&mut t.beta, &mut t.decay, proj, neg_a, dt_bias, b_at, a_at, v_heads); + deltanet_recur(&mut t.o, state, &t.q, &t.k, &t.v, &t.beta, &t.decay, v_heads / k_heads, v_heads); + deltanet_gated_norm(y, &t.o, proj, norm, z_at, v_heads, eps); + return; +} + +/// The convolution and the SiLU of q, k and v, and the L2 norms of q and k. Block h does the 128 +/// channels of one head: heads 0 to k_heads - 1 of q, then those of k, then those of v. The channels +/// of `proj` are in the same order, so channel i of block h is h * 128 + i. +fn deltanet_conv(qn : &mut Tensor, kn : &mut Tensor, vv : &mut Tensor, conv_state : &mut Tensor, proj : &Tensor, conv : &Tensor, k_heads : i32, v_heads : i32) -> void { + spawn on(Topology::Device) { + for h in 0..2 * k_heads + v_heads across blocks { + let mut y = unsafe { Tensor::uninit() }; + let mut part = unsafe { Tensor::uninit() }; + for i in 0..128 across lanes { + let c = h * 128 + i; + let x0 = conv_state[h][i][0]; + let x1 = conv_state[h][i][1]; + let x2 = conv_state[h][i][2]; + let x3 = proj[c]; + let a = conv[c * 4] * x0 + conv[c * 4 + 1] * x1 + conv[c * 4 + 2] * x2 + conv[c * 4 + 3] * x3; + let s = a / (1.0 + (0.0 - a).fast_exp()); + conv_state[h][i][0] = x1; + conv_state[h][i][1] = x2; + conv_state[h][i][2] = x3; + y[i] = s; + part[i] = s * s; + } + let ss = lanes::sum(&part, 128); + let inv = 1.0 / (ss + 0.000001).sqrt(); + for i in 0..128 across lanes { + if h < k_heads { + qn[h][i] = y[i] * inv * 0.08838834764831845; + } else if h < 2 * k_heads { + kn[h - k_heads][i] = y[i] * inv; + } else { + vv[h - 2 * k_heads][i] = y[i]; + } + } + } + } + return; +} + +/// beta = sigmoid(b) and the decay exp(neg_a softplus(a + dt_bias)) of each head of v. softplus(x) +/// is x above 20, as in torch. +fn deltanet_gates(beta : &mut Tensor, decay : &mut Tensor, proj : &Tensor, neg_a : &Tensor, dt_bias : &Tensor, b_at : i32, a_at : i32, v_heads : i32) -> void { + spawn on(Topology::Device) { + for blk in 0..1 across blocks { + for j in 0..64 across lanes { + if j < v_heads { + let b = proj[b_at + j]; + beta[j] = 1.0 / (1.0 + (0.0 - b).fast_exp()); + let x = proj[a_at + j] + dt_bias[j]; + let mut sp = x; + if x <= 20.0 { + sp = simd_log(1.0 + x.fast_exp()); + } + decay[j] = (neg_a[j] * sp).fast_exp(); + } + } + } + } + return; +} + +/// The update of the state and the output q . S, for each head h of v. Block (h, vq) is one SIMD +/// group for values vq * 32 to vq * 32 + 31 of v. Lane l owns values 4 l to 4 l + 3 of k. For each +/// value of v, the lanes add up k . S, then each lane updates its 4 values of S and the lanes add up +/// q . S. Lane m keeps the output of value m. +fn deltanet_recur(o : &mut Tensor, state : &mut Tensor, qn : &Tensor, kn : &Tensor, vv : &Tensor, beta : &Tensor, decay : &Tensor, group : i32, v_heads : i32) -> void { + spawn on(Topology::Device) { + for h in 0..v_heads across blocks { + for vq in 0..4 across blocks { + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let g = h / group; + let d = 4 * l; + let q0 = qn[g][d]; + let q1 = qn[g][d + 1]; + let q2 = qn[g][d + 2]; + let q3 = qn[g][d + 3]; + let k0 = kn[g][d]; + let k1 = kn[g][d + 1]; + let k2 = kn[g][d + 2]; + let k3 = kn[g][d + 3]; + let b = beta[h]; + let dec = decay[h]; + let mut mine : f32 = 0.0; + for m in 0..32 { + let v = vq * 32 + m; + let s0 = state[h][v][d] * dec; + let s1 = state[h][v][d + 1] * dec; + let s2 = state[h][v][d + 2] * dec; + let s3 = state[h][v][d + 3] * dec; + let kv = simd_sum(s0 * k0 + s1 * k1 + s2 * k2 + s3 * k3); + let delta = (vv[h][v] - kv) * b; + let n0 = s0 + k0 * delta; + let n1 = s1 + k1 * delta; + let n2 = s2 + k2 * delta; + let n3 = s3 + k3 * delta; + state[h][v][d] = n0; + state[h][v][d + 1] = n1; + state[h][v][d + 2] = n2; + state[h][v][d + 3] = n3; + let out = simd_sum(n0 * q0 + n1 * q1 + n2 * q2 + n3 * q3); + if m == l { + mine = out; + } + } + o[h][vq * 32 + l] = mine; + } + } + } + } + } + return; +} + +/// y = rms_norm(o) * norm * silu(z), for each head of v. Block h does one head. +fn deltanet_gated_norm(y : &mut Tensor, o : &Tensor, proj : &Tensor, norm : &Tensor, z_at : i32, v_heads : i32, eps : f32) -> void { + spawn on(Topology::Device) { + for h in 0..v_heads across blocks { + let mut part = unsafe { Tensor::uninit() }; + for i in 0..128 across lanes { + let a = o[h][i]; + part[i] = a * a; + } + let ss = lanes::sum(&part, 128); + let inv = 1.0 / (ss / 128.0 + eps).sqrt(); + for i in 0..128 across lanes { + let z = proj[z_at + h * 128 + i]; + y[h * 128 + i] = o[h][i] * inv * norm[i] * (z / (1.0 + (0.0 - z).fast_exp())); + } + } + } + return; +} diff --git a/src/gated_attention.vx b/src/gated_attention.vx new file mode 100644 index 0000000..77a95ad --- /dev/null +++ b/src/gated_attention.vx @@ -0,0 +1,454 @@ +//===- gated_attention.vx - Qwen app ----------------------------------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// The full attention of one token in a layer of Qwen3.5 and Qwen3.6 (#89), between the product +// `qkv` and the product `attn_out`, with the math of `modeling_qwen3_5_moe.py` of transformers: +// +// - `qkvg`, the output of `qkv`, has q (q_heads x 256), k (kv_heads x 256), v (kv_heads x 256), +// then the gate (q_heads x 256). +// - q and k get an RMS norm for each head, times their norm weights, which the weight file stores +// as 1 + w. RoPE then turns the first `rot` values of each head (rotate_half inside those +// values), and leaves the others. +// - Attention with the scale 1/sqrt(256) over the KV cache, which is f16 [position, kv_head, 256]. +// - The output is multiplied by sigmoid(gate). +// +// The attention has the design of `vec_attention` (llama.cpp's kernel_flash_attn_ext_vec, MIT +// License, Copyright (c) 2023-2026 The ggml authors), for 256 values a head: each block is a SIMD +// group of one head of q, and lane l owns values 8 l to 8 l + 7. +import core::num; +import std::nn; +import qwen::simd; + +/// The norms and RoPE of q and k at position `pos`, and the store of k and v into the caches. Block h +/// does head h of q, then the heads of k. `cos` and `sin` have rot / 2 values for each position. +pub fn gated_norm_rope_and_store(q_out : &mut Tensor, k_cache : &mut Tensor, v_cache : &mut Tensor, qkvg : &Tensor, q_norm : &Tensor, k_norm : &Tensor, cos : &Tensor, sin : &Tensor, pos : i32, q_heads : i32, kv_heads : i32, rot : i32, eps : f32) -> void { + let half = rot / 2; + assert(q_out.extent(0) == q_heads && q_out.extent(1) == 256, "gated_norm_rope_and_store: q_out must be [q_heads, 256]"); + assert(k_cache.extent(0) > pos && k_cache.extent(1) == kv_heads && k_cache.extent(2) == 256 && v_cache.extent(0) > pos && v_cache.extent(1) == kv_heads && v_cache.extent(2) == 256, "gated_norm_rope_and_store: the caches must be [positions, kv_heads, 256] with a row for pos"); + assert(qkvg.len() >= (2 * q_heads + 2 * kv_heads) * 256 && q_norm.len() >= 256 && k_norm.len() >= 256, "gated_norm_rope_and_store: a tensor is too short"); + assert(rot % 2 == 0 && rot <= 256 && pos < cos.extent(0) && pos < sin.extent(0) && half <= cos.extent(1) && half <= sin.extent(1), "gated_norm_rope_and_store: `cos` and `sin` need a row for `pos` with rot / 2 values"); + spawn on(Topology::Device) { + for h in 0..q_heads + kv_heads across blocks { + let mut x = unsafe { Tensor::uninit() }; + let mut part = unsafe { Tensor::uninit() }; + for i in 0..256 across lanes { + let a = qkvg[h * 256 + i]; + x[i] = a; + part[i] = a * a; + } + let ss = lanes::sum(&part, 256); + let inv = 1.0 / (ss / 256.0 + eps).sqrt(); + for i in 0..256 across lanes { + let mut w = q_norm[i]; + if h >= q_heads { + w = k_norm[i]; + } + let a = x[i] * inv * w; + let mut r = a; + if i < rot { + // Value i, its partner, and the angle that they share. + let mut j = i; + let mut sign : f32 = -1.0; + let mut partner = i + half; + if i >= half { + j = i - half; + sign = 1.0; + partner = i - half; + } + let mut wp = q_norm[partner]; + if h >= q_heads { + wp = k_norm[partner]; + } + let b = x[partner] * inv * wp; + r = a * cos[pos][j] + sign * b * sin[pos][j]; + } + if h < q_heads { + q_out[h][i] = r; + } else { + k_cache[pos][h - q_heads][i] = r as f16; + v_cache[pos][h - q_heads][i] = qkvg[(q_heads + kv_heads + h - q_heads) * 256 + i] as f16; + } + } + } + } + return; +} + +/// The attention of the token at position `pos`, times sigmoid(gate): y[h * 256 + d] for each head +/// h of q. `part` is scratch space from `gated_attention_scratch`. +pub fn gated_attention(y : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, qkvg : &Tensor, pos : i32, q_heads : i32, kv_heads : i32) -> void { + assert(q.extent(0) == q_heads && q.extent(1) == 256 && q_heads % kv_heads == 0, "gated_attention: q must be [q_heads, 256], and q_heads a multiple of kv_heads"); + assert(k_cache.extent(0) > pos && k_cache.extent(1) == kv_heads && k_cache.extent(2) == 256 && v_cache.extent(0) > pos && v_cache.extent(1) == kv_heads && v_cache.extent(2) == 256, "gated_attention: the caches must be [positions, kv_heads, 256] with a row for pos"); + assert(part.extent(0) >= q_heads && part.extent(1) >= 64 && part.extent(2) == 260, "gated_attention: `part` is too small. Make it with gated_attention_scratch"); + assert(y.len() >= q_heads * 256 && qkvg.len() >= (2 * q_heads + 2 * kv_heads) * 256, "gated_attention: a tensor is too short"); + let mut nwg = 32; + if 2 * nwg * 32 < pos + 1 { + nwg = nwg * 2; + } + gated_attention_parts(part, q, k_cache, v_cache, pos, q_heads, q_heads / kv_heads, nwg, 0.0625); + gated_attention_merge(y, part, qkvg, nwg, q_heads, (q_heads + 2 * kv_heads) * 256); + return; +} + +/// The scratch space of `gated_attention`, on the CPU: up to 64 parts for each head of q, each the sum +/// of V (256 values), the largest score, and the sum of the weights. +pub fn gated_attention_scratch(q_heads : i32) -> Tensor { + return Tensor([q_heads, 64, 260]); +} + +/// The parts of `gated_attention`. Block (h, w) is a SIMD group for head h of q. It does the blocks of +/// 32 positions w, w + nwg, w + 2 nwg, ... up to `pos`, and writes part[h][w]: the sum of V, not +/// divided, then the largest score and the sum of the weights. For each row, the lanes add up their +/// parts of q . k, and lane r keeps the score of row r. Each lane then takes the weight of each row +/// from the lane that keeps it, for the sum of V. +fn gated_attention_parts(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, pos : i32, q_heads : i32, group : i32, nwg : i32, scale : f32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for w in 0..nwg across blocks { + let mut stats = unsafe { Tensor::uninit() }; + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let g = h / group; + let d = 8 * l; + let q0 = q[h][d] * scale; + let q1 = q[h][d + 1] * scale; + let q2 = q[h][d + 2] * scale; + let q3 = q[h][d + 3] * scale; + let q4 = q[h][d + 4] * scale; + let q5 = q[h][d + 5] * scale; + let q6 = q[h][d + 6] * scale; + let q7 = q[h][d + 7] * scale; + let mut big : f32 = -3.0e38; + let mut total : f32 = 0.0; + let mut o0 : f32 = 0.0; + let mut o1 : f32 = 0.0; + let mut o2 : f32 = 0.0; + let mut o3 : f32 = 0.0; + let mut o4 : f32 = 0.0; + let mut o5 : f32 = 0.0; + let mut o6 : f32 = 0.0; + let mut o7 : f32 = 0.0; + let chunks = (pos + 32) / 32; + let mut c = w; + while c < chunks { + let r0 = c * 32; + let mut mine : f32 = -3.0e38; + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > pos { + kept = pos; + } + let k0 = half4_at(k_cache, kept, g, d, 0); + let k1 = half4_at(k_cache, kept, g, d, 1); + let k2 = half4_at(k_cache, kept, g, d, 2); + let k3 = half4_at(k_cache, kept, g, d, 3); + let k4 = half4_at(k_cache, kept, g, d + 4, 0); + let k5 = half4_at(k_cache, kept, g, d + 4, 1); + let k6 = half4_at(k_cache, kept, g, d + 4, 2); + let k7 = half4_at(k_cache, kept, g, d + 4, 3); + let mut score = simd_sum(((k0 * q0 + k1 * q1) + (k2 * q2 + k3 * q3)) + ((k4 * q4 + k5 * q5) + (k6 * q6 + k7 * q7))); + if row > pos { + score = -3.0e38; + } + if r == l { + mine = score; + } + } + let top = big.max(simd_max(mine)); + let shrink = (big - top).fast_exp(); + let p = (mine - top).fast_exp(); + total = total * shrink + simd_sum(p); + o0 = o0 * shrink; + o1 = o1 * shrink; + o2 = o2 * shrink; + o3 = o3 * shrink; + o4 = o4 * shrink; + o5 = o5 * shrink; + o6 = o6 * shrink; + o7 = o7 * shrink; + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > pos { + kept = pos; + } + let pr = simd_value(p, r); + o0 = o0 + half4_at(v_cache, kept, g, d, 0) * pr; + o1 = o1 + half4_at(v_cache, kept, g, d, 1) * pr; + o2 = o2 + half4_at(v_cache, kept, g, d, 2) * pr; + o3 = o3 + half4_at(v_cache, kept, g, d, 3) * pr; + o4 = o4 + half4_at(v_cache, kept, g, d + 4, 0) * pr; + o5 = o5 + half4_at(v_cache, kept, g, d + 4, 1) * pr; + o6 = o6 + half4_at(v_cache, kept, g, d + 4, 2) * pr; + o7 = o7 + half4_at(v_cache, kept, g, d + 4, 3) * pr; + } + big = top; + c = c + nwg; + } + part[h][w][d] = o0; + part[h][w][d + 1] = o1; + part[h][w][d + 2] = o2; + part[h][w][d + 3] = o3; + part[h][w][d + 4] = o4; + part[h][w][d + 5] = o5; + part[h][w][d + 6] = o6; + part[h][w][d + 7] = o7; + // Every lane has the same largest score and sum of the weights. Lanes 0 and 1 keep them for + // the next loop. + if l < 2 { + let mut x = big; + if l == 1 { + x = total; + } + stats[s][l] = x; + } + } + for l in 0..2 across lanes(32) { + part[h][w][256 + l] = stats[s][l]; + } + } + } + } + } + return; +} + +/// Merges the first `parts` parts of `gated_attention_parts` for each head of q, and multiplies by +/// sigmoid of the gate, which starts at `gate_at` of `qkvg`. A block of 32 lanes does 32 values of one +/// head, a value for each lane. +fn gated_attention_merge(y : &mut Tensor, part : &Tensor, qkvg : &Tensor, parts : i32, q_heads : i32, gate_at : i32) -> void { + spawn on(Topology::Device) { + for h in 0..q_heads across blocks { + for dq in 0..8 across blocks { + let mut top = unsafe { Tensor::uninit() }; + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let mut m : f32 = -3.0e38; + let mut c = l; + while c < parts { + m = m.max(part[h][c][256]); + c = c + 32; + } + top[s][l] = m; + } + let big = lanes::max(&top[s], 32); + for l in 0..32 across lanes(32) { + let d = dq * 32 + l; + let mut total : f32 = 0.0; + let mut acc : f32 = 0.0; + for c in 0..parts { + let w = (part[h][c][256] - big).fast_exp(); + total = total + w * part[h][c][257]; + acc = acc + w * part[h][c][d]; + } + let gate = qkvg[gate_at + h * 256 + d]; + y[h * 256 + d] = acc / total / (1.0 + (0.0 - gate).fast_exp()); + } + } + } + } + } + return; +} + +// ------------------------------------------------------------------ the positions of a round --- + +/// `gated_attention` for the n positions of a round, after `pf_gated_norm_rope_and_store` stored +/// their rows in the caches: position t is at start + t, with q[t], qkvg[t] and y[t]. Each position +/// gets the bits of `gated_attention` at its position, with 2 launches for all n. `part` is scratch +/// space from `gated_attention_rows_scratch`. +pkg fn gated_attention_rows(y : &mut Tensor, part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, qkvg : &Tensor, start : i32, n : i32, q_heads : i32, kv_heads : i32) -> void { + assert(n >= 1 && q.extent(0) >= n && q.extent(1) == q_heads && q.extent(2) == 256 && q_heads % kv_heads == 0, "gated_attention_rows: q must be [n, q_heads, 256], and q_heads a multiple of kv_heads"); + assert(k_cache.extent(0) >= start + n && k_cache.extent(1) == kv_heads && k_cache.extent(2) == 256 && v_cache.extent(0) >= start + n && v_cache.extent(1) == kv_heads && v_cache.extent(2) == 256, "gated_attention_rows: the caches must be [positions, kv_heads, 256] with rows for the n positions"); + assert(part.extent(0) >= n && part.extent(1) == q_heads && part.extent(2) >= 64 && part.extent(3) == 260, "gated_attention_rows: `part` is too small. Make it with gated_attention_rows_scratch"); + assert(y.extent(0) >= n && y.extent(1) >= q_heads * 256 && qkvg.extent(0) >= n && qkvg.extent(1) >= (2 * q_heads + 2 * kv_heads) * 256, "gated_attention_rows: a tensor is too short"); + gated_attention_parts_rows(part, q, k_cache, v_cache, start, n, q_heads, q_heads / kv_heads, 0.0625); + gated_attention_merge_rows(y, part, qkvg, start, n, q_heads, (q_heads + 2 * kv_heads) * 256); + return; +} + +/// The scratch space of `gated_attention_rows` for up to n positions, on the CPU. +pkg fn gated_attention_rows_scratch(n : i32, q_heads : i32) -> Tensor { + return Tensor([n, q_heads, 64, 260]); +} + +/// `gated_attention_parts` for the n positions of a round: position t is at start + t, with q[t], +/// and with the parts that `gated_attention` takes at start + t. Block (t, h, w) does part[t][h][w] +/// with the arithmetic of block (h, w) of `gated_attention_parts`, so each position gets the bits +/// of `gated_attention`. A block with w at or above the parts of its position writes a part that +/// `gated_attention_merge_rows` does not read. +fn gated_attention_parts_rows(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, start : i32, n : i32, q_heads : i32, group : i32, scale : f32) -> void { + spawn on(Topology::Device) { + for t in 0..n across blocks { + for h in 0..q_heads across blocks { + for w in 0..64 across blocks { + let mut stats = unsafe { Tensor::uninit() }; + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let pos = start + t; + // The parts of `gated_attention` at pos. + let mut nwg = 32; + if 2 * nwg * 32 < pos + 1 { + nwg = nwg * 2; + } + let g = h / group; + let d = 8 * l; + let q0 = q[t][h][d] * scale; + let q1 = q[t][h][d + 1] * scale; + let q2 = q[t][h][d + 2] * scale; + let q3 = q[t][h][d + 3] * scale; + let q4 = q[t][h][d + 4] * scale; + let q5 = q[t][h][d + 5] * scale; + let q6 = q[t][h][d + 6] * scale; + let q7 = q[t][h][d + 7] * scale; + let mut big : f32 = -3.0e38; + let mut total : f32 = 0.0; + let mut o0 : f32 = 0.0; + let mut o1 : f32 = 0.0; + let mut o2 : f32 = 0.0; + let mut o3 : f32 = 0.0; + let mut o4 : f32 = 0.0; + let mut o5 : f32 = 0.0; + let mut o6 : f32 = 0.0; + let mut o7 : f32 = 0.0; + let chunks = (pos + 32) / 32; + let mut c = w; + if w >= nwg { + c = chunks; + } + while c < chunks { + let r0 = c * 32; + let mut mine : f32 = -3.0e38; + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > pos { + kept = pos; + } + let k0 = half4_at(k_cache, kept, g, d, 0); + let k1 = half4_at(k_cache, kept, g, d, 1); + let k2 = half4_at(k_cache, kept, g, d, 2); + let k3 = half4_at(k_cache, kept, g, d, 3); + let k4 = half4_at(k_cache, kept, g, d + 4, 0); + let k5 = half4_at(k_cache, kept, g, d + 4, 1); + let k6 = half4_at(k_cache, kept, g, d + 4, 2); + let k7 = half4_at(k_cache, kept, g, d + 4, 3); + let mut score = simd_sum(((k0 * q0 + k1 * q1) + (k2 * q2 + k3 * q3)) + ((k4 * q4 + k5 * q5) + (k6 * q6 + k7 * q7))); + if row > pos { + score = -3.0e38; + } + if r == l { + mine = score; + } + } + let top = big.max(simd_max(mine)); + let shrink = (big - top).fast_exp(); + let p = (mine - top).fast_exp(); + total = total * shrink + simd_sum(p); + o0 = o0 * shrink; + o1 = o1 * shrink; + o2 = o2 * shrink; + o3 = o3 * shrink; + o4 = o4 * shrink; + o5 = o5 * shrink; + o6 = o6 * shrink; + o7 = o7 * shrink; + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > pos { + kept = pos; + } + let pr = simd_value(p, r); + o0 = o0 + half4_at(v_cache, kept, g, d, 0) * pr; + o1 = o1 + half4_at(v_cache, kept, g, d, 1) * pr; + o2 = o2 + half4_at(v_cache, kept, g, d, 2) * pr; + o3 = o3 + half4_at(v_cache, kept, g, d, 3) * pr; + o4 = o4 + half4_at(v_cache, kept, g, d + 4, 0) * pr; + o5 = o5 + half4_at(v_cache, kept, g, d + 4, 1) * pr; + o6 = o6 + half4_at(v_cache, kept, g, d + 4, 2) * pr; + o7 = o7 + half4_at(v_cache, kept, g, d + 4, 3) * pr; + } + big = top; + c = c + nwg; + } + part[t][h][w][d] = o0; + part[t][h][w][d + 1] = o1; + part[t][h][w][d + 2] = o2; + part[t][h][w][d + 3] = o3; + part[t][h][w][d + 4] = o4; + part[t][h][w][d + 5] = o5; + part[t][h][w][d + 6] = o6; + part[t][h][w][d + 7] = o7; + // Every lane has the same largest score and sum of the weights. Lanes 0 and 1 keep + // them for the next loop. + if l < 2 { + let mut x = big; + if l == 1 { + x = total; + } + stats[s][l] = x; + } + } + for l in 0..2 across lanes(32) { + part[t][h][w][256 + l] = stats[s][l]; + } + } + } + } + } + } + return; +} + +/// `gated_attention_merge` for the n positions of `gated_attention_parts_rows`: y[t] and qkvg[t] +/// are the rows of position t, at start + t. +fn gated_attention_merge_rows(y : &mut Tensor, part : &Tensor, qkvg : &Tensor, start : i32, n : i32, q_heads : i32, gate_at : i32) -> void { + spawn on(Topology::Device) { + for t in 0..n across blocks { + for h in 0..q_heads across blocks { + for dq in 0..8 across blocks { + let mut top = unsafe { Tensor::uninit() }; + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let mut parts = 32; + if 2 * parts * 32 < start + t + 1 { + parts = parts * 2; + } + let mut m : f32 = -3.0e38; + let mut c = l; + while c < parts { + m = m.max(part[t][h][c][256]); + c = c + 32; + } + top[s][l] = m; + } + let big = lanes::max(&top[s], 32); + for l in 0..32 across lanes(32) { + let mut parts = 32; + if 2 * parts * 32 < start + t + 1 { + parts = parts * 2; + } + let d = dq * 32 + l; + let mut total : f32 = 0.0; + let mut acc : f32 = 0.0; + for c in 0..parts { + let w = (part[t][h][c][256] - big).fast_exp(); + total = total + w * part[t][h][c][257]; + acc = acc + w * part[t][h][c][d]; + } + let gate = qkvg[t][gate_at + h * 256 + d]; + y[t][h * 256 + d] = acc / total / (1.0 + (0.0 - gate).fast_exp()); + } + } + } + } + } + } + return; +} diff --git a/src/main.vx b/src/main.vx index a8fcde7..ed9ad98 100644 --- a/src/main.vx +++ b/src/main.vx @@ -7,7 +7,7 @@ //===----------------------------------------------------------------------===// // Generates tokens with greedy decoding, on the GPU: // -// vxc src/main.vx --package qwen=src --host default \ +// vxc -O2 src/main.vx --package qwen=src --host default \ // --machine ~/.vx/current/fleet/m4-uma.vx -- WEIGHTS --tokens 750,75698,1445 --steps 16 // vxc src/main.vx ... -- WEIGHTS --tokenizer TOKENIZER --prompt "def fibonacci(n):" --steps 64 // vxc src/main.vx ... -- WEIGHTS --tokenizer TOKENIZER --chat --prompt-file FILE --steps 512 @@ -19,59 +19,96 @@ // --prompt-file FILE. The program prints the prompt and the text that it generates. It stops at a // special token, such as <|im_end|>, or after --steps tokens. --chat puts the prompt in the chat // format of the Instruct models and prints only the reply. --lines prints the lines of --tokens -// in place of the text. +// in place of the text. Qwen3.5 and Qwen3.6 think before they reply by default; with --chat, the +// prompt turns the thinking off, as the chat template does with enable_thinking=false, unless +// --think is given. --ignore-eos does not stop at a special token, so the text runs for --steps +// tokens, as llama.cpp's --ignore-eos. --prompt-runs K (Qwen3.5 and Qwen3.6) runs the prompt K +// times, each on a fresh state, and prints the time of each run: the first run includes the first +// launch of each kernel. The tokens come from the last run. import core::convert; +import std::fs; +import std::io; +import std::libc; +import std::root; +import std::string; import std::time; import std::vec; import qwen::weights; import qwen::model; +import qwen::mtp35; +import qwen::qwen35; +import qwen::prefill35; import qwen::prefill; import qwen::session; import qwen::speculate; import qwen::round; +import qwen::round35; import qwen::tokenizer; /// The options of the command line. struct Options { - weights : *const i8, - tokens : *const i8, - tokenizer : *const i8, - prompt : *const i8, - prompt_file : *const i8, - steps : *const i8, + weights : String, + tokens : String, + tokenizer : String, + prompt : String, + prompt_file : String, + steps : String, has_tokens : bool, has_tokenizer : bool, has_prompt : bool, has_prompt_file : bool, has_steps : bool, - context : *const i8, + context : String, has_context : bool, - requests : *const i8, + requests : String, has_requests : bool, - replies : *const i8, + replies : String, has_replies : bool, session : bool, chat : bool, lines : bool, - draft : *const i8, + draft : String, has_draft : bool, + mtp : String, + has_mtp : bool, + mtp_vocab : String, + has_mtp_vocab : bool, + think : bool, + ignore_eos : bool, + prompt_runs : String, + has_prompt_runs : bool, } -/// The options of `argv`. Asserts that they are complete and that they fit together. -fn parse_options(argc : i32, argv : *mut *mut i8) -> Options { +/// A copy of `word`. +fn copy(word : &String) -> String { + let mut c = String::new(); + c.push_str(word); + return c; +} + +/// The options of the words of the command line. Asserts that they are complete and that they fit +/// together. +fn parse_options(args : &Vec) -> Options { + let argc = args.len(); assert(argc >= 4, "give: WEIGHTS --tokens 1,2,3 --steps N, or WEIGHTS --tokenizer FILE (--prompt TEXT | --prompt-file FILE) [--chat] [--lines] --steps N"); - let empty : *const i8 = ""; let mut o = Options { - weights: unsafe { argv[1] }, tokens: empty, tokenizer: empty, prompt: empty, prompt_file: empty, - steps: empty, has_tokens: false, has_tokenizer: false, has_prompt: false, has_prompt_file: false, - has_steps: false, context: empty, has_context: false, requests: empty, has_requests: false, replies: empty, has_replies: false, session: false, chat: false, lines: false, draft: empty, has_draft: false, + weights: copy(args.get_ref(1)), tokens: String::new(), tokenizer: String::new(), prompt: String::new(), prompt_file: String::new(), + steps: String::new(), has_tokens: false, has_tokenizer: false, has_prompt: false, has_prompt_file: false, + has_steps: false, context: String::new(), has_context: false, requests: String::new(), has_requests: false, replies: String::new(), has_replies: false, session: false, chat: false, lines: false, draft: String::new(), has_draft: false, mtp: String::new(), has_mtp: false, mtp_vocab: String::new(), has_mtp_vocab: false, think: false, ignore_eos: false, prompt_runs: String::new(), has_prompt_runs: false, }; let mut i = 2; while i < argc { - let name = unsafe { argv[i] }; + // One copy of each word as a C string. It is never freed, as the words of argv are not. + let name = args.get_ref(i).as_c_str(); if same(name, "--chat") { o.chat = true; i = i + 1; + } else if same(name, "--think") { + o.think = true; + i = i + 1; + } else if same(name, "--ignore-eos") { + o.ignore_eos = true; + i = i + 1; } else if same(name, "--session") { o.session = true; i = i + 1; @@ -80,34 +117,43 @@ fn parse_options(argc : i32, argv : *mut *mut i8) -> Options { i = i + 1; } else { assert(i + 1 < argc, "give: WEIGHTS --tokens 1,2,3 --steps N, or WEIGHTS --tokenizer FILE (--prompt TEXT | --prompt-file FILE) [--chat] [--lines] --steps N"); - let value = unsafe { argv[i + 1] }; + let value = args.get_ref(i + 1); if same(name, "--tokens") { - o.tokens = value; + o.tokens = copy(value); o.has_tokens = true; } else if same(name, "--tokenizer") { - o.tokenizer = value; + o.tokenizer = copy(value); o.has_tokenizer = true; } else if same(name, "--prompt") { - o.prompt = value; + o.prompt = copy(value); o.has_prompt = true; } else if same(name, "--prompt-file") { - o.prompt_file = value; + o.prompt_file = copy(value); o.has_prompt_file = true; } else if same(name, "--context") { - o.context = value; + o.context = copy(value); o.has_context = true; } else if same(name, "--requests") { - o.requests = value; + o.requests = copy(value); o.has_requests = true; } else if same(name, "--replies") { - o.replies = value; + o.replies = copy(value); o.has_replies = true; } else if same(name, "--draft") { - o.draft = value; + o.draft = copy(value); o.has_draft = true; + } else if same(name, "--mtp") { + o.mtp = copy(value); + o.has_mtp = true; + } else if same(name, "--mtp-vocab") { + o.mtp_vocab = copy(value); + o.has_mtp_vocab = true; + } else if same(name, "--prompt-runs") { + o.prompt_runs = copy(value); + o.has_prompt_runs = true; } else { assert(same(name, "--steps"), "give: WEIGHTS --tokens 1,2,3 --steps N, or WEIGHTS --tokenizer FILE (--prompt TEXT | --prompt-file FILE) [--chat] [--lines] --steps N"); - o.steps = value; + o.steps = copy(value); o.has_steps = true; } i = i + 2; @@ -122,19 +168,19 @@ fn parse_options(argc : i32, argv : *mut *mut i8) -> Options { let no_text = !o.has_prompt && !o.has_prompt_file; assert((o.has_tokens && no_text) || (o.has_tokenizer && !o.has_tokens && one_text), "give: WEIGHTS --tokens 1,2,3 --steps N, or WEIGHTS --tokenizer FILE (--prompt TEXT | --prompt-file FILE) [--chat] [--lines] --steps N"); assert(o.has_tokenizer || (!o.chat && !o.lines), "--chat and --lines need --tokenizer"); + assert(o.chat || !o.think, "--think needs --chat"); return o; } /// The comma-separated numbers of `text`. Asserts that it has only digits and commas, and no empty /// number. -fn parse_numbers(text : *const i8) -> Vec { +fn parse_numbers(text : &String) -> Vec { let mut numbers = Vec::new(); let mut value : i32 = 0; let mut digits = 0; let mut empty = false; - let mut i : i64 = 0; - let mut ch = i32::from(unsafe { text[0] }); - while ch != 0 { + for i in 0..text.len() { + let ch = i32::from(text.byte(i)); if ch == 44 { empty = empty || digits == 0; numbers.push(value); @@ -145,8 +191,6 @@ fn parse_numbers(text : *const i8) -> Vec { value = value * 10 + (ch - 48); digits = digits + 1; } - i = i + 1; - ch = i32::from(unsafe { text[i] }); } assert(!empty && digits > 0, "an empty number in a comma-separated list"); numbers.push(value); @@ -180,20 +224,44 @@ fn read_logit(logits : &Tensor, token : i32) -> f32 { /// Whether the C string `a` is `b`. fn same(a : *const i8, b : *const i8) -> bool { - return unsafe { strcmp(a, b) } == 0; + return unsafe { string_compare(a, b) } == 0; +} + +/// The bytes of `a` and then those of `b`, in new memory. +fn join_text(a : &Text, b : &Text) -> Text { + let length = a.length + b.length; + let bytes : *mut i8 = unsafe { malloc((length + 1) as usize) }; + copy_bytes(bytes, a.bytes, a.length); + copy_bytes(offset_mut(bytes, a.length), b.bytes, b.length); + return Text { + bytes: bytes, length: length + }; } /// The token ids of the prompt: the numbers of --tokens, or the tokens of the text. -fn prompt_ids(o : &Options, t : &Tokenizer) -> Vec { +fn prompt_ids(files : &Files, o : &Options, t : &Tokenizer) -> Vec { if o.has_tokens { - return parse_numbers(o.tokens); + return parse_numbers(&o.tokens); } let text = if o.has_prompt { - c_text(o.prompt) + c_text(o.prompt.as_c_str()) } else { - read_text_file(o.prompt_file) + read_text_file(files, &o.prompt_file) }; - let full = if o.chat { + let full = if o.chat && weight_file_arch(files, &o.weights) == 1 { + // The chat template of Qwen3.5 and Qwen3.6 opens the reply with a block. + let reply = if o.think { + c_text(" +") + } else { + c_text(" + + + +") + }; + join_text(&chat_text(&text), &reply) + } else if o.chat { chat_text(&text) } else { text @@ -204,22 +272,28 @@ fn prompt_ids(o : &Options, t : &Tokenizer) -> Vec { } /// Shows token number `step`, as the loop of `main` does: its text, or a line with its logit. -/// Gives false at the end of the text, where the loop stops. -fn show(t : &Tokenizer, w : &Weights, text_mode : bool, step : i32, token : i32, logit : f32) -> bool { +/// Gives false at the end of the text, where the loop stops. With `eos` -1 (--ignore-eos), the text +/// has no end. +fn show(out : &mut Stdout, t : &Tokenizer, eos : i32, text_mode : bool, step : i32, token : i32, logit : f32) -> bool { if text_mode { - if is_special(t, token) || token == w.config.eos_token_id { + if ends_text(t, eos, token) { return false; } - write_token(t, token); + write_token(out, t, token); } else { println!("step={} token={} logit={};", step, token, logit); } return true; } +/// True when `token` ends the text: a special token or `eos`. Nothing ends it when `eos` is -1. +fn ends_text(t : &Tokenizer, eos : i32, token : i32) -> bool { + return eos >= 0 && (is_special(t, token) || token == eos); +} + /// The logit `token` of position j of a round. -fn round_logit(r : &Round, j : i32, token : i32) -> f32 { - let h = transfer(&r.logits, Memory::CPU_DRAM); +fn round_logit(logits : &Tensor, j : i32, token : i32) -> f32 { + let h = transfer(logits, Memory::CPU_DRAM); return h[j][token]; } @@ -229,7 +303,7 @@ fn round_logit(r : &Round, j : i32, token : i32) -> f32 { /// row that accepted nothing, until a longer match than theirs appears. A draft has up to `max` /// tokens. `first` is the first generated token, from the logits in `s.logits`. Shows the same /// `steps` tokens as the loop of `main`, and gives the number of tokens after the first. -fn generate_with_drafts(w : &Weights, s : &mut State, t : &Tokenizer, text_mode : bool, prompt : &Vec, first : i32, steps : i32, max : i32, start : &mut Instant) -> i32 { +fn generate_with_drafts(out : &mut Stdout, w : &Weights, s : &mut State, t : &Tokenizer, eos : i32, text_mode : bool, prompt : &Vec, first : i32, steps : i32, max : i32, start : &mut Instant) -> i32 { assert(can_round(w), "--draft needs a model of Q4_0 experts with QK norms, head_dim 128 and a 6-bit lm_head"); assert(max >= 1 && max < ROUND_MAX, "--draft must be 1 to ROUND_MAX - 1"); assert(steps >= ROUND_MAX, "--draft needs --steps of at least ROUND_MAX"); @@ -270,7 +344,7 @@ fn generate_with_drafts(w : &Weights, s : &mut State, t : &Tokenizer, text_mode // Rounds in a row that accepted nothing, and the length of the match of the last of them. let mut misses = 0; let mut missed_length = 0; - let mut going = show(t, w, text_mode, 0, token, read_logit(&s.logits, token)); + let mut going = show(out, t, eos, text_mode, 0, token, read_logit(&s.logits, token)); while going && step + 1 < steps { let room = steps - step - 1; let m = longest_match(&context); @@ -308,7 +382,7 @@ fn generate_with_drafts(w : &Weights, s : &mut State, t : &Tokenizer, text_mode if !text_mode { logit = read_logit(&s.logits, token); } - going = show(t, w, text_mode, step, token, logit); + going = show(out, t, eos, text_mode, step, token, logit); j = j + 1; } run = i32::min(run * 2, AHEAD); @@ -332,9 +406,9 @@ fn generate_with_drafts(w : &Weights, s : &mut State, t : &Tokenizer, text_mode step = step + 1; let mut logit : f32 = 0.0; if !text_mode { - logit = round_logit(&r, j, token); + logit = round_logit(&r.logits, j, token); } - going = show(t, w, text_mode, step, token, logit); + going = show(out, t, eos, text_mode, step, token, logit); more = j < k && draft[j] == token; if more { accepted = accepted + 1; @@ -354,26 +428,573 @@ fn generate_with_drafts(w : &Weights, s : &mut State, t : &Tokenizer, text_mode return step; } -fn main(argc : i32, argv : *mut *mut i8) -> i32 { - let o = parse_options(argc, argv); +/// `generate_with_drafts` for a Qwen3.5 or Qwen3.6 model (src/round35.vx). After each round, +/// `commit_round35` writes the DeltaNet states of the tokens that the round keeps. The first step +/// is a plain step that compiles the kernels of a token, so the clock starts after it and the +/// count of tokens leaves it out. +fn generate_with_drafts35(out : &mut Stdout, w : &Qwen35Weights, s : &mut Qwen35State, t : &Tokenizer, eos : i32, text_mode : bool, prompt : &Vec, first : i32, steps : i32, max : i32, start : &mut Instant) -> i32 { + assert(can_round35(w), "--draft needs a model of Q4_0 layers and experts and a 6-bit lm_head"); + assert(max >= 1 && max < ROUND_MAX, "--draft must be 1 to ROUND_MAX - 1"); + assert(steps >= ROUND_MAX, "--draft needs --steps of at least ROUND_MAX"); + let mut r = new_round35(&w.config); + let mut ring = Vec::new(); + for j in 0..AHEAD { + ring.push(Slot { + next: transfer(Tensor([1]), Memory::HBM), + }); + } + let mut context = Vec::new(); + for i in 0..prompt.len() { + context.push(prompt[i]); + } + let mut token = first; + context.push(token); + // The position of `token`, which is not in the KV cache yet. + let mut pos = prompt.len(); + let mut step = 0; + let mut going = show(out, t, eos, text_mode, 0, token, read_logit(&s.logits, token)); + if going { + let mut h = Tensor([1]); + h[0] = token; + let input = transfer(h, Memory::HBM); + run_qwen35_layers(w, s, &input, pos); + predict_qwen35(w, s, &mut ring[0].next); + token = read_token(&ring[0].next); + context.push(token); + step = 1; + pos = pos + 1; + going = show(out, t, eos, text_mode, step, token, read_logit(&s.logits, token)); + } + // One run of the round kernels for each n to 8, so that their compile time is not in the time + // of a token. They write rows of the KV cache that later tokens write again before they read + // them, and no DeltaNet state. + let mut warm = Vec::new(); + for n in 1..9 { + warm.push(token); + run_round35(w, s, &mut r, &warm, pos, n); + } + let _ready = transfer(&r.next, Memory::CPU_DRAM); + *start = Instant::now(); + let first_step = step; + let mut run = 1; + let mut rounds = 0; + let mut drafted = 0; + let mut accepted = 0; + while going && step + 1 < steps { + let room = steps - step - 1; + let m = longest_match(&context); + // No backoff after misses, unlike `generate_with_drafts`: a round of 2 positions costs little + // more than a step, so the simulation of `draft_length35` found drafts after misses best. + let k_max = i32::min(i32::min(draft_length35(m.length), max), room - 1); + let draft = tokens_after(&context, m.end, k_max); + let k = draft.len(); + if k == 0 { + let mut n = 1; + if text_mode { + n = i32::min(run, room); + } + let mut h = Tensor([1]); + h[0] = token; + let input = transfer(h, Memory::HBM); + run_qwen35_layers(w, s, &input, pos); + predict_qwen35(w, s, &mut ring[0].next); + for j in 1..n { + run_qwen35_layers(w, s, &ring[j - 1].next, pos + j); + predict_qwen35(w, s, &mut ring[j].next); + } + let mut j = 0; + while j < n && going { + token = read_token(&ring[j].next); + context.push(token); + step = step + 1; + pos = pos + 1; + let mut logit : f32 = 0.0; + if !text_mode { + logit = read_logit(&s.logits, token); + } + going = show(out, t, eos, text_mode, step, token, logit); + j = j + 1; + } + run = i32::min(run * 2, AHEAD); + } else { + run = 1; + let mut inputs = Vec::new(); + inputs.push(token); + for i in 0..k { + inputs.push(draft[i]); + } + run_round35(w, s, &mut r, &inputs, pos, k + 1); + let choice = transfer(&r.next, Memory::CPU_DRAM); + rounds = rounds + 1; + drafted = drafted + k; + let mut j = 0; + let mut more = true; + while more && going { + token = choice[j]; + context.push(token); + step = step + 1; + let mut logit : f32 = 0.0; + if !text_mode { + logit = round_logit(&r.logits, j, token); + } + going = show(out, t, eos, text_mode, step, token, logit); + more = j < k && draft[j] == token; + if more { + accepted = accepted + 1; + j = j + 1; + } + } + // Inputs 0 to j of the round are kept: the last accepted token and the j draft tokens + // before the first miss. + commit_round35(w, s, &r, j + 1); + pos = pos + j + 1; + } + } + println!("rounds={} drafted={} accepted={};", rounds, drafted, accepted); + return step - first_step; +} + +/// The share of kept drafts from which a round of MTP drafts takes its longest drafts +/// (`generate_with_mtp35`). +const MTP_LONG_SHARE : f64 = 0.85; + +/// The share of kept drafts from which a round takes the second number of `--mtp K,L` drafts. +const MTP_LONGER_SHARE : f64 = 0.95; + +/// With --draft D and --mtp, the shortest match in the context from which a round drafts up to D +/// tokens of the context and not from the MTP layer. `--draft D,M` sets it to M. A match of 16 is +/// the longest that `longest_match` finds. Shorter matches often give drafts that the round does not +/// keep, and such a round costs more than the MTP round that it replaces. +const MTP_CONTEXT_MATCH : i32 = MATCH_MAX; + +/// The tokens that an MTP draft comes from without --mtp-vocab: ids 0 to MTP_VOCAB - 1. On the +/// tuning prompts, the drafts of Qwen3.6-35B-A3B from these tokens are kept as often as those from +/// all 248,320, and the rows of lm_head that they read are a quarter. +const MTP_VOCAB : i32 = 65536; + +/// Puts `token` into a tensor of one value in GPU memory. +fn upload_token(token : i32) -> Tensor { + let mut h = Tensor([1]); + h[0] = token; + return transfer(h, Memory::HBM); +} + +/// Drafts from the MTP layer of the model (src/mtp35.vx), checked by rounds as in +/// `generate_with_drafts35`. Each round drafts up to `max` tokens, one row of the MTP layer each, +/// from the last token and h of the position before it; then `run_round35` checks them. The rows of +/// the tokens that the round keeps then run again with the true h of the model, from `r.xn`. The +/// prompt must have filled the MTP rows before its last position (`prefill_qwen35_mtp`), and s.xn +/// must hold h of its last position (`predict_qwen35`). The first step is a plain step that +/// compiles the kernels of a token, so the clock starts after it and the count of tokens leaves +/// it out. The drafts come from tokens 0 to vocab - 1 (`mtp35_step`). +/// +/// A round of 1 draft (2 positions) costs little more than a plain step, but 2 or 3 drafts (3 or 4 +/// positions) cost a second pass of the round kernels, which take 2 positions at a time. So a round +/// drafts `max` tokens while the drafts are likely to be kept, and 1 token otherwise: `kept` is a +/// running mean of the share of drafts that the rounds keep, of each draft up to the first miss. +/// With the cost of a round at 4 positions about 1.7 times that at 2, `max` drafts pay from a +/// share of about MTP_LONG_SHARE. +fn generate_with_mtp35(out : &mut Stdout, w : &Qwen35Weights, s : &mut Qwen35State, m : &mut Mtp35State, t : &Tokenizer, eos : i32, text_mode : bool, prompt : &Vec, first : i32, steps : i32, max : i32, long : i32, long_share : f64, ctx_max : i32, ctx_match : i32, vocab : i32, start : &mut Instant) -> i32 { + assert(can_round35(w), "--mtp needs a model of Q4_0 layers and experts and a 6-bit lm_head"); + assert(w.mtp.len() == 1, "--mtp needs a weight file with the MTP layer"); + assert(max >= 1 && max < ROUND_MAX, "--mtp must be 1 to ROUND_MAX - 1"); + assert(long < ROUND_MAX, "the second number of --mtp must be below ROUND_MAX"); + assert(ctx_max < ROUND_MAX, "the drafts from the context must be below ROUND_MAX"); + let most = i32::max(i32::max(max, long), ctx_max); + let c = &w.config; + let mut r = new_round35(c); + let mut slots = Vec::new(); + for j in 0..ROUND_MAX + 1 { + slots.push(Slot { + next: transfer(Tensor([1]), Memory::HBM), + }); + } + let mut token = first; + let mut context = Vec::new(); + for i in 0..prompt.len() { + context.push(prompt[i]); + } + context.push(token); + // The position of `token`, which is not in the KV cache yet. m.h holds h of the position before. + let mut pos = prompt.len(); + copy_f32(&mut m.h, &s.xn, c.hidden_size); + let mut step = 0; + let mut going = show(out, t, eos, text_mode, 0, token, read_logit(&s.logits, token)); + if going { + // A plain step, and the MTP row of its token, which also compile their kernels. + m.token = upload_token(token); + mtp35_step(w, s, m, pos - 1, true, vocab); + let input = upload_token(token); + run_qwen35_layers(w, s, &input, pos); + predict_qwen35(w, s, &mut slots[2].next); + copy_f32(&mut m.h, &s.xn, c.hidden_size); + token = read_token(&slots[2].next); + context.push(token); + step = 1; + pos = pos + 1; + going = show(out, t, eos, text_mode, step, token, read_logit(&s.logits, token)); + } + // One run of the round kernels for each n to max + 1, so that their compile time is not in the + // time of a token. They write rows of the KV cache that later tokens write again before they + // read them, and no DeltaNet state. + // The same for the MTP rows after a round, which write MTP rows that later drafts write again + // before they read them, and m.token and m.h, which the first round sets again. + let mut warm = Vec::new(); + for n in 1..most + 2 { + warm.push(token); + run_round35(w, s, &mut r, &warm, pos, n); + mtp35_rows(w, s, &mut r, m, pos, n, vocab); + } + copy_f32(&mut m.h, &s.xn, c.hidden_size); + let _ready = transfer(&r.next, Memory::CPU_DRAM); + // m.token has the first draft of the next round when the last round ran the MTP rows. + let mut first_draft = false; + *start = Instant::now(); + let first_step = step; + let mut rounds = 0; + let mut drafted = 0; + let mut accepted = 0; + let mut kept : f64 = MTP_LONG_SHARE; + let mut ctx_rounds = 0; + let mut ctx_drafted = 0; + let mut ctx_accepted = 0; + while going && step + 1 < steps { + let room = steps - step - 1; + let want = if long > max && kept >= long_share { + long + } else if kept >= MTP_LONG_SHARE { + max + } else { + 1 + }; + // With ctx_max > 0, a round whose context has a match of at least ctx_match tokens drafts up to + // ctx_max tokens of the context after the match, as `generate_with_drafts35` does, and not + // from the MTP layer. + let mut ctx = Vec::new(); + if ctx_max > 0 && room > 1 { + let cm = longest_match(&context); + if cm.length >= ctx_match { + ctx = tokens_after(&context, cm.end, i32::min(ctx_max, room - 1)); + } + } + let from_context = ctx.len() > 0; + let k = if from_context { + ctx.len() + } else { + i32::min(want, room - 1) + }; + if k == 0 { + // The last token: a plain step. + let input = upload_token(token); + run_qwen35_layers(w, s, &input, pos); + predict_qwen35(w, s, &mut slots[1].next); + token = read_token(&slots[1].next); + context.push(token); + step = step + 1; + pos = pos + 1; + let mut logit : f32 = 0.0; + if !text_mode { + logit = read_logit(&s.logits, token); + } + going = show(out, t, eos, text_mode, step, token, logit); + } else { + // Draft j + 1, from row pos - 1 + j of the MTP layer, goes to slots[j]. + // The first round also runs MTP row pos - 1, so that the MTP rows have no gap. + if !first_draft { + m.token = upload_token(token); + mtp35_step(w, s, m, pos - 1, true, vocab); + } + let mut draft = Vec::new(); + if from_context { + for j in 0..k { + draft.push(ctx[j]); + } + } else { + copy_token(&mut slots[0].next, &m.token); + for j in 1..k { + mtp35_step(w, s, m, pos - 1 + j, true, vocab); + copy_token(&mut slots[j].next, &m.token); + } + for j in 0..k { + draft.push(read_token(&slots[j].next)); + } + } + let mut inputs = Vec::new(); + inputs.push(token); + for i in 0..k { + inputs.push(draft[i]); + } + run_round35(w, s, &mut r, &inputs, pos, k + 1); + let choice = transfer(&r.next, Memory::CPU_DRAM); + rounds = rounds + 1; + drafted = drafted + k; + if from_context { + ctx_rounds = ctx_rounds + 1; + ctx_drafted = ctx_drafted + k; + } + let mut j = 0; + let mut more = true; + while more && going { + token = choice[j]; + context.push(token); + step = step + 1; + let mut logit : f32 = 0.0; + if !text_mode { + logit = round_logit(&r.logits, j, token); + } + going = show(out, t, eos, text_mode, step, token, logit); + more = j < k && draft[j] == token; + if more { + accepted = accepted + 1; + j = j + 1; + if from_context { + ctx_accepted = ctx_accepted + 1; + } else { + kept = kept * 0.9 + 0.1; + } + } else if j < k && !from_context { + kept = kept * 0.9; + } + } + // Inputs 0 to j of the round are kept: the last token and the j drafts before the first + // miss. MTP rows pos to pos + j then run with the true h of positions pos to pos + j and + // the tokens after them, the kept drafts and `token`. The last row gives the first draft of + // the next round. + commit_round35(w, s, &r, j + 1); + mtp35_rows(w, s, &mut r, m, pos, j + 1, vocab); + first_draft = true; + pos = pos + j + 1; + } + } + if ctx_max > 0 { + println!("context_drafts: rounds={} drafted={} kept={};", ctx_rounds, ctx_drafted, ctx_accepted); + } + println!("rounds={} drafted={} accepted={};", rounds, drafted, accepted); + return step - first_step; +} + + +/// `main` for a Qwen3.5 or Qwen3.6 model (weight file v2, arch 1). The prompt runs in chunks +/// (src/prefill35.vx). With --draft, the tokens come from `generate_with_drafts35`. Prints the +/// same lines as `main`. +fn run_qwen35(out : &mut Stdout, files : &Files, path : &String, t : &Tokenizer, text_mode : bool, chat : bool, ignore_eos : bool, prompt : &Vec, steps : i32, draft : i32, draft_match : i32, mtp : i32, mtp_long : i32, mtp_share : f64, mtp_vocab : i32, runs : i32) -> i32 { + let w = load_qwen35_weights(files, path); + let eos = if ignore_eos { + -1 + } else { + w.config.eos_token_id + }; + let count = prompt.len(); + let mut s = new_qwen35_state(&w.config, count + steps); + for i in 0..count { + assert(prompt[i] < w.config.vocab_size, "a token of the prompt is not in the vocabulary"); + } + let ahead = if text_mode { + AHEAD + } else { + 1 + }; + let mut slots = Vec::new(); + for i in 0..ahead + 1 { + slots.push(Slot { + next: transfer(Tensor([1]), Memory::HBM) + }); + } + if text_mode { + if !chat { + for i in 0..count { + write_token(out, t, prompt[i]); + } + } + } else { + print!("prompt="); + for i in 0..count { + if i > 0 { + print!(","); + } + print!("{}", prompt[i]); + } + println!(";"); + } + // Each run of the prompt starts from a fresh state, made before its clock starts. The runs use the + // same tensors of the chunk, as a session does, made before the first clock starts, as llama.cpp + // makes its buffers when it loads the model. + let mut p = new_prefill35(&w.config, prefill35_chunk(count)); + // The first run of a kernel compiles it. So before the first clock starts, the first tokens of + // the prompt (up to 16) go through every kernel of the prompt and of `predict_qwen35`, with a + // small state of their own, as llama.cpp runs a warm-up batch when it loads a model. The kernels + // of a chunk do not depend on its number of tokens. + let mut warm_prompt = Vec::new(); + for i in 0..i32::min(count, 16) { + warm_prompt.push(prompt[i]); + } + let mut warm = new_qwen35_state(&w.config, warm_prompt.len()); + // With --mtp, the prompt also fills the rows of the MTP layer. + let mut m = if mtp > 0 { + new_mtp35_state(&w.config, count + steps) + } else { + new_mtp35_state_none() + }; + if mtp > 0 { + let mut warm_m = new_mtp35_state(&w.config, warm_prompt.len()); + prefill_qwen35_mtp(&w, &mut warm, &mut warm_m, &mut p, &warm_prompt); + } else { + prefill_qwen35_with(&w, &mut warm, &mut p, &warm_prompt); + } + predict_qwen35(&w, &mut warm, &mut slots[0].next); + read_token(&slots[0].next); + let mut tokens = Vec::new(); + let mut prompt_ms : f64 = 0.0; + for run in 0..runs { + if run > 0 { + s = new_qwen35_state(&w.config, count + steps); + } + let prompt_start = Instant::now(); + if mtp > 0 { + if run > 0 { + m = new_mtp35_state(&w.config, count + steps); + } + prefill_qwen35_mtp(&w, &mut s, &mut m, &mut p, prompt); + } else { + prefill_qwen35_with(&w, &mut s, &mut p, prompt); + } + predict_qwen35(&w, &mut s, &mut slots[0].next); + tokens = Vec::new(); + tokens.push(read_token(&slots[0].next)); + prompt_ms = f64::from(prompt_start.elapsed().as_secs_f32()) * 1000.0; + if runs > 1 { + println!("time prompt_ms={};", prompt_ms); + } + } + let mut start = Instant::now(); + let mut decoded = 0; + // --draft with --mtp: the drafts come from the context where it has a match of at least + // draft_match tokens, and from the MTP layer otherwise. + if draft > 0 && mtp == 0 { + decoded = generate_with_drafts35(out, &w, &mut s, t, eos, text_mode, prompt, tokens[0], steps, draft, &mut start); + } + if mtp > 0 { + let vocab = if mtp_vocab > 0 { + mtp_vocab + } else { + i32::min(MTP_VOCAB, w.config.vocab_size) + }; + decoded = generate_with_mtp35(out, &w, &mut s, &mut m, t, eos, text_mode, prompt, tokens[0], steps, mtp, mtp_long, mtp_share, draft, draft_match, vocab, &mut start); + } + for step in 0..steps { + if draft > 0 || mtp > 0 { + break; + } + let token = tokens[step]; + if text_mode { + if ends_text(t, eos, token) { + break; + } + write_token(out, t, token); + } else { + println!("step={} token={} logit={};", step, token, read_logit(&s.logits, token)); + } + if step == 1 { + // The tokens of step 0 compile the kernels of a step, so the clock starts after them. (A token + // cannot run twice to warm up, as in `main`: the DeltaNet would update its state twice.) + start = Instant::now(); + } + if step + 1 < steps && tokens.len() == step + 1 { + let mut n = steps - 1 - step; + if n > ahead { + n = ahead; + } + for j in 0..n { + let from = (step + j) % (ahead + 1); + let to = (step + j + 1) % (ahead + 1); + run_qwen35_layers(&w, &mut s, &slots[from].next, count + step + j); + predict_qwen35(&w, &mut s, &mut slots[to].next); + } + for j in 0..n { + tokens.push(read_token(&slots[(step + j + 1) % (ahead + 1)].next)); + } + if step > 0 { + decoded = decoded + n; + } + } + } + if text_mode { + println!(""); + } + if decoded > 0 { + let ms = f64::from(start.elapsed().as_secs_f32()) * 1000.0 / f64::from(decoded); + println!("time ms_per_token={};", ms); + } + println!("time prompt_ms_per_token={};", prompt_ms / f64::from(count)); + return 0; +} + +fn main(root : Root, args : Vec) -> i32 { + let o = parse_options(&args); + // The rights of the program that it uses: to open files and to print. + let files = root.files; + let mut out = root.stdout; if o.session { - let context = parse_numbers(o.context); - return run_session(o.weights, o.tokenizer, o.requests, o.replies, context[0]); + let context = parse_numbers(&o.context); + return run_session(&files, &o.weights, &o.tokenizer, &o.requests, &o.replies, context[0]); } let t = if o.has_tokenizer { - load_tokenizer(o.tokenizer) + load_tokenizer(&files, &o.tokenizer) } else { no_tokenizer() }; // Text mode prints text. Otherwise the program prints the lines of `reference.py`. let text_mode = o.has_tokenizer && !o.lines; - let prompt = prompt_ids(&o, &t); - let steps_list = parse_numbers(o.steps); + let prompt = prompt_ids(&files, &o, &t); + let steps_list = parse_numbers(&o.steps); let steps = steps_list[0]; let count = prompt.len(); assert(steps > 0, "--steps must be at least 1"); - let w = load_weights(o.weights); + if weight_file_arch(&files, &o.weights) == 1 { + let mut draft = 0; + let mut draft_match = MTP_CONTEXT_MATCH; + if o.has_draft { + let d = parse_numbers(&o.draft); + draft = d[0]; + if d.len() > 1 { + draft_match = d[1]; + } + } + let runs = if o.has_prompt_runs { + parse_numbers(&o.prompt_runs)[0] + } else { + 1 + }; + assert(runs >= 1, "--prompt-runs must be at least 1"); + let mut mtp = 0; + let mut mtp_long = 0; + let mut mtp_share : f64 = 1.0; + if o.has_mtp { + let k = parse_numbers(&o.mtp); + mtp = k[0]; + if k.len() > 1 { + mtp_long = k[1]; + mtp_share = MTP_LONGER_SHARE; + } + if k.len() > 2 { + mtp_share = f64::from(k[2]) / 100.0; + } + } + let mtp_vocab = if o.has_mtp_vocab { + parse_numbers(&o.mtp_vocab)[0] + } else { + 0 + }; + return run_qwen35(&mut out, &files, &o.weights, &t, text_mode, o.chat, o.ignore_eos, &prompt, steps, draft, draft_match, mtp, mtp_long, mtp_share, mtp_vocab, runs); + } + assert(!o.has_prompt_runs, "--prompt-runs needs a Qwen3.5 or Qwen3.6 file"); + let w = load_weights(&files, &o.weights); + let eos = if o.ignore_eos { + -1 + } else { + w.config.eos_token_id + }; let mut s = new_state(&w.config, count + steps); for i in 0..count { assert(prompt[i] < w.config.vocab_size, "a token of the prompt is not in the vocabulary"); @@ -395,7 +1016,7 @@ fn main(argc : i32, argv : *mut *mut i8) -> i32 { if text_mode { if !o.chat { for i in 0..count { - write_token(&t, prompt[i]); + write_token(&mut out, &t, prompt[i]); } } } else { @@ -425,7 +1046,7 @@ fn main(argc : i32, argv : *mut *mut i8) -> i32 { // The number of tokens that the loop ran through the model. let mut decoded = 0; if o.has_draft { - decoded = generate_with_drafts(&w, &mut s, &t, text_mode, &prompt, tokens[0], steps, parse_numbers(o.draft)[0], &mut start); + decoded = generate_with_drafts(&mut out, &w, &mut s, &t, eos, text_mode, &prompt, tokens[0], steps, parse_numbers(&o.draft)[0], &mut start); } for step in 0..steps { if o.has_draft { @@ -433,10 +1054,10 @@ fn main(argc : i32, argv : *mut *mut i8) -> i32 { } let token = tokens[step]; if text_mode { - if is_special(&t, token) || token == w.config.eos_token_id { + if ends_text(&t, eos, token) { break; } - write_token(&t, token); + write_token(&mut out, &t, token); } else { println!("step={} token={} logit={};", step, token, read_logit(&s.logits, token)); } diff --git a/src/model.vx b/src/model.vx index c2ebfdf..3146142 100644 --- a/src/model.vx +++ b/src/model.vx @@ -58,7 +58,7 @@ struct State { /// The state for up to `max_seq` positions. The angles of RoPE are computed in f64, as in /// `reference.py`, and rounded to f32 once. -fn new_state(c : &Config, max_seq : i32) -> State { +pub fn new_state(c : &Config, max_seq : i32) -> State { assert(max_seq > 0 && max_seq <= c.max_positions, "max_seq must be between 1 and the max_positions of the model"); let half = c.head_dim / 2; let mut hcos = Tensor([max_seq, half]); @@ -109,7 +109,7 @@ fn new_state(c : &Config, max_seq : i32) -> State { } /// y = m x, with the kernel for the dtype of `m`, which has `rows` x `cols` weights. -fn matvec(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { +pub fn matvec(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { if m.dtype == U6 { matvec_q6(y, &m.codes, &m.high, &m.group_scales, x, rows, cols); } else if m.dtype == U4 { @@ -123,7 +123,7 @@ fn matvec(y : &mut Tensor, m : &WeightMatrix, x : &Tensor } /// y += m x. -fn matvec_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { +pkg fn matvec_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, cols : i32) -> void { if m.dtype == U4 { nn_matvec_q4_add(y, &m.codes, &m.group_scales, x, rows, cols); } else if m.dtype == F8E4M3 { @@ -135,7 +135,7 @@ fn matvec_add(y : &mut Tensor, m : &WeightMatrix, x : &Te } /// y += m x, for x of [heads, head_dim]. -fn matvec_heads_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, heads : i32, head_dim : i32) -> void { +pub fn matvec_heads_add(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, rows : i32, heads : i32, head_dim : i32) -> void { if m.dtype == U4 { matvec_q4_heads_add_blocks(y, &m.codes, &m.group_scales, x, rows, heads, head_dim); } else if m.dtype == F8E4M3 { @@ -147,7 +147,7 @@ fn matvec_heads_add(y : &mut Tensor, m : &WeightMatrix, x } /// The Q, K and V of x: m x + b, split by heads. -fn qkv(q : &mut Tensor, k : &mut Tensor, v : &mut Tensor, m : &WeightMatrix, b : &Tensor, x : &Tensor, c : &Config) -> void { +pub fn qkv(q : &mut Tensor, k : &mut Tensor, v : &mut Tensor, m : &WeightMatrix, b : &Tensor, x : &Tensor, c : &Config) -> void { if m.dtype == U4 { qkv_q4_blocks(q, k, v, &m.codes, &m.group_scales, b, x, c.num_q_heads, c.num_kv_heads, c.head_dim, c.hidden_size); } else if m.dtype == F8E4M3 { @@ -192,7 +192,7 @@ fn add_experts(e : &mut Experts, x : &mut Tensor, xn : &T /// Runs the token in `token` at position `pos` through every layer. The hidden state of the /// token is then in `s.x`, and its keys and values are in the caches. -fn run_layers(w : &Weights, s : &mut State, token : &Tensor, pos : i32) -> void { +pub fn run_layers(w : &Weights, s : &mut State, token : &Tensor, pos : i32) -> void { let c = &w.config; let eps = c.rms_norm_eps as f32; assert(pos >= 0 && pos < s.max_seq, "the position is past the end of the KV cache"); @@ -227,7 +227,7 @@ fn run_layers(w : &Weights, s : &mut State, token : &Tensor