From f1ac311dd1459d1f55d3d6946b4d94fdb4ae8ccf Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:25:14 -0800 Subject: [PATCH 01/60] Declare and pin the dependencies: requirements files, VX_VERSION, z3 The Python packages were in three places with no versions. requirements.txt (the scripts), requirements-test.txt (the tests, which CI installs) and requirements-mlx.txt (check_against_mlx.py) pin them. VX_VERSION names the Vx release that CI tests, and CI checks that vxc --version gives it. The README names z3, which the Vx toolchain needs on macOS. Part of #79. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- .github/workflows/ci.yml | 13 +++++++------ README.md | 40 ++++++++++++++++++++++++++++------------ VX_VERSION | 1 + requirements-mlx.txt | 4 ++++ requirements-test.txt | 5 +++++ requirements.txt | 10 ++++++++++ tests/run.sh | 4 ++-- 7 files changed, 57 insertions(+), 20 deletions(-) create mode 100644 VX_VERSION create mode 100644 requirements-mlx.txt create mode 100644 requirements-test.txt create mode 100644 requirements.txt diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 36e9cb0..22d1076 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,23 +15,24 @@ jobs: 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 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..646b592 100644 --- a/README.md +++ b/README.md @@ -20,14 +20,17 @@ changed, its measurements, and the changes that did not help. ## Install Vx -The program needs Vx v0.0.5 or later: +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.5). CI tests that release. On a Mac, the Vx toolchain +also needs LLVM 22 and z3 from Homebrew: ```sh -curl -fsSL https://vxlang.org/install.sh | 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`. 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 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" @@ -49,14 +52,15 @@ with no Apple GPU, the same program runs on the CPU. ## Prepare a model -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), +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 numpy tokenizers huggingface_hub +pip install -r requirements.txt ``` 1. Download a model from Hugging Face, for example @@ -219,8 +223,8 @@ the same prompt, after `convert_tokenizer.py ~/models/Qwen3-Coder-30B-A3B-Instru 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 +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 @@ -411,8 +415,9 @@ A program imports the modules as `qwen::weights`, `qwen::model`, `qwen::attentio `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 +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`: @@ -502,3 +507,14 @@ The check fails when the router chooses the smallest experts or one expert too f 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. + +## License and notices + +The code of this repository is under the Apache License v2.0 with LLVM Exceptions +([`LICENSE`](LICENSE)). Some kernels follow the design of llama.cpp, which is under the MIT License. +[`THIRD_PARTY_NOTICES`](THIRD_PARTY_NOTICES) lists them, with the notice of that license. + +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/VX_VERSION b/VX_VERSION new file mode 100644 index 0000000..5c314e5 --- /dev/null +++ b/VX_VERSION @@ -0,0 +1 @@ +v0.0.5 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/tests/run.sh b/tests/run.sh index e1c577c..17efa0a 100755 --- a/tests/run.sh +++ b/tests/run.sh @@ -1,7 +1,7 @@ #!/bin/bash # Runs the RUN lines of the tests, as the fixture runner of Vx runs them, from the root of this -# repository. A python3 that has NumPy must be on PATH, and FileCheck or the `filecheck` of -# `pip install filecheck`. +# repository. A python3 with the packages of requirements-test.txt must be on PATH. FileCheck of +# LLVM on PATH comes first, else the `filecheck` of those packages. # # tests/run.sh # the Python tests of the scripts, and every test here # tests/run.sh FILE... # only these tests From 708a3dd0f944476512028b191d805aa079080f1e Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:25:14 -0800 Subject: [PATCH 02/60] THIRD_PARTY_NOTICES: the code that follows llama.cpp Six pieces follow the design of llama.cpp (MIT License): the decode, round and prompt attention, the expert product of the prompt, the block shape of the Q4_0 products, and the Q4_0 rounding of qwen_weights.py. The file lists each with its upstream kernel, and has the MIT text. The README links it, and says that model weights and tokenizers keep the license of their model. Fixes #80. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- THIRD_PARTY_NOTICES | 59 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 THIRD_PARTY_NOTICES 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. From a27bafcf8b4ae1c1a27ee460873c908acb510011 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:39:10 +0000 Subject: [PATCH 03/60] tests: broken copies of the decode attention parts, not to merge Each copy breaks one part of vec_attention_parts, and runs the checks of tests/decode_attention.vx. Each must show values off. Co-Authored-By: Claude Opus 5.5 --- tests/sabotage_decode_attention.vx | 520 +++++++++++++++++++++++++++++ 1 file changed, 520 insertions(+) create mode 100644 tests/sabotage_decode_attention.vx diff --git a/tests/sabotage_decode_attention.vx b/tests/sabotage_decode_attention.vx new file mode 100644 index 0000000..cc325e5 --- /dev/null +++ b/tests/sabotage_decode_attention.vx @@ -0,0 +1,520 @@ +// Throwaway: broken copies of vec_attention_parts, each run through the checks of +// tests/decode_attention.vx. Each line must show some values off. +// +// RUN: vxc %s --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx | grep off; false +import core::num; +import qwen::attention; + +fn parts_no_mask(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 = 4 * 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 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 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 mut score = lane_sum(dot4(k_cache, kept, g, d, q0, q1, q2, q3)); + if r == l { + mine = score; + } + } + let top = big.max(lane_max(mine)); + let shrink = (big - top).fast_exp(); + let p = (mine - top).fast_exp(); + total = total * shrink + lane_sum(p); + o0 = o0 * shrink; + o1 = o1 * shrink; + o2 = o2 * shrink; + o3 = o3 * shrink; + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + 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); + } + 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; + // 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][128 + l] = stats[s][l]; + } + } + } + } + } + return; +} + +fn parts_no_clamp(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 = 4 * 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 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 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 kept = row; + let mut score = lane_sum(dot4(k_cache, kept, g, d, q0, q1, q2, q3)); + if row > pos { + score = -3.0e38; + } + if r == l { + mine = score; + } + } + let top = big.max(lane_max(mine)); + let shrink = (big - top).fast_exp(); + let p = (mine - top).fast_exp(); + total = total * shrink + lane_sum(p); + o0 = o0 * shrink; + o1 = o1 * shrink; + o2 = o2 * shrink; + o3 = o3 * shrink; + for r in 0..32 { + let row = r0 + r; + let kept = row; + 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); + } + 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; + // 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][128 + l] = stats[s][l]; + } + } + } + } + } + return; +} + +fn parts_no_rescale(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 = 4 * 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 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 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 mut score = lane_sum(dot4(k_cache, kept, g, d, q0, q1, q2, q3)); + if row > pos { + score = -3.0e38; + } + if r == l { + mine = score; + } + } + let top = big.max(lane_max(mine)); + let shrink = (big - top).fast_exp(); + let p = (mine - top).fast_exp(); + total = total * shrink + lane_sum(p); + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + 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); + } + 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; + // 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][128 + l] = stats[s][l]; + } + } + } + } + } + return; +} + +fn parts_own_weight(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 = 4 * 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 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 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 mut score = lane_sum(dot4(k_cache, kept, g, d, q0, q1, q2, q3)); + if row > pos { + score = -3.0e38; + } + if r == l { + mine = score; + } + } + let top = big.max(lane_max(mine)); + let shrink = (big - top).fast_exp(); + let p = (mine - top).fast_exp(); + total = total * shrink + lane_sum(p); + o0 = o0 * shrink; + o1 = o1 * shrink; + o2 = o2 * shrink; + o3 = o3 * shrink; + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > pos { + kept = pos; + } + let pr = lane_value(p, l); + 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); + } + 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; + // 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][128 + l] = stats[s][l]; + } + } + } + } + } + return; +} + +fn parts_swapped_stats(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 = 4 * 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 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 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 mut score = lane_sum(dot4(k_cache, kept, g, d, q0, q1, q2, q3)); + if row > pos { + score = -3.0e38; + } + if r == l { + mine = score; + } + } + let top = big.max(lane_max(mine)); + let shrink = (big - top).fast_exp(); + let p = (mine - top).fast_exp(); + total = total * shrink + lane_sum(p); + o0 = o0 * shrink; + o1 = o1 * shrink; + o2 = o2 * shrink; + o3 = o3 * shrink; + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + 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); + } + 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; + // 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 = total; + if l == 1 { + x = big; + } + stats[s][l] = x; + } + } + for l in 0..2 across lanes(32) { + part[h][w][128 + l] = stats[s][l]; + } + } + } + } + } + return; +} + +const Q_HEADS : i32 = 32; +const KV_HEADS : i32 = 4; + +/// A number in [-1, 1) from the state `s` of a linear congruential generator. +fn random(s : &mut i64) -> f32 { + *s = (*s * 1103515245 + 12345) % 2147483648; + return (*s as f32) / 1073741824.0 - 1.0; +} + +fn check(s : &mut i64, pos : i32, which : i32) -> void { + let rows = pos + 32; + let mut qh = Tensor([Q_HEADS, 128]); + let mut kh = Tensor([rows, KV_HEADS, 128]); + let mut vh = Tensor([rows, KV_HEADS, 128]); + for h in 0..Q_HEADS { + for d in 0..128 { + qh[h][d] = 4.0 * random(s); + } + } + for r in 0..rows { + for g in 0..KV_HEADS { + for d in 0..128 { + if r <= pos { + kh[r][g][d] = random(s) as f16; + vh[r][g][d] = random(s) as f16; + } else { + kh[r][g][d] = 8.0 as f16; + vh[r][g][d] = f16::nan(); + } + } + } + } + let q = transfer(&qh, Memory::HBM); + let k = transfer(&kh, Memory::HBM); + let v = transfer(&vh, Memory::HBM); + let mut part = transfer(vec_attention_scratch(Q_HEADS), Memory::HBM); + let mut out = transfer(Tensor([Q_HEADS, 128]), Memory::HBM); + let mut nwg = 32; + if 2 * nwg * 32 < pos + 1 { + nwg = nwg * 2; + } + let sc = 1.0 / (128.0 as f32).sqrt(); + if which == 0 { + parts_no_mask(&mut part, &q, &k, &v, pos, Q_HEADS, Q_HEADS / KV_HEADS, nwg, sc); + } else if which == 1 { + parts_no_clamp(&mut part, &q, &k, &v, pos, Q_HEADS, Q_HEADS / KV_HEADS, nwg, sc); + } else if which == 2 { + parts_no_rescale(&mut part, &q, &k, &v, pos, Q_HEADS, Q_HEADS / KV_HEADS, nwg, sc); + } else if which == 3 { + parts_own_weight(&mut part, &q, &k, &v, pos, Q_HEADS, Q_HEADS / KV_HEADS, nwg, sc); + } else if which == 4 { + parts_swapped_stats(&mut part, &q, &k, &v, pos, Q_HEADS, Q_HEADS / KV_HEADS, nwg, sc); + } + vec_attention_merge(&mut out, &part, nwg, Q_HEADS); + let got = transfer(&out, Memory::CPU_DRAM); + let scale = 1.0 / (128.0 as f64).sqrt(); + let mut score = Tensor([pos + 1]); + let mut off = 0; + for h in 0..Q_HEADS { + let g = h / (Q_HEADS / KV_HEADS); + let mut big : f64 = -1.0e300; + for r in 0..pos + 1 { + let mut dot : f64 = 0.0; + for d in 0..128 { + dot = dot + (qh[h][d] as f64) * (kh[r][g][d] as f64); + } + score[r] = dot * scale; + big = big.max(score[r]); + } + let mut total : f64 = 0.0; + for r in 0..pos + 1 { + score[r] = (score[r] - big).exp(); + total = total + score[r]; + } + for d in 0..128 { + let mut acc : f64 = 0.0; + for r in 0..pos + 1 { + acc = acc + score[r] * (vh[r][g][d] as f64); + } + let want = acc / total; + // Written so that a NaN counts as off. + if !(((got[h][d] as f64) - want).abs() <= 1.0e-5 * (1.0 + want.abs())) { + off = off + 1; + } + } + } + println!("kernel {} pos {}: {} off", which, pos, off); + return; +} + +fn main() -> i32 { + let mut s : i64 = 11; + for which in 0..5 { + check(&mut s, 0, which); + check(&mut s, 40, which); + check(&mut s, 1000, which); + check(&mut s, 2100, which); + check(&mut s, 8000, which); + } + return 0; +} From 3657ac66d96704f39f9688d41a793db687a517f3 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:46:59 +0000 Subject: [PATCH 04/60] round: write the round attention parts in Vx, as the decode kernel is The 8 kernels of round_attention_parts, one for each number of queries n, were mlir! blocks. scripts/round_attention.py now prints them as Vx code, in the form of vec_attention_parts: the same small mlir! functions, the same order of operations for each query, and each row of K and V read once for all n queries. Each query keeps its values in variables of its own, so that they stay in registers. Vx v0.0.5 keeps a tile in threadgroup memory on Metal, so one kernel with a tile for n queries would be slower. The script moved out of scripts/mlir_kernels/. The score of a row is now 4 calls of half_at and a dot product in Vx, in both kernels, not dot4. dot4 had its own load, so the kernel for n queries loaded each row of K n times. Vx merges the 4 loads of half_at into one, as it does for V. The sum keeps its order: ((k0 q0 + k1 q1) + k2 q2) + k3 q3. dot4 is gone. The Metal code of the kernel for 2 queries has one half4 load for each row of K and of V, as the mlir! block had. With this commit and the 2 before it, 11 of the 13 mlir! blocks are gone. 2 are left: the prefill attention and the prefill expert product. Part of #76. Co-Authored-By: Claude Opus 5.5 --- scripts/mlir_kernels/round_attention.py | 168 - scripts/round_attention.py | 155 + src/attention.vx | 26 +- src/round.vx | 3789 +++++++++++------------ 4 files changed, 2051 insertions(+), 2087 deletions(-) delete mode 100644 scripts/mlir_kernels/round_attention.py create mode 100644 scripts/round_attention.py 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/round_attention.py b/scripts/round_attention.py new file mode 100644 index 0000000..b85928f --- /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/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} = half_at(k_cache, kept, g, d, {j});') + for t in T: + d(f'let mut score{t} = lane_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(lane_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 + lane_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} = lane_value(p{t}, r);') + for j in range(4): + d(f'o{t}_{j} = fused(half_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/src/attention.vx b/src/attention.vx index 646a9f0..55ca2fe 100644 --- a/src/attention.vx +++ b/src/attention.vx @@ -106,26 +106,6 @@ ensures writes_only() }; } -/// 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 @@ -192,7 +172,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 = half_at(k_cache, kept, g, d, 0); + let k1 = half_at(k_cache, kept, g, d, 1); + let k2 = half_at(k_cache, kept, g, d, 2); + let k3 = half_at(k_cache, kept, g, d, 3); + let mut score = lane_sum(k0 * q0 + k1 * q1 + k2 * q2 + k3 * q3); if row > pos { score = -3.0e38; } diff --git a/src/round.vx b/src/round.vx index 08cd983..226ca18 100644 --- a/src/round.vx +++ b/src/round.vx @@ -10,10 +10,11 @@ // round gives the tokens that plain decoding gives. Tensors of a round have the position first: // q of [n, q_heads, head_dim]. // -// scripts/mlir_kernels/round_attention.py writes the kernels of `round_attention`: change that -// script, not the MLIR. +// scripts/round_attention.py writes the kernels of `round_attention`, one for each number of queries: +// change that script, not the kernels. import core::num; import std::nn; +import qwen::attention; /// The largest n of a round. const ROUND_MAX : i32 = 16; @@ -154,100 +155,92 @@ fn round_attention_parts_1(part : &mut Tensor, q : 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, %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])]) { - %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 - %c132 = arith.constant 132 : 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 - %t0i = arith.index_cast %t0 : 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> - %scv = vector.broadcast %scale : f32 to vector<4xf32> - %ct0 = arith.constant 0 : index - %pos0 = arith.addi %posi, %ct0 : index - %n0 = arith.addi %pos0, %c32 : index - %chunks0 = arith.divui %n0, %c32 : index - %qt0 = arith.addi %t0i, %ct0 : index - %qv0 = vector.load %q[%qt0, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs0 = arith.mulf %qv0, %scv : vector<4xf32> - %st:3 = scf.for %ic = %wi to %chunks0 step %nwgi iter_args(%M0 = %neg, %S0 = %zero, %o0 = %vz4) -> (f32, f32, vector<4xf32>) { - %r0 = arith.muli %ic, %c32 : index - %my:1 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%m0 = %neg) -> (f32) { - %row = arith.addi %r0, %cc : index - %rowc = arith.minui %row, %pos0 : index - %kh = vector.load %k[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> - %kf = arith.extf %kh : vector<4xf16> to vector<4xf32> - %mine = arith.cmpi eq, %cc, %l : index - %pr0 = arith.mulf %kf, %qs0 : vector<4xf32> - %pl0 = vector.reduction , %pr0 : vector<4xf32> into f32 - %sc0 = gpu.subgroup_reduce add %pl0 : (f32) -> f32 - %live0 = arith.cmpi ule, %row, %pos0 : index - %scm0 = arith.select %live0, %sc0, %neg : f32 - %mm0 = arith.select %mine, %scm0, %m0 : f32 - scf.yield %mm0 : f32 - } - %act0 = arith.cmpi ult, %ic, %chunks0 : index - %u0:4 = scf.if %act0 -> (f32, f32, vector<4xf32>, f32) { - %bm0 = gpu.subgroup_reduce maxnumf %my#0 : (f32) -> f32 - %Mn0 = arith.maxnumf %M0, %bm0 : f32 - %dm0 = arith.subf %M0, %Mn0 : f32 - %ms0 = math.exp %dm0 : f32 - %dp0 = arith.subf %my#0, %Mn0 : f32 - %p0 = math.exp %dp0 : f32 - %bs0 = gpu.subgroup_reduce add %p0 : (f32) -> f32 - %Ss0 = arith.mulf %S0, %ms0 : f32 - %Sn0 = arith.addf %Ss0, %bs0 : f32 - %msv0 = vector.broadcast %ms0 : f32 to vector<4xf32> - %ox0 = arith.mulf %o0, %msv0 : vector<4xf32> - scf.yield %Mn0, %Sn0, %ox0, %p0 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M0, %S0, %o0, %zero : f32, f32, vector<4xf32>, f32 + 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 = 4 * l; + let last = pos + 0; + let q0_0 = q[t0 + 0][h][d + 0] * scale; + let q0_1 = q[t0 + 0][h][d + 1] * scale; + let q0_2 = q[t0 + 0][h][d + 2] * scale; + let q0_3 = q[t0 + 0][h][d + 3] * scale; + let mut big0 : f32 = -3.0e38; + let mut total0 : f32 = 0.0; + let mut o0_0 : f32 = 0.0; + let mut o0_1 : f32 = 0.0; + let mut o0_2 : f32 = 0.0; + let mut o0_3 : f32 = 0.0; + let chunks = (last + 32) / 32; + let mut c = w; + while c < chunks { + let r0 = c * 32; + let mut mine0 : f32 = -3.0e38; + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > last { + kept = last; + } + let k0 = half_at(k_cache, kept, g, d, 0); + let k1 = half_at(k_cache, kept, g, d, 1); + let k2 = half_at(k_cache, kept, g, d, 2); + let k3 = half_at(k_cache, kept, g, d, 3); + let mut score0 = lane_sum(k0 * q0_0 + k1 * q0_1 + k2 * q0_2 + k3 * q0_3); + if row > pos + 0 { + score0 = -3.0e38; + } + if r == l { + mine0 = score0; + } + } + let mut p0 : f32 = 0.0; + if c < (pos + 0 + 32) / 32 { + let top = big0.max(lane_max(mine0)); + let shrink = (big0 - top).fast_exp(); + p0 = (mine0 - top).fast_exp(); + total0 = total0 * shrink + lane_sum(p0); + o0_0 = o0_0 * shrink; + o0_1 = o0_1 * shrink; + o0_2 = o0_2 * shrink; + o0_3 = o0_3 * shrink; + big0 = top; + } + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > last { + kept = last; + } + let pr0 = lane_value(p0, r); + o0_0 = fused(half_at(v_cache, kept, g, d, 0), pr0, o0_0); + o0_1 = fused(half_at(v_cache, kept, g, d, 1), pr0, o0_1); + o0_2 = fused(half_at(v_cache, kept, g, d, 2), pr0, o0_2); + o0_3 = fused(half_at(v_cache, kept, g, d, 3), pr0, o0_3); + } + c = c + nwg; } - %ov:1 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%oa0 = %u0#2) -> (vector<4xf32>) { - %row = arith.addi %r0, %cc : index - %rowc = arith.minui %row, %pos0 : 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 - %pc0, %pv0 = gpu.shuffle idx %u0#3, %cci, %c32i : f32 - %pcv0 = vector.broadcast %pc0 : f32 to vector<4xf32> - %on0 = vector.fma %vf, %pcv0, %oa0 : vector<4xf32> - scf.yield %on0 : vector<4xf32> + let b0 = 132 * (t0 + 0); + part[h][w][b0 + d + 0] = o0_0; + part[h][w][b0 + d + 1] = o0_1; + part[h][w][b0 + d + 2] = o0_2; + part[h][w][b0 + d + 3] = o0_3; + // Every lane has the same largest score and sum of the weights of a query. Lanes 0 and 1 keep them + // for the next loop. + if l < 2 { + let mut x0 = big0; + if l == 1 { + x0 = total0; + } + stats[s][0][l] = x0; } - scf.yield %u0#0, %u0#1, %ov#0 : f32, f32, vector<4xf32> } - %lane0 = arith.cmpi eq, %l, %c0 : index - %base0 = arith.muli %qt0, %c132 : index - %at0 = arith.addi %base0, %l4 : index - vector.store %st#2, %part[%hi, %wi, %at0] : memref, vector<4xf32> - %am0 = arith.addi %base0, %c128 : index - %as0 = arith.addi %base0, %c129 : index - scf.if %lane0 { - memref.store %st#0, %part[%hi, %wi, %am0] : memref - memref.store %st#1, %part[%hi, %wi, %as0] : memref + for l in 0..2 across lanes(32) { + part[h][w][132 * (t0 + 0) + 128 + l] = stats[s][0][l]; } - macro.yield %h : i32 - }; + } } } } @@ -260,142 +253,136 @@ fn round_attention_parts_2(part : &mut Tensor, q : 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, %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])]) { - %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 - %c132 = arith.constant 132 : 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 - %t0i = arith.index_cast %t0 : 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> - %scv = vector.broadcast %scale : f32 to vector<4xf32> - %ct0 = arith.constant 0 : index - %pos0 = arith.addi %posi, %ct0 : index - %n0 = arith.addi %pos0, %c32 : index - %chunks0 = arith.divui %n0, %c32 : index - %qt0 = arith.addi %t0i, %ct0 : index - %qv0 = vector.load %q[%qt0, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs0 = arith.mulf %qv0, %scv : vector<4xf32> - %ct1 = arith.constant 1 : index - %pos1 = arith.addi %posi, %ct1 : index - %n1 = arith.addi %pos1, %c32 : index - %chunks1 = arith.divui %n1, %c32 : index - %qt1 = arith.addi %t0i, %ct1 : index - %qv1 = vector.load %q[%qt1, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs1 = arith.mulf %qv1, %scv : vector<4xf32> - %st:6 = scf.for %ic = %wi to %chunks1 step %nwgi iter_args(%M0 = %neg, %S0 = %zero, %o0 = %vz4, %M1 = %neg, %S1 = %zero, %o1 = %vz4) -> (f32, f32, vector<4xf32>, f32, f32, vector<4xf32>) { - %r0 = arith.muli %ic, %c32 : index - %my:2 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%m0 = %neg, %m1 = %neg) -> (f32, f32) { - %row = arith.addi %r0, %cc : index - %rowc = arith.minui %row, %pos1 : index - %kh = vector.load %k[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> - %kf = arith.extf %kh : vector<4xf16> to vector<4xf32> - %mine = arith.cmpi eq, %cc, %l : index - %pr0 = arith.mulf %kf, %qs0 : vector<4xf32> - %pl0 = vector.reduction , %pr0 : vector<4xf32> into f32 - %sc0 = gpu.subgroup_reduce add %pl0 : (f32) -> f32 - %live0 = arith.cmpi ule, %row, %pos0 : index - %scm0 = arith.select %live0, %sc0, %neg : f32 - %mm0 = arith.select %mine, %scm0, %m0 : f32 - %pr1 = arith.mulf %kf, %qs1 : vector<4xf32> - %pl1 = vector.reduction , %pr1 : vector<4xf32> into f32 - %sc1 = gpu.subgroup_reduce add %pl1 : (f32) -> f32 - %live1 = arith.cmpi ule, %row, %pos1 : index - %scm1 = arith.select %live1, %sc1, %neg : f32 - %mm1 = arith.select %mine, %scm1, %m1 : f32 - scf.yield %mm0, %mm1 : f32, f32 - } - %act0 = arith.cmpi ult, %ic, %chunks0 : index - %u0:4 = scf.if %act0 -> (f32, f32, vector<4xf32>, f32) { - %bm0 = gpu.subgroup_reduce maxnumf %my#0 : (f32) -> f32 - %Mn0 = arith.maxnumf %M0, %bm0 : f32 - %dm0 = arith.subf %M0, %Mn0 : f32 - %ms0 = math.exp %dm0 : f32 - %dp0 = arith.subf %my#0, %Mn0 : f32 - %p0 = math.exp %dp0 : f32 - %bs0 = gpu.subgroup_reduce add %p0 : (f32) -> f32 - %Ss0 = arith.mulf %S0, %ms0 : f32 - %Sn0 = arith.addf %Ss0, %bs0 : f32 - %msv0 = vector.broadcast %ms0 : f32 to vector<4xf32> - %ox0 = arith.mulf %o0, %msv0 : vector<4xf32> - scf.yield %Mn0, %Sn0, %ox0, %p0 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M0, %S0, %o0, %zero : f32, f32, vector<4xf32>, f32 - } - %act1 = arith.cmpi ult, %ic, %chunks1 : index - %u1:4 = scf.if %act1 -> (f32, f32, vector<4xf32>, f32) { - %bm1 = gpu.subgroup_reduce maxnumf %my#1 : (f32) -> f32 - %Mn1 = arith.maxnumf %M1, %bm1 : f32 - %dm1 = arith.subf %M1, %Mn1 : f32 - %ms1 = math.exp %dm1 : f32 - %dp1 = arith.subf %my#1, %Mn1 : f32 - %p1 = math.exp %dp1 : f32 - %bs1 = gpu.subgroup_reduce add %p1 : (f32) -> f32 - %Ss1 = arith.mulf %S1, %ms1 : f32 - %Sn1 = arith.addf %Ss1, %bs1 : f32 - %msv1 = vector.broadcast %ms1 : f32 to vector<4xf32> - %ox1 = arith.mulf %o1, %msv1 : vector<4xf32> - scf.yield %Mn1, %Sn1, %ox1, %p1 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M1, %S1, %o1, %zero : f32, f32, vector<4xf32>, f32 + 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 = 4 * l; + let last = pos + 1; + let q0_0 = q[t0 + 0][h][d + 0] * scale; + let q0_1 = q[t0 + 0][h][d + 1] * scale; + let q0_2 = q[t0 + 0][h][d + 2] * scale; + let q0_3 = q[t0 + 0][h][d + 3] * scale; + let mut big0 : f32 = -3.0e38; + let mut total0 : f32 = 0.0; + let mut o0_0 : f32 = 0.0; + let mut o0_1 : f32 = 0.0; + let mut o0_2 : f32 = 0.0; + let mut o0_3 : f32 = 0.0; + let q1_0 = q[t0 + 1][h][d + 0] * scale; + let q1_1 = q[t0 + 1][h][d + 1] * scale; + let q1_2 = q[t0 + 1][h][d + 2] * scale; + let q1_3 = q[t0 + 1][h][d + 3] * scale; + let mut big1 : f32 = -3.0e38; + let mut total1 : f32 = 0.0; + let mut o1_0 : f32 = 0.0; + let mut o1_1 : f32 = 0.0; + let mut o1_2 : f32 = 0.0; + let mut o1_3 : f32 = 0.0; + let chunks = (last + 32) / 32; + let mut c = w; + while c < chunks { + let r0 = c * 32; + let mut mine0 : f32 = -3.0e38; + let mut mine1 : f32 = -3.0e38; + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > last { + kept = last; + } + let k0 = half_at(k_cache, kept, g, d, 0); + let k1 = half_at(k_cache, kept, g, d, 1); + let k2 = half_at(k_cache, kept, g, d, 2); + let k3 = half_at(k_cache, kept, g, d, 3); + let mut score0 = lane_sum(k0 * q0_0 + k1 * q0_1 + k2 * q0_2 + k3 * q0_3); + if row > pos + 0 { + score0 = -3.0e38; + } + let mut score1 = lane_sum(k0 * q1_0 + k1 * q1_1 + k2 * q1_2 + k3 * q1_3); + if row > pos + 1 { + score1 = -3.0e38; + } + if r == l { + mine0 = score0; + mine1 = score1; + } + } + let mut p0 : f32 = 0.0; + if c < (pos + 0 + 32) / 32 { + let top = big0.max(lane_max(mine0)); + let shrink = (big0 - top).fast_exp(); + p0 = (mine0 - top).fast_exp(); + total0 = total0 * shrink + lane_sum(p0); + o0_0 = o0_0 * shrink; + o0_1 = o0_1 * shrink; + o0_2 = o0_2 * shrink; + o0_3 = o0_3 * shrink; + big0 = top; + } + let mut p1 : f32 = 0.0; + if c < (pos + 1 + 32) / 32 { + let top = big1.max(lane_max(mine1)); + let shrink = (big1 - top).fast_exp(); + p1 = (mine1 - top).fast_exp(); + total1 = total1 * shrink + lane_sum(p1); + o1_0 = o1_0 * shrink; + o1_1 = o1_1 * shrink; + o1_2 = o1_2 * shrink; + o1_3 = o1_3 * shrink; + big1 = top; + } + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > last { + kept = last; + } + let pr0 = lane_value(p0, r); + o0_0 = fused(half_at(v_cache, kept, g, d, 0), pr0, o0_0); + o0_1 = fused(half_at(v_cache, kept, g, d, 1), pr0, o0_1); + o0_2 = fused(half_at(v_cache, kept, g, d, 2), pr0, o0_2); + o0_3 = fused(half_at(v_cache, kept, g, d, 3), pr0, o0_3); + let pr1 = lane_value(p1, r); + o1_0 = fused(half_at(v_cache, kept, g, d, 0), pr1, o1_0); + o1_1 = fused(half_at(v_cache, kept, g, d, 1), pr1, o1_1); + o1_2 = fused(half_at(v_cache, kept, g, d, 2), pr1, o1_2); + o1_3 = fused(half_at(v_cache, kept, g, d, 3), pr1, o1_3); + } + c = c + nwg; } - %ov:2 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%oa0 = %u0#2, %oa1 = %u1#2) -> (vector<4xf32>, vector<4xf32>) { - %row = arith.addi %r0, %cc : index - %rowc = arith.minui %row, %pos1 : 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 - %pc0, %pv0 = gpu.shuffle idx %u0#3, %cci, %c32i : f32 - %pcv0 = vector.broadcast %pc0 : f32 to vector<4xf32> - %on0 = vector.fma %vf, %pcv0, %oa0 : vector<4xf32> - %pc1, %pv1 = gpu.shuffle idx %u1#3, %cci, %c32i : f32 - %pcv1 = vector.broadcast %pc1 : f32 to vector<4xf32> - %on1 = vector.fma %vf, %pcv1, %oa1 : vector<4xf32> - scf.yield %on0, %on1 : vector<4xf32>, vector<4xf32> + let b0 = 132 * (t0 + 0); + part[h][w][b0 + d + 0] = o0_0; + part[h][w][b0 + d + 1] = o0_1; + part[h][w][b0 + d + 2] = o0_2; + part[h][w][b0 + d + 3] = o0_3; + let b1 = 132 * (t0 + 1); + part[h][w][b1 + d + 0] = o1_0; + part[h][w][b1 + d + 1] = o1_1; + part[h][w][b1 + d + 2] = o1_2; + part[h][w][b1 + d + 3] = o1_3; + // Every lane has the same largest score and sum of the weights of a query. Lanes 0 and 1 keep them + // for the next loop. + if l < 2 { + let mut x0 = big0; + if l == 1 { + x0 = total0; + } + stats[s][0][l] = x0; + let mut x1 = big1; + if l == 1 { + x1 = total1; + } + stats[s][1][l] = x1; } - scf.yield %u0#0, %u0#1, %ov#0, %u1#0, %u1#1, %ov#1 : f32, f32, vector<4xf32>, f32, f32, vector<4xf32> - } - %lane0 = arith.cmpi eq, %l, %c0 : index - %base0 = arith.muli %qt0, %c132 : index - %at0 = arith.addi %base0, %l4 : index - vector.store %st#2, %part[%hi, %wi, %at0] : memref, vector<4xf32> - %am0 = arith.addi %base0, %c128 : index - %as0 = arith.addi %base0, %c129 : index - scf.if %lane0 { - memref.store %st#0, %part[%hi, %wi, %am0] : memref - memref.store %st#1, %part[%hi, %wi, %as0] : memref } - %base1 = arith.muli %qt1, %c132 : index - %at1 = arith.addi %base1, %l4 : index - vector.store %st#5, %part[%hi, %wi, %at1] : memref, vector<4xf32> - %am1 = arith.addi %base1, %c128 : index - %as1 = arith.addi %base1, %c129 : index - scf.if %lane0 { - memref.store %st#3, %part[%hi, %wi, %am1] : memref - memref.store %st#4, %part[%hi, %wi, %as1] : memref + for l in 0..2 across lanes(32) { + part[h][w][132 * (t0 + 0) + 128 + l] = stats[s][0][l]; + part[h][w][132 * (t0 + 1) + 128 + l] = stats[s][1][l]; } - macro.yield %h : i32 - }; + } } } } @@ -408,184 +395,180 @@ fn round_attention_parts_3(part : &mut Tensor, q : 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, %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])]) { - %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 - %c132 = arith.constant 132 : 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 - %t0i = arith.index_cast %t0 : 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> - %scv = vector.broadcast %scale : f32 to vector<4xf32> - %ct0 = arith.constant 0 : index - %pos0 = arith.addi %posi, %ct0 : index - %n0 = arith.addi %pos0, %c32 : index - %chunks0 = arith.divui %n0, %c32 : index - %qt0 = arith.addi %t0i, %ct0 : index - %qv0 = vector.load %q[%qt0, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs0 = arith.mulf %qv0, %scv : vector<4xf32> - %ct1 = arith.constant 1 : index - %pos1 = arith.addi %posi, %ct1 : index - %n1 = arith.addi %pos1, %c32 : index - %chunks1 = arith.divui %n1, %c32 : index - %qt1 = arith.addi %t0i, %ct1 : index - %qv1 = vector.load %q[%qt1, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs1 = arith.mulf %qv1, %scv : vector<4xf32> - %ct2 = arith.constant 2 : index - %pos2 = arith.addi %posi, %ct2 : index - %n2 = arith.addi %pos2, %c32 : index - %chunks2 = arith.divui %n2, %c32 : index - %qt2 = arith.addi %t0i, %ct2 : index - %qv2 = vector.load %q[%qt2, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs2 = arith.mulf %qv2, %scv : vector<4xf32> - %st:9 = scf.for %ic = %wi to %chunks2 step %nwgi iter_args(%M0 = %neg, %S0 = %zero, %o0 = %vz4, %M1 = %neg, %S1 = %zero, %o1 = %vz4, %M2 = %neg, %S2 = %zero, %o2 = %vz4) -> (f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>) { - %r0 = arith.muli %ic, %c32 : index - %my:3 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%m0 = %neg, %m1 = %neg, %m2 = %neg) -> (f32, f32, f32) { - %row = arith.addi %r0, %cc : index - %rowc = arith.minui %row, %pos2 : index - %kh = vector.load %k[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> - %kf = arith.extf %kh : vector<4xf16> to vector<4xf32> - %mine = arith.cmpi eq, %cc, %l : index - %pr0 = arith.mulf %kf, %qs0 : vector<4xf32> - %pl0 = vector.reduction , %pr0 : vector<4xf32> into f32 - %sc0 = gpu.subgroup_reduce add %pl0 : (f32) -> f32 - %live0 = arith.cmpi ule, %row, %pos0 : index - %scm0 = arith.select %live0, %sc0, %neg : f32 - %mm0 = arith.select %mine, %scm0, %m0 : f32 - %pr1 = arith.mulf %kf, %qs1 : vector<4xf32> - %pl1 = vector.reduction , %pr1 : vector<4xf32> into f32 - %sc1 = gpu.subgroup_reduce add %pl1 : (f32) -> f32 - %live1 = arith.cmpi ule, %row, %pos1 : index - %scm1 = arith.select %live1, %sc1, %neg : f32 - %mm1 = arith.select %mine, %scm1, %m1 : f32 - %pr2 = arith.mulf %kf, %qs2 : vector<4xf32> - %pl2 = vector.reduction , %pr2 : vector<4xf32> into f32 - %sc2 = gpu.subgroup_reduce add %pl2 : (f32) -> f32 - %live2 = arith.cmpi ule, %row, %pos2 : index - %scm2 = arith.select %live2, %sc2, %neg : f32 - %mm2 = arith.select %mine, %scm2, %m2 : f32 - scf.yield %mm0, %mm1, %mm2 : f32, f32, f32 - } - %act0 = arith.cmpi ult, %ic, %chunks0 : index - %u0:4 = scf.if %act0 -> (f32, f32, vector<4xf32>, f32) { - %bm0 = gpu.subgroup_reduce maxnumf %my#0 : (f32) -> f32 - %Mn0 = arith.maxnumf %M0, %bm0 : f32 - %dm0 = arith.subf %M0, %Mn0 : f32 - %ms0 = math.exp %dm0 : f32 - %dp0 = arith.subf %my#0, %Mn0 : f32 - %p0 = math.exp %dp0 : f32 - %bs0 = gpu.subgroup_reduce add %p0 : (f32) -> f32 - %Ss0 = arith.mulf %S0, %ms0 : f32 - %Sn0 = arith.addf %Ss0, %bs0 : f32 - %msv0 = vector.broadcast %ms0 : f32 to vector<4xf32> - %ox0 = arith.mulf %o0, %msv0 : vector<4xf32> - scf.yield %Mn0, %Sn0, %ox0, %p0 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M0, %S0, %o0, %zero : f32, f32, vector<4xf32>, f32 - } - %act1 = arith.cmpi ult, %ic, %chunks1 : index - %u1:4 = scf.if %act1 -> (f32, f32, vector<4xf32>, f32) { - %bm1 = gpu.subgroup_reduce maxnumf %my#1 : (f32) -> f32 - %Mn1 = arith.maxnumf %M1, %bm1 : f32 - %dm1 = arith.subf %M1, %Mn1 : f32 - %ms1 = math.exp %dm1 : f32 - %dp1 = arith.subf %my#1, %Mn1 : f32 - %p1 = math.exp %dp1 : f32 - %bs1 = gpu.subgroup_reduce add %p1 : (f32) -> f32 - %Ss1 = arith.mulf %S1, %ms1 : f32 - %Sn1 = arith.addf %Ss1, %bs1 : f32 - %msv1 = vector.broadcast %ms1 : f32 to vector<4xf32> - %ox1 = arith.mulf %o1, %msv1 : vector<4xf32> - scf.yield %Mn1, %Sn1, %ox1, %p1 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M1, %S1, %o1, %zero : f32, f32, vector<4xf32>, f32 - } - %act2 = arith.cmpi ult, %ic, %chunks2 : index - %u2:4 = scf.if %act2 -> (f32, f32, vector<4xf32>, f32) { - %bm2 = gpu.subgroup_reduce maxnumf %my#2 : (f32) -> f32 - %Mn2 = arith.maxnumf %M2, %bm2 : f32 - %dm2 = arith.subf %M2, %Mn2 : f32 - %ms2 = math.exp %dm2 : f32 - %dp2 = arith.subf %my#2, %Mn2 : f32 - %p2 = math.exp %dp2 : f32 - %bs2 = gpu.subgroup_reduce add %p2 : (f32) -> f32 - %Ss2 = arith.mulf %S2, %ms2 : f32 - %Sn2 = arith.addf %Ss2, %bs2 : f32 - %msv2 = vector.broadcast %ms2 : f32 to vector<4xf32> - %ox2 = arith.mulf %o2, %msv2 : vector<4xf32> - scf.yield %Mn2, %Sn2, %ox2, %p2 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M2, %S2, %o2, %zero : f32, f32, vector<4xf32>, f32 + 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 = 4 * l; + let last = pos + 2; + let q0_0 = q[t0 + 0][h][d + 0] * scale; + let q0_1 = q[t0 + 0][h][d + 1] * scale; + let q0_2 = q[t0 + 0][h][d + 2] * scale; + let q0_3 = q[t0 + 0][h][d + 3] * scale; + let mut big0 : f32 = -3.0e38; + let mut total0 : f32 = 0.0; + let mut o0_0 : f32 = 0.0; + let mut o0_1 : f32 = 0.0; + let mut o0_2 : f32 = 0.0; + let mut o0_3 : f32 = 0.0; + let q1_0 = q[t0 + 1][h][d + 0] * scale; + let q1_1 = q[t0 + 1][h][d + 1] * scale; + let q1_2 = q[t0 + 1][h][d + 2] * scale; + let q1_3 = q[t0 + 1][h][d + 3] * scale; + let mut big1 : f32 = -3.0e38; + let mut total1 : f32 = 0.0; + let mut o1_0 : f32 = 0.0; + let mut o1_1 : f32 = 0.0; + let mut o1_2 : f32 = 0.0; + let mut o1_3 : f32 = 0.0; + let q2_0 = q[t0 + 2][h][d + 0] * scale; + let q2_1 = q[t0 + 2][h][d + 1] * scale; + let q2_2 = q[t0 + 2][h][d + 2] * scale; + let q2_3 = q[t0 + 2][h][d + 3] * scale; + let mut big2 : f32 = -3.0e38; + let mut total2 : f32 = 0.0; + let mut o2_0 : f32 = 0.0; + let mut o2_1 : f32 = 0.0; + let mut o2_2 : f32 = 0.0; + let mut o2_3 : f32 = 0.0; + let chunks = (last + 32) / 32; + let mut c = w; + while c < chunks { + let r0 = c * 32; + let mut mine0 : f32 = -3.0e38; + let mut mine1 : f32 = -3.0e38; + let mut mine2 : f32 = -3.0e38; + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > last { + kept = last; + } + let k0 = half_at(k_cache, kept, g, d, 0); + let k1 = half_at(k_cache, kept, g, d, 1); + let k2 = half_at(k_cache, kept, g, d, 2); + let k3 = half_at(k_cache, kept, g, d, 3); + let mut score0 = lane_sum(k0 * q0_0 + k1 * q0_1 + k2 * q0_2 + k3 * q0_3); + if row > pos + 0 { + score0 = -3.0e38; + } + let mut score1 = lane_sum(k0 * q1_0 + k1 * q1_1 + k2 * q1_2 + k3 * q1_3); + if row > pos + 1 { + score1 = -3.0e38; + } + let mut score2 = lane_sum(k0 * q2_0 + k1 * q2_1 + k2 * q2_2 + k3 * q2_3); + if row > pos + 2 { + score2 = -3.0e38; + } + if r == l { + mine0 = score0; + mine1 = score1; + mine2 = score2; + } + } + let mut p0 : f32 = 0.0; + if c < (pos + 0 + 32) / 32 { + let top = big0.max(lane_max(mine0)); + let shrink = (big0 - top).fast_exp(); + p0 = (mine0 - top).fast_exp(); + total0 = total0 * shrink + lane_sum(p0); + o0_0 = o0_0 * shrink; + o0_1 = o0_1 * shrink; + o0_2 = o0_2 * shrink; + o0_3 = o0_3 * shrink; + big0 = top; + } + let mut p1 : f32 = 0.0; + if c < (pos + 1 + 32) / 32 { + let top = big1.max(lane_max(mine1)); + let shrink = (big1 - top).fast_exp(); + p1 = (mine1 - top).fast_exp(); + total1 = total1 * shrink + lane_sum(p1); + o1_0 = o1_0 * shrink; + o1_1 = o1_1 * shrink; + o1_2 = o1_2 * shrink; + o1_3 = o1_3 * shrink; + big1 = top; + } + let mut p2 : f32 = 0.0; + if c < (pos + 2 + 32) / 32 { + let top = big2.max(lane_max(mine2)); + let shrink = (big2 - top).fast_exp(); + p2 = (mine2 - top).fast_exp(); + total2 = total2 * shrink + lane_sum(p2); + o2_0 = o2_0 * shrink; + o2_1 = o2_1 * shrink; + o2_2 = o2_2 * shrink; + o2_3 = o2_3 * shrink; + big2 = top; + } + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > last { + kept = last; + } + let pr0 = lane_value(p0, r); + o0_0 = fused(half_at(v_cache, kept, g, d, 0), pr0, o0_0); + o0_1 = fused(half_at(v_cache, kept, g, d, 1), pr0, o0_1); + o0_2 = fused(half_at(v_cache, kept, g, d, 2), pr0, o0_2); + o0_3 = fused(half_at(v_cache, kept, g, d, 3), pr0, o0_3); + let pr1 = lane_value(p1, r); + o1_0 = fused(half_at(v_cache, kept, g, d, 0), pr1, o1_0); + o1_1 = fused(half_at(v_cache, kept, g, d, 1), pr1, o1_1); + o1_2 = fused(half_at(v_cache, kept, g, d, 2), pr1, o1_2); + o1_3 = fused(half_at(v_cache, kept, g, d, 3), pr1, o1_3); + let pr2 = lane_value(p2, r); + o2_0 = fused(half_at(v_cache, kept, g, d, 0), pr2, o2_0); + o2_1 = fused(half_at(v_cache, kept, g, d, 1), pr2, o2_1); + o2_2 = fused(half_at(v_cache, kept, g, d, 2), pr2, o2_2); + o2_3 = fused(half_at(v_cache, kept, g, d, 3), pr2, o2_3); + } + c = c + nwg; } - %ov:3 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%oa0 = %u0#2, %oa1 = %u1#2, %oa2 = %u2#2) -> (vector<4xf32>, vector<4xf32>, vector<4xf32>) { - %row = arith.addi %r0, %cc : index - %rowc = arith.minui %row, %pos2 : 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 - %pc0, %pv0 = gpu.shuffle idx %u0#3, %cci, %c32i : f32 - %pcv0 = vector.broadcast %pc0 : f32 to vector<4xf32> - %on0 = vector.fma %vf, %pcv0, %oa0 : vector<4xf32> - %pc1, %pv1 = gpu.shuffle idx %u1#3, %cci, %c32i : f32 - %pcv1 = vector.broadcast %pc1 : f32 to vector<4xf32> - %on1 = vector.fma %vf, %pcv1, %oa1 : vector<4xf32> - %pc2, %pv2 = gpu.shuffle idx %u2#3, %cci, %c32i : f32 - %pcv2 = vector.broadcast %pc2 : f32 to vector<4xf32> - %on2 = vector.fma %vf, %pcv2, %oa2 : vector<4xf32> - scf.yield %on0, %on1, %on2 : vector<4xf32>, vector<4xf32>, vector<4xf32> + let b0 = 132 * (t0 + 0); + part[h][w][b0 + d + 0] = o0_0; + part[h][w][b0 + d + 1] = o0_1; + part[h][w][b0 + d + 2] = o0_2; + part[h][w][b0 + d + 3] = o0_3; + let b1 = 132 * (t0 + 1); + part[h][w][b1 + d + 0] = o1_0; + part[h][w][b1 + d + 1] = o1_1; + part[h][w][b1 + d + 2] = o1_2; + part[h][w][b1 + d + 3] = o1_3; + let b2 = 132 * (t0 + 2); + part[h][w][b2 + d + 0] = o2_0; + part[h][w][b2 + d + 1] = o2_1; + part[h][w][b2 + d + 2] = o2_2; + part[h][w][b2 + d + 3] = o2_3; + // Every lane has the same largest score and sum of the weights of a query. Lanes 0 and 1 keep them + // for the next loop. + if l < 2 { + let mut x0 = big0; + if l == 1 { + x0 = total0; + } + stats[s][0][l] = x0; + let mut x1 = big1; + if l == 1 { + x1 = total1; + } + stats[s][1][l] = x1; + let mut x2 = big2; + if l == 1 { + x2 = total2; + } + stats[s][2][l] = x2; } - scf.yield %u0#0, %u0#1, %ov#0, %u1#0, %u1#1, %ov#1, %u2#0, %u2#1, %ov#2 : f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32> - } - %lane0 = arith.cmpi eq, %l, %c0 : index - %base0 = arith.muli %qt0, %c132 : index - %at0 = arith.addi %base0, %l4 : index - vector.store %st#2, %part[%hi, %wi, %at0] : memref, vector<4xf32> - %am0 = arith.addi %base0, %c128 : index - %as0 = arith.addi %base0, %c129 : index - scf.if %lane0 { - memref.store %st#0, %part[%hi, %wi, %am0] : memref - memref.store %st#1, %part[%hi, %wi, %as0] : memref - } - %base1 = arith.muli %qt1, %c132 : index - %at1 = arith.addi %base1, %l4 : index - vector.store %st#5, %part[%hi, %wi, %at1] : memref, vector<4xf32> - %am1 = arith.addi %base1, %c128 : index - %as1 = arith.addi %base1, %c129 : index - scf.if %lane0 { - memref.store %st#3, %part[%hi, %wi, %am1] : memref - memref.store %st#4, %part[%hi, %wi, %as1] : memref } - %base2 = arith.muli %qt2, %c132 : index - %at2 = arith.addi %base2, %l4 : index - vector.store %st#8, %part[%hi, %wi, %at2] : memref, vector<4xf32> - %am2 = arith.addi %base2, %c128 : index - %as2 = arith.addi %base2, %c129 : index - scf.if %lane0 { - memref.store %st#6, %part[%hi, %wi, %am2] : memref - memref.store %st#7, %part[%hi, %wi, %as2] : memref + for l in 0..2 across lanes(32) { + part[h][w][132 * (t0 + 0) + 128 + l] = stats[s][0][l]; + part[h][w][132 * (t0 + 1) + 128 + l] = stats[s][1][l]; + part[h][w][132 * (t0 + 2) + 128 + l] = stats[s][2][l]; } - macro.yield %h : i32 - }; + } } } } @@ -598,226 +581,224 @@ fn round_attention_parts_4(part : &mut Tensor, q : 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, %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])]) { - %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 - %c132 = arith.constant 132 : 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 - %t0i = arith.index_cast %t0 : 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> - %scv = vector.broadcast %scale : f32 to vector<4xf32> - %ct0 = arith.constant 0 : index - %pos0 = arith.addi %posi, %ct0 : index - %n0 = arith.addi %pos0, %c32 : index - %chunks0 = arith.divui %n0, %c32 : index - %qt0 = arith.addi %t0i, %ct0 : index - %qv0 = vector.load %q[%qt0, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs0 = arith.mulf %qv0, %scv : vector<4xf32> - %ct1 = arith.constant 1 : index - %pos1 = arith.addi %posi, %ct1 : index - %n1 = arith.addi %pos1, %c32 : index - %chunks1 = arith.divui %n1, %c32 : index - %qt1 = arith.addi %t0i, %ct1 : index - %qv1 = vector.load %q[%qt1, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs1 = arith.mulf %qv1, %scv : vector<4xf32> - %ct2 = arith.constant 2 : index - %pos2 = arith.addi %posi, %ct2 : index - %n2 = arith.addi %pos2, %c32 : index - %chunks2 = arith.divui %n2, %c32 : index - %qt2 = arith.addi %t0i, %ct2 : index - %qv2 = vector.load %q[%qt2, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs2 = arith.mulf %qv2, %scv : vector<4xf32> - %ct3 = arith.constant 3 : index - %pos3 = arith.addi %posi, %ct3 : index - %n3 = arith.addi %pos3, %c32 : index - %chunks3 = arith.divui %n3, %c32 : index - %qt3 = arith.addi %t0i, %ct3 : index - %qv3 = vector.load %q[%qt3, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs3 = arith.mulf %qv3, %scv : vector<4xf32> - %st:12 = scf.for %ic = %wi to %chunks3 step %nwgi iter_args(%M0 = %neg, %S0 = %zero, %o0 = %vz4, %M1 = %neg, %S1 = %zero, %o1 = %vz4, %M2 = %neg, %S2 = %zero, %o2 = %vz4, %M3 = %neg, %S3 = %zero, %o3 = %vz4) -> (f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>) { - %r0 = arith.muli %ic, %c32 : index - %my:4 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%m0 = %neg, %m1 = %neg, %m2 = %neg, %m3 = %neg) -> (f32, f32, f32, f32) { - %row = arith.addi %r0, %cc : index - %rowc = arith.minui %row, %pos3 : index - %kh = vector.load %k[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> - %kf = arith.extf %kh : vector<4xf16> to vector<4xf32> - %mine = arith.cmpi eq, %cc, %l : index - %pr0 = arith.mulf %kf, %qs0 : vector<4xf32> - %pl0 = vector.reduction , %pr0 : vector<4xf32> into f32 - %sc0 = gpu.subgroup_reduce add %pl0 : (f32) -> f32 - %live0 = arith.cmpi ule, %row, %pos0 : index - %scm0 = arith.select %live0, %sc0, %neg : f32 - %mm0 = arith.select %mine, %scm0, %m0 : f32 - %pr1 = arith.mulf %kf, %qs1 : vector<4xf32> - %pl1 = vector.reduction , %pr1 : vector<4xf32> into f32 - %sc1 = gpu.subgroup_reduce add %pl1 : (f32) -> f32 - %live1 = arith.cmpi ule, %row, %pos1 : index - %scm1 = arith.select %live1, %sc1, %neg : f32 - %mm1 = arith.select %mine, %scm1, %m1 : f32 - %pr2 = arith.mulf %kf, %qs2 : vector<4xf32> - %pl2 = vector.reduction , %pr2 : vector<4xf32> into f32 - %sc2 = gpu.subgroup_reduce add %pl2 : (f32) -> f32 - %live2 = arith.cmpi ule, %row, %pos2 : index - %scm2 = arith.select %live2, %sc2, %neg : f32 - %mm2 = arith.select %mine, %scm2, %m2 : f32 - %pr3 = arith.mulf %kf, %qs3 : vector<4xf32> - %pl3 = vector.reduction , %pr3 : vector<4xf32> into f32 - %sc3 = gpu.subgroup_reduce add %pl3 : (f32) -> f32 - %live3 = arith.cmpi ule, %row, %pos3 : index - %scm3 = arith.select %live3, %sc3, %neg : f32 - %mm3 = arith.select %mine, %scm3, %m3 : f32 - scf.yield %mm0, %mm1, %mm2, %mm3 : f32, f32, f32, f32 - } - %act0 = arith.cmpi ult, %ic, %chunks0 : index - %u0:4 = scf.if %act0 -> (f32, f32, vector<4xf32>, f32) { - %bm0 = gpu.subgroup_reduce maxnumf %my#0 : (f32) -> f32 - %Mn0 = arith.maxnumf %M0, %bm0 : f32 - %dm0 = arith.subf %M0, %Mn0 : f32 - %ms0 = math.exp %dm0 : f32 - %dp0 = arith.subf %my#0, %Mn0 : f32 - %p0 = math.exp %dp0 : f32 - %bs0 = gpu.subgroup_reduce add %p0 : (f32) -> f32 - %Ss0 = arith.mulf %S0, %ms0 : f32 - %Sn0 = arith.addf %Ss0, %bs0 : f32 - %msv0 = vector.broadcast %ms0 : f32 to vector<4xf32> - %ox0 = arith.mulf %o0, %msv0 : vector<4xf32> - scf.yield %Mn0, %Sn0, %ox0, %p0 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M0, %S0, %o0, %zero : f32, f32, vector<4xf32>, f32 - } - %act1 = arith.cmpi ult, %ic, %chunks1 : index - %u1:4 = scf.if %act1 -> (f32, f32, vector<4xf32>, f32) { - %bm1 = gpu.subgroup_reduce maxnumf %my#1 : (f32) -> f32 - %Mn1 = arith.maxnumf %M1, %bm1 : f32 - %dm1 = arith.subf %M1, %Mn1 : f32 - %ms1 = math.exp %dm1 : f32 - %dp1 = arith.subf %my#1, %Mn1 : f32 - %p1 = math.exp %dp1 : f32 - %bs1 = gpu.subgroup_reduce add %p1 : (f32) -> f32 - %Ss1 = arith.mulf %S1, %ms1 : f32 - %Sn1 = arith.addf %Ss1, %bs1 : f32 - %msv1 = vector.broadcast %ms1 : f32 to vector<4xf32> - %ox1 = arith.mulf %o1, %msv1 : vector<4xf32> - scf.yield %Mn1, %Sn1, %ox1, %p1 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M1, %S1, %o1, %zero : f32, f32, vector<4xf32>, f32 - } - %act2 = arith.cmpi ult, %ic, %chunks2 : index - %u2:4 = scf.if %act2 -> (f32, f32, vector<4xf32>, f32) { - %bm2 = gpu.subgroup_reduce maxnumf %my#2 : (f32) -> f32 - %Mn2 = arith.maxnumf %M2, %bm2 : f32 - %dm2 = arith.subf %M2, %Mn2 : f32 - %ms2 = math.exp %dm2 : f32 - %dp2 = arith.subf %my#2, %Mn2 : f32 - %p2 = math.exp %dp2 : f32 - %bs2 = gpu.subgroup_reduce add %p2 : (f32) -> f32 - %Ss2 = arith.mulf %S2, %ms2 : f32 - %Sn2 = arith.addf %Ss2, %bs2 : f32 - %msv2 = vector.broadcast %ms2 : f32 to vector<4xf32> - %ox2 = arith.mulf %o2, %msv2 : vector<4xf32> - scf.yield %Mn2, %Sn2, %ox2, %p2 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M2, %S2, %o2, %zero : f32, f32, vector<4xf32>, f32 - } - %act3 = arith.cmpi ult, %ic, %chunks3 : index - %u3:4 = scf.if %act3 -> (f32, f32, vector<4xf32>, f32) { - %bm3 = gpu.subgroup_reduce maxnumf %my#3 : (f32) -> f32 - %Mn3 = arith.maxnumf %M3, %bm3 : f32 - %dm3 = arith.subf %M3, %Mn3 : f32 - %ms3 = math.exp %dm3 : f32 - %dp3 = arith.subf %my#3, %Mn3 : f32 - %p3 = math.exp %dp3 : f32 - %bs3 = gpu.subgroup_reduce add %p3 : (f32) -> f32 - %Ss3 = arith.mulf %S3, %ms3 : f32 - %Sn3 = arith.addf %Ss3, %bs3 : f32 - %msv3 = vector.broadcast %ms3 : f32 to vector<4xf32> - %ox3 = arith.mulf %o3, %msv3 : vector<4xf32> - scf.yield %Mn3, %Sn3, %ox3, %p3 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M3, %S3, %o3, %zero : f32, f32, vector<4xf32>, f32 + 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 = 4 * l; + let last = pos + 3; + let q0_0 = q[t0 + 0][h][d + 0] * scale; + let q0_1 = q[t0 + 0][h][d + 1] * scale; + let q0_2 = q[t0 + 0][h][d + 2] * scale; + let q0_3 = q[t0 + 0][h][d + 3] * scale; + let mut big0 : f32 = -3.0e38; + let mut total0 : f32 = 0.0; + let mut o0_0 : f32 = 0.0; + let mut o0_1 : f32 = 0.0; + let mut o0_2 : f32 = 0.0; + let mut o0_3 : f32 = 0.0; + let q1_0 = q[t0 + 1][h][d + 0] * scale; + let q1_1 = q[t0 + 1][h][d + 1] * scale; + let q1_2 = q[t0 + 1][h][d + 2] * scale; + let q1_3 = q[t0 + 1][h][d + 3] * scale; + let mut big1 : f32 = -3.0e38; + let mut total1 : f32 = 0.0; + let mut o1_0 : f32 = 0.0; + let mut o1_1 : f32 = 0.0; + let mut o1_2 : f32 = 0.0; + let mut o1_3 : f32 = 0.0; + let q2_0 = q[t0 + 2][h][d + 0] * scale; + let q2_1 = q[t0 + 2][h][d + 1] * scale; + let q2_2 = q[t0 + 2][h][d + 2] * scale; + let q2_3 = q[t0 + 2][h][d + 3] * scale; + let mut big2 : f32 = -3.0e38; + let mut total2 : f32 = 0.0; + let mut o2_0 : f32 = 0.0; + let mut o2_1 : f32 = 0.0; + let mut o2_2 : f32 = 0.0; + let mut o2_3 : f32 = 0.0; + let q3_0 = q[t0 + 3][h][d + 0] * scale; + let q3_1 = q[t0 + 3][h][d + 1] * scale; + let q3_2 = q[t0 + 3][h][d + 2] * scale; + let q3_3 = q[t0 + 3][h][d + 3] * scale; + let mut big3 : f32 = -3.0e38; + let mut total3 : f32 = 0.0; + let mut o3_0 : f32 = 0.0; + let mut o3_1 : f32 = 0.0; + let mut o3_2 : f32 = 0.0; + let mut o3_3 : f32 = 0.0; + let chunks = (last + 32) / 32; + let mut c = w; + while c < chunks { + let r0 = c * 32; + let mut mine0 : f32 = -3.0e38; + let mut mine1 : f32 = -3.0e38; + let mut mine2 : f32 = -3.0e38; + let mut mine3 : f32 = -3.0e38; + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > last { + kept = last; + } + let k0 = half_at(k_cache, kept, g, d, 0); + let k1 = half_at(k_cache, kept, g, d, 1); + let k2 = half_at(k_cache, kept, g, d, 2); + let k3 = half_at(k_cache, kept, g, d, 3); + let mut score0 = lane_sum(k0 * q0_0 + k1 * q0_1 + k2 * q0_2 + k3 * q0_3); + if row > pos + 0 { + score0 = -3.0e38; + } + let mut score1 = lane_sum(k0 * q1_0 + k1 * q1_1 + k2 * q1_2 + k3 * q1_3); + if row > pos + 1 { + score1 = -3.0e38; + } + let mut score2 = lane_sum(k0 * q2_0 + k1 * q2_1 + k2 * q2_2 + k3 * q2_3); + if row > pos + 2 { + score2 = -3.0e38; + } + let mut score3 = lane_sum(k0 * q3_0 + k1 * q3_1 + k2 * q3_2 + k3 * q3_3); + if row > pos + 3 { + score3 = -3.0e38; + } + if r == l { + mine0 = score0; + mine1 = score1; + mine2 = score2; + mine3 = score3; + } + } + let mut p0 : f32 = 0.0; + if c < (pos + 0 + 32) / 32 { + let top = big0.max(lane_max(mine0)); + let shrink = (big0 - top).fast_exp(); + p0 = (mine0 - top).fast_exp(); + total0 = total0 * shrink + lane_sum(p0); + o0_0 = o0_0 * shrink; + o0_1 = o0_1 * shrink; + o0_2 = o0_2 * shrink; + o0_3 = o0_3 * shrink; + big0 = top; + } + let mut p1 : f32 = 0.0; + if c < (pos + 1 + 32) / 32 { + let top = big1.max(lane_max(mine1)); + let shrink = (big1 - top).fast_exp(); + p1 = (mine1 - top).fast_exp(); + total1 = total1 * shrink + lane_sum(p1); + o1_0 = o1_0 * shrink; + o1_1 = o1_1 * shrink; + o1_2 = o1_2 * shrink; + o1_3 = o1_3 * shrink; + big1 = top; + } + let mut p2 : f32 = 0.0; + if c < (pos + 2 + 32) / 32 { + let top = big2.max(lane_max(mine2)); + let shrink = (big2 - top).fast_exp(); + p2 = (mine2 - top).fast_exp(); + total2 = total2 * shrink + lane_sum(p2); + o2_0 = o2_0 * shrink; + o2_1 = o2_1 * shrink; + o2_2 = o2_2 * shrink; + o2_3 = o2_3 * shrink; + big2 = top; + } + let mut p3 : f32 = 0.0; + if c < (pos + 3 + 32) / 32 { + let top = big3.max(lane_max(mine3)); + let shrink = (big3 - top).fast_exp(); + p3 = (mine3 - top).fast_exp(); + total3 = total3 * shrink + lane_sum(p3); + o3_0 = o3_0 * shrink; + o3_1 = o3_1 * shrink; + o3_2 = o3_2 * shrink; + o3_3 = o3_3 * shrink; + big3 = top; + } + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > last { + kept = last; + } + let pr0 = lane_value(p0, r); + o0_0 = fused(half_at(v_cache, kept, g, d, 0), pr0, o0_0); + o0_1 = fused(half_at(v_cache, kept, g, d, 1), pr0, o0_1); + o0_2 = fused(half_at(v_cache, kept, g, d, 2), pr0, o0_2); + o0_3 = fused(half_at(v_cache, kept, g, d, 3), pr0, o0_3); + let pr1 = lane_value(p1, r); + o1_0 = fused(half_at(v_cache, kept, g, d, 0), pr1, o1_0); + o1_1 = fused(half_at(v_cache, kept, g, d, 1), pr1, o1_1); + o1_2 = fused(half_at(v_cache, kept, g, d, 2), pr1, o1_2); + o1_3 = fused(half_at(v_cache, kept, g, d, 3), pr1, o1_3); + let pr2 = lane_value(p2, r); + o2_0 = fused(half_at(v_cache, kept, g, d, 0), pr2, o2_0); + o2_1 = fused(half_at(v_cache, kept, g, d, 1), pr2, o2_1); + o2_2 = fused(half_at(v_cache, kept, g, d, 2), pr2, o2_2); + o2_3 = fused(half_at(v_cache, kept, g, d, 3), pr2, o2_3); + let pr3 = lane_value(p3, r); + o3_0 = fused(half_at(v_cache, kept, g, d, 0), pr3, o3_0); + o3_1 = fused(half_at(v_cache, kept, g, d, 1), pr3, o3_1); + o3_2 = fused(half_at(v_cache, kept, g, d, 2), pr3, o3_2); + o3_3 = fused(half_at(v_cache, kept, g, d, 3), pr3, o3_3); + } + c = c + nwg; } - %ov:4 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%oa0 = %u0#2, %oa1 = %u1#2, %oa2 = %u2#2, %oa3 = %u3#2) -> (vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>) { - %row = arith.addi %r0, %cc : index - %rowc = arith.minui %row, %pos3 : 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 - %pc0, %pv0 = gpu.shuffle idx %u0#3, %cci, %c32i : f32 - %pcv0 = vector.broadcast %pc0 : f32 to vector<4xf32> - %on0 = vector.fma %vf, %pcv0, %oa0 : vector<4xf32> - %pc1, %pv1 = gpu.shuffle idx %u1#3, %cci, %c32i : f32 - %pcv1 = vector.broadcast %pc1 : f32 to vector<4xf32> - %on1 = vector.fma %vf, %pcv1, %oa1 : vector<4xf32> - %pc2, %pv2 = gpu.shuffle idx %u2#3, %cci, %c32i : f32 - %pcv2 = vector.broadcast %pc2 : f32 to vector<4xf32> - %on2 = vector.fma %vf, %pcv2, %oa2 : vector<4xf32> - %pc3, %pv3 = gpu.shuffle idx %u3#3, %cci, %c32i : f32 - %pcv3 = vector.broadcast %pc3 : f32 to vector<4xf32> - %on3 = vector.fma %vf, %pcv3, %oa3 : vector<4xf32> - scf.yield %on0, %on1, %on2, %on3 : vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32> + let b0 = 132 * (t0 + 0); + part[h][w][b0 + d + 0] = o0_0; + part[h][w][b0 + d + 1] = o0_1; + part[h][w][b0 + d + 2] = o0_2; + part[h][w][b0 + d + 3] = o0_3; + let b1 = 132 * (t0 + 1); + part[h][w][b1 + d + 0] = o1_0; + part[h][w][b1 + d + 1] = o1_1; + part[h][w][b1 + d + 2] = o1_2; + part[h][w][b1 + d + 3] = o1_3; + let b2 = 132 * (t0 + 2); + part[h][w][b2 + d + 0] = o2_0; + part[h][w][b2 + d + 1] = o2_1; + part[h][w][b2 + d + 2] = o2_2; + part[h][w][b2 + d + 3] = o2_3; + let b3 = 132 * (t0 + 3); + part[h][w][b3 + d + 0] = o3_0; + part[h][w][b3 + d + 1] = o3_1; + part[h][w][b3 + d + 2] = o3_2; + part[h][w][b3 + d + 3] = o3_3; + // Every lane has the same largest score and sum of the weights of a query. Lanes 0 and 1 keep them + // for the next loop. + if l < 2 { + let mut x0 = big0; + if l == 1 { + x0 = total0; + } + stats[s][0][l] = x0; + let mut x1 = big1; + if l == 1 { + x1 = total1; + } + stats[s][1][l] = x1; + let mut x2 = big2; + if l == 1 { + x2 = total2; + } + stats[s][2][l] = x2; + let mut x3 = big3; + if l == 1 { + x3 = total3; + } + stats[s][3][l] = x3; } - scf.yield %u0#0, %u0#1, %ov#0, %u1#0, %u1#1, %ov#1, %u2#0, %u2#1, %ov#2, %u3#0, %u3#1, %ov#3 : f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32> - } - %lane0 = arith.cmpi eq, %l, %c0 : index - %base0 = arith.muli %qt0, %c132 : index - %at0 = arith.addi %base0, %l4 : index - vector.store %st#2, %part[%hi, %wi, %at0] : memref, vector<4xf32> - %am0 = arith.addi %base0, %c128 : index - %as0 = arith.addi %base0, %c129 : index - scf.if %lane0 { - memref.store %st#0, %part[%hi, %wi, %am0] : memref - memref.store %st#1, %part[%hi, %wi, %as0] : memref - } - %base1 = arith.muli %qt1, %c132 : index - %at1 = arith.addi %base1, %l4 : index - vector.store %st#5, %part[%hi, %wi, %at1] : memref, vector<4xf32> - %am1 = arith.addi %base1, %c128 : index - %as1 = arith.addi %base1, %c129 : index - scf.if %lane0 { - memref.store %st#3, %part[%hi, %wi, %am1] : memref - memref.store %st#4, %part[%hi, %wi, %as1] : memref - } - %base2 = arith.muli %qt2, %c132 : index - %at2 = arith.addi %base2, %l4 : index - vector.store %st#8, %part[%hi, %wi, %at2] : memref, vector<4xf32> - %am2 = arith.addi %base2, %c128 : index - %as2 = arith.addi %base2, %c129 : index - scf.if %lane0 { - memref.store %st#6, %part[%hi, %wi, %am2] : memref - memref.store %st#7, %part[%hi, %wi, %as2] : memref } - %base3 = arith.muli %qt3, %c132 : index - %at3 = arith.addi %base3, %l4 : index - vector.store %st#11, %part[%hi, %wi, %at3] : memref, vector<4xf32> - %am3 = arith.addi %base3, %c128 : index - %as3 = arith.addi %base3, %c129 : index - scf.if %lane0 { - memref.store %st#9, %part[%hi, %wi, %am3] : memref - memref.store %st#10, %part[%hi, %wi, %as3] : memref + for l in 0..2 across lanes(32) { + part[h][w][132 * (t0 + 0) + 128 + l] = stats[s][0][l]; + part[h][w][132 * (t0 + 1) + 128 + l] = stats[s][1][l]; + part[h][w][132 * (t0 + 2) + 128 + l] = stats[s][2][l]; + part[h][w][132 * (t0 + 3) + 128 + l] = stats[s][3][l]; } - macro.yield %h : i32 - }; + } } } } @@ -830,268 +811,268 @@ fn round_attention_parts_5(part : &mut Tensor, q : 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, %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])]) { - %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 - %c132 = arith.constant 132 : 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 - %t0i = arith.index_cast %t0 : 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> - %scv = vector.broadcast %scale : f32 to vector<4xf32> - %ct0 = arith.constant 0 : index - %pos0 = arith.addi %posi, %ct0 : index - %n0 = arith.addi %pos0, %c32 : index - %chunks0 = arith.divui %n0, %c32 : index - %qt0 = arith.addi %t0i, %ct0 : index - %qv0 = vector.load %q[%qt0, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs0 = arith.mulf %qv0, %scv : vector<4xf32> - %ct1 = arith.constant 1 : index - %pos1 = arith.addi %posi, %ct1 : index - %n1 = arith.addi %pos1, %c32 : index - %chunks1 = arith.divui %n1, %c32 : index - %qt1 = arith.addi %t0i, %ct1 : index - %qv1 = vector.load %q[%qt1, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs1 = arith.mulf %qv1, %scv : vector<4xf32> - %ct2 = arith.constant 2 : index - %pos2 = arith.addi %posi, %ct2 : index - %n2 = arith.addi %pos2, %c32 : index - %chunks2 = arith.divui %n2, %c32 : index - %qt2 = arith.addi %t0i, %ct2 : index - %qv2 = vector.load %q[%qt2, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs2 = arith.mulf %qv2, %scv : vector<4xf32> - %ct3 = arith.constant 3 : index - %pos3 = arith.addi %posi, %ct3 : index - %n3 = arith.addi %pos3, %c32 : index - %chunks3 = arith.divui %n3, %c32 : index - %qt3 = arith.addi %t0i, %ct3 : index - %qv3 = vector.load %q[%qt3, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs3 = arith.mulf %qv3, %scv : vector<4xf32> - %ct4 = arith.constant 4 : index - %pos4 = arith.addi %posi, %ct4 : index - %n4 = arith.addi %pos4, %c32 : index - %chunks4 = arith.divui %n4, %c32 : index - %qt4 = arith.addi %t0i, %ct4 : index - %qv4 = vector.load %q[%qt4, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs4 = arith.mulf %qv4, %scv : vector<4xf32> - %st:15 = scf.for %ic = %wi to %chunks4 step %nwgi iter_args(%M0 = %neg, %S0 = %zero, %o0 = %vz4, %M1 = %neg, %S1 = %zero, %o1 = %vz4, %M2 = %neg, %S2 = %zero, %o2 = %vz4, %M3 = %neg, %S3 = %zero, %o3 = %vz4, %M4 = %neg, %S4 = %zero, %o4 = %vz4) -> (f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>) { - %r0 = arith.muli %ic, %c32 : index - %my:5 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%m0 = %neg, %m1 = %neg, %m2 = %neg, %m3 = %neg, %m4 = %neg) -> (f32, f32, f32, f32, f32) { - %row = arith.addi %r0, %cc : index - %rowc = arith.minui %row, %pos4 : index - %kh = vector.load %k[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> - %kf = arith.extf %kh : vector<4xf16> to vector<4xf32> - %mine = arith.cmpi eq, %cc, %l : index - %pr0 = arith.mulf %kf, %qs0 : vector<4xf32> - %pl0 = vector.reduction , %pr0 : vector<4xf32> into f32 - %sc0 = gpu.subgroup_reduce add %pl0 : (f32) -> f32 - %live0 = arith.cmpi ule, %row, %pos0 : index - %scm0 = arith.select %live0, %sc0, %neg : f32 - %mm0 = arith.select %mine, %scm0, %m0 : f32 - %pr1 = arith.mulf %kf, %qs1 : vector<4xf32> - %pl1 = vector.reduction , %pr1 : vector<4xf32> into f32 - %sc1 = gpu.subgroup_reduce add %pl1 : (f32) -> f32 - %live1 = arith.cmpi ule, %row, %pos1 : index - %scm1 = arith.select %live1, %sc1, %neg : f32 - %mm1 = arith.select %mine, %scm1, %m1 : f32 - %pr2 = arith.mulf %kf, %qs2 : vector<4xf32> - %pl2 = vector.reduction , %pr2 : vector<4xf32> into f32 - %sc2 = gpu.subgroup_reduce add %pl2 : (f32) -> f32 - %live2 = arith.cmpi ule, %row, %pos2 : index - %scm2 = arith.select %live2, %sc2, %neg : f32 - %mm2 = arith.select %mine, %scm2, %m2 : f32 - %pr3 = arith.mulf %kf, %qs3 : vector<4xf32> - %pl3 = vector.reduction , %pr3 : vector<4xf32> into f32 - %sc3 = gpu.subgroup_reduce add %pl3 : (f32) -> f32 - %live3 = arith.cmpi ule, %row, %pos3 : index - %scm3 = arith.select %live3, %sc3, %neg : f32 - %mm3 = arith.select %mine, %scm3, %m3 : f32 - %pr4 = arith.mulf %kf, %qs4 : vector<4xf32> - %pl4 = vector.reduction , %pr4 : vector<4xf32> into f32 - %sc4 = gpu.subgroup_reduce add %pl4 : (f32) -> f32 - %live4 = arith.cmpi ule, %row, %pos4 : index - %scm4 = arith.select %live4, %sc4, %neg : f32 - %mm4 = arith.select %mine, %scm4, %m4 : f32 - scf.yield %mm0, %mm1, %mm2, %mm3, %mm4 : f32, f32, f32, f32, f32 - } - %act0 = arith.cmpi ult, %ic, %chunks0 : index - %u0:4 = scf.if %act0 -> (f32, f32, vector<4xf32>, f32) { - %bm0 = gpu.subgroup_reduce maxnumf %my#0 : (f32) -> f32 - %Mn0 = arith.maxnumf %M0, %bm0 : f32 - %dm0 = arith.subf %M0, %Mn0 : f32 - %ms0 = math.exp %dm0 : f32 - %dp0 = arith.subf %my#0, %Mn0 : f32 - %p0 = math.exp %dp0 : f32 - %bs0 = gpu.subgroup_reduce add %p0 : (f32) -> f32 - %Ss0 = arith.mulf %S0, %ms0 : f32 - %Sn0 = arith.addf %Ss0, %bs0 : f32 - %msv0 = vector.broadcast %ms0 : f32 to vector<4xf32> - %ox0 = arith.mulf %o0, %msv0 : vector<4xf32> - scf.yield %Mn0, %Sn0, %ox0, %p0 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M0, %S0, %o0, %zero : f32, f32, vector<4xf32>, f32 - } - %act1 = arith.cmpi ult, %ic, %chunks1 : index - %u1:4 = scf.if %act1 -> (f32, f32, vector<4xf32>, f32) { - %bm1 = gpu.subgroup_reduce maxnumf %my#1 : (f32) -> f32 - %Mn1 = arith.maxnumf %M1, %bm1 : f32 - %dm1 = arith.subf %M1, %Mn1 : f32 - %ms1 = math.exp %dm1 : f32 - %dp1 = arith.subf %my#1, %Mn1 : f32 - %p1 = math.exp %dp1 : f32 - %bs1 = gpu.subgroup_reduce add %p1 : (f32) -> f32 - %Ss1 = arith.mulf %S1, %ms1 : f32 - %Sn1 = arith.addf %Ss1, %bs1 : f32 - %msv1 = vector.broadcast %ms1 : f32 to vector<4xf32> - %ox1 = arith.mulf %o1, %msv1 : vector<4xf32> - scf.yield %Mn1, %Sn1, %ox1, %p1 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M1, %S1, %o1, %zero : f32, f32, vector<4xf32>, f32 - } - %act2 = arith.cmpi ult, %ic, %chunks2 : index - %u2:4 = scf.if %act2 -> (f32, f32, vector<4xf32>, f32) { - %bm2 = gpu.subgroup_reduce maxnumf %my#2 : (f32) -> f32 - %Mn2 = arith.maxnumf %M2, %bm2 : f32 - %dm2 = arith.subf %M2, %Mn2 : f32 - %ms2 = math.exp %dm2 : f32 - %dp2 = arith.subf %my#2, %Mn2 : f32 - %p2 = math.exp %dp2 : f32 - %bs2 = gpu.subgroup_reduce add %p2 : (f32) -> f32 - %Ss2 = arith.mulf %S2, %ms2 : f32 - %Sn2 = arith.addf %Ss2, %bs2 : f32 - %msv2 = vector.broadcast %ms2 : f32 to vector<4xf32> - %ox2 = arith.mulf %o2, %msv2 : vector<4xf32> - scf.yield %Mn2, %Sn2, %ox2, %p2 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M2, %S2, %o2, %zero : f32, f32, vector<4xf32>, f32 - } - %act3 = arith.cmpi ult, %ic, %chunks3 : index - %u3:4 = scf.if %act3 -> (f32, f32, vector<4xf32>, f32) { - %bm3 = gpu.subgroup_reduce maxnumf %my#3 : (f32) -> f32 - %Mn3 = arith.maxnumf %M3, %bm3 : f32 - %dm3 = arith.subf %M3, %Mn3 : f32 - %ms3 = math.exp %dm3 : f32 - %dp3 = arith.subf %my#3, %Mn3 : f32 - %p3 = math.exp %dp3 : f32 - %bs3 = gpu.subgroup_reduce add %p3 : (f32) -> f32 - %Ss3 = arith.mulf %S3, %ms3 : f32 - %Sn3 = arith.addf %Ss3, %bs3 : f32 - %msv3 = vector.broadcast %ms3 : f32 to vector<4xf32> - %ox3 = arith.mulf %o3, %msv3 : vector<4xf32> - scf.yield %Mn3, %Sn3, %ox3, %p3 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M3, %S3, %o3, %zero : f32, f32, vector<4xf32>, f32 - } - %act4 = arith.cmpi ult, %ic, %chunks4 : index - %u4:4 = scf.if %act4 -> (f32, f32, vector<4xf32>, f32) { - %bm4 = gpu.subgroup_reduce maxnumf %my#4 : (f32) -> f32 - %Mn4 = arith.maxnumf %M4, %bm4 : f32 - %dm4 = arith.subf %M4, %Mn4 : f32 - %ms4 = math.exp %dm4 : f32 - %dp4 = arith.subf %my#4, %Mn4 : f32 - %p4 = math.exp %dp4 : f32 - %bs4 = gpu.subgroup_reduce add %p4 : (f32) -> f32 - %Ss4 = arith.mulf %S4, %ms4 : f32 - %Sn4 = arith.addf %Ss4, %bs4 : f32 - %msv4 = vector.broadcast %ms4 : f32 to vector<4xf32> - %ox4 = arith.mulf %o4, %msv4 : vector<4xf32> - scf.yield %Mn4, %Sn4, %ox4, %p4 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M4, %S4, %o4, %zero : f32, f32, vector<4xf32>, f32 + 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 = 4 * l; + let last = pos + 4; + let q0_0 = q[t0 + 0][h][d + 0] * scale; + let q0_1 = q[t0 + 0][h][d + 1] * scale; + let q0_2 = q[t0 + 0][h][d + 2] * scale; + let q0_3 = q[t0 + 0][h][d + 3] * scale; + let mut big0 : f32 = -3.0e38; + let mut total0 : f32 = 0.0; + let mut o0_0 : f32 = 0.0; + let mut o0_1 : f32 = 0.0; + let mut o0_2 : f32 = 0.0; + let mut o0_3 : f32 = 0.0; + let q1_0 = q[t0 + 1][h][d + 0] * scale; + let q1_1 = q[t0 + 1][h][d + 1] * scale; + let q1_2 = q[t0 + 1][h][d + 2] * scale; + let q1_3 = q[t0 + 1][h][d + 3] * scale; + let mut big1 : f32 = -3.0e38; + let mut total1 : f32 = 0.0; + let mut o1_0 : f32 = 0.0; + let mut o1_1 : f32 = 0.0; + let mut o1_2 : f32 = 0.0; + let mut o1_3 : f32 = 0.0; + let q2_0 = q[t0 + 2][h][d + 0] * scale; + let q2_1 = q[t0 + 2][h][d + 1] * scale; + let q2_2 = q[t0 + 2][h][d + 2] * scale; + let q2_3 = q[t0 + 2][h][d + 3] * scale; + let mut big2 : f32 = -3.0e38; + let mut total2 : f32 = 0.0; + let mut o2_0 : f32 = 0.0; + let mut o2_1 : f32 = 0.0; + let mut o2_2 : f32 = 0.0; + let mut o2_3 : f32 = 0.0; + let q3_0 = q[t0 + 3][h][d + 0] * scale; + let q3_1 = q[t0 + 3][h][d + 1] * scale; + let q3_2 = q[t0 + 3][h][d + 2] * scale; + let q3_3 = q[t0 + 3][h][d + 3] * scale; + let mut big3 : f32 = -3.0e38; + let mut total3 : f32 = 0.0; + let mut o3_0 : f32 = 0.0; + let mut o3_1 : f32 = 0.0; + let mut o3_2 : f32 = 0.0; + let mut o3_3 : f32 = 0.0; + let q4_0 = q[t0 + 4][h][d + 0] * scale; + let q4_1 = q[t0 + 4][h][d + 1] * scale; + let q4_2 = q[t0 + 4][h][d + 2] * scale; + let q4_3 = q[t0 + 4][h][d + 3] * scale; + let mut big4 : f32 = -3.0e38; + let mut total4 : f32 = 0.0; + let mut o4_0 : f32 = 0.0; + let mut o4_1 : f32 = 0.0; + let mut o4_2 : f32 = 0.0; + let mut o4_3 : f32 = 0.0; + let chunks = (last + 32) / 32; + let mut c = w; + while c < chunks { + let r0 = c * 32; + let mut mine0 : f32 = -3.0e38; + let mut mine1 : f32 = -3.0e38; + let mut mine2 : f32 = -3.0e38; + let mut mine3 : f32 = -3.0e38; + let mut mine4 : f32 = -3.0e38; + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > last { + kept = last; + } + let k0 = half_at(k_cache, kept, g, d, 0); + let k1 = half_at(k_cache, kept, g, d, 1); + let k2 = half_at(k_cache, kept, g, d, 2); + let k3 = half_at(k_cache, kept, g, d, 3); + let mut score0 = lane_sum(k0 * q0_0 + k1 * q0_1 + k2 * q0_2 + k3 * q0_3); + if row > pos + 0 { + score0 = -3.0e38; + } + let mut score1 = lane_sum(k0 * q1_0 + k1 * q1_1 + k2 * q1_2 + k3 * q1_3); + if row > pos + 1 { + score1 = -3.0e38; + } + let mut score2 = lane_sum(k0 * q2_0 + k1 * q2_1 + k2 * q2_2 + k3 * q2_3); + if row > pos + 2 { + score2 = -3.0e38; + } + let mut score3 = lane_sum(k0 * q3_0 + k1 * q3_1 + k2 * q3_2 + k3 * q3_3); + if row > pos + 3 { + score3 = -3.0e38; + } + let mut score4 = lane_sum(k0 * q4_0 + k1 * q4_1 + k2 * q4_2 + k3 * q4_3); + if row > pos + 4 { + score4 = -3.0e38; + } + if r == l { + mine0 = score0; + mine1 = score1; + mine2 = score2; + mine3 = score3; + mine4 = score4; + } + } + let mut p0 : f32 = 0.0; + if c < (pos + 0 + 32) / 32 { + let top = big0.max(lane_max(mine0)); + let shrink = (big0 - top).fast_exp(); + p0 = (mine0 - top).fast_exp(); + total0 = total0 * shrink + lane_sum(p0); + o0_0 = o0_0 * shrink; + o0_1 = o0_1 * shrink; + o0_2 = o0_2 * shrink; + o0_3 = o0_3 * shrink; + big0 = top; + } + let mut p1 : f32 = 0.0; + if c < (pos + 1 + 32) / 32 { + let top = big1.max(lane_max(mine1)); + let shrink = (big1 - top).fast_exp(); + p1 = (mine1 - top).fast_exp(); + total1 = total1 * shrink + lane_sum(p1); + o1_0 = o1_0 * shrink; + o1_1 = o1_1 * shrink; + o1_2 = o1_2 * shrink; + o1_3 = o1_3 * shrink; + big1 = top; + } + let mut p2 : f32 = 0.0; + if c < (pos + 2 + 32) / 32 { + let top = big2.max(lane_max(mine2)); + let shrink = (big2 - top).fast_exp(); + p2 = (mine2 - top).fast_exp(); + total2 = total2 * shrink + lane_sum(p2); + o2_0 = o2_0 * shrink; + o2_1 = o2_1 * shrink; + o2_2 = o2_2 * shrink; + o2_3 = o2_3 * shrink; + big2 = top; + } + let mut p3 : f32 = 0.0; + if c < (pos + 3 + 32) / 32 { + let top = big3.max(lane_max(mine3)); + let shrink = (big3 - top).fast_exp(); + p3 = (mine3 - top).fast_exp(); + total3 = total3 * shrink + lane_sum(p3); + o3_0 = o3_0 * shrink; + o3_1 = o3_1 * shrink; + o3_2 = o3_2 * shrink; + o3_3 = o3_3 * shrink; + big3 = top; + } + let mut p4 : f32 = 0.0; + if c < (pos + 4 + 32) / 32 { + let top = big4.max(lane_max(mine4)); + let shrink = (big4 - top).fast_exp(); + p4 = (mine4 - top).fast_exp(); + total4 = total4 * shrink + lane_sum(p4); + o4_0 = o4_0 * shrink; + o4_1 = o4_1 * shrink; + o4_2 = o4_2 * shrink; + o4_3 = o4_3 * shrink; + big4 = top; + } + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > last { + kept = last; + } + let pr0 = lane_value(p0, r); + o0_0 = fused(half_at(v_cache, kept, g, d, 0), pr0, o0_0); + o0_1 = fused(half_at(v_cache, kept, g, d, 1), pr0, o0_1); + o0_2 = fused(half_at(v_cache, kept, g, d, 2), pr0, o0_2); + o0_3 = fused(half_at(v_cache, kept, g, d, 3), pr0, o0_3); + let pr1 = lane_value(p1, r); + o1_0 = fused(half_at(v_cache, kept, g, d, 0), pr1, o1_0); + o1_1 = fused(half_at(v_cache, kept, g, d, 1), pr1, o1_1); + o1_2 = fused(half_at(v_cache, kept, g, d, 2), pr1, o1_2); + o1_3 = fused(half_at(v_cache, kept, g, d, 3), pr1, o1_3); + let pr2 = lane_value(p2, r); + o2_0 = fused(half_at(v_cache, kept, g, d, 0), pr2, o2_0); + o2_1 = fused(half_at(v_cache, kept, g, d, 1), pr2, o2_1); + o2_2 = fused(half_at(v_cache, kept, g, d, 2), pr2, o2_2); + o2_3 = fused(half_at(v_cache, kept, g, d, 3), pr2, o2_3); + let pr3 = lane_value(p3, r); + o3_0 = fused(half_at(v_cache, kept, g, d, 0), pr3, o3_0); + o3_1 = fused(half_at(v_cache, kept, g, d, 1), pr3, o3_1); + o3_2 = fused(half_at(v_cache, kept, g, d, 2), pr3, o3_2); + o3_3 = fused(half_at(v_cache, kept, g, d, 3), pr3, o3_3); + let pr4 = lane_value(p4, r); + o4_0 = fused(half_at(v_cache, kept, g, d, 0), pr4, o4_0); + o4_1 = fused(half_at(v_cache, kept, g, d, 1), pr4, o4_1); + o4_2 = fused(half_at(v_cache, kept, g, d, 2), pr4, o4_2); + o4_3 = fused(half_at(v_cache, kept, g, d, 3), pr4, o4_3); + } + c = c + nwg; } - %ov:5 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%oa0 = %u0#2, %oa1 = %u1#2, %oa2 = %u2#2, %oa3 = %u3#2, %oa4 = %u4#2) -> (vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>) { - %row = arith.addi %r0, %cc : index - %rowc = arith.minui %row, %pos4 : 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 - %pc0, %pv0 = gpu.shuffle idx %u0#3, %cci, %c32i : f32 - %pcv0 = vector.broadcast %pc0 : f32 to vector<4xf32> - %on0 = vector.fma %vf, %pcv0, %oa0 : vector<4xf32> - %pc1, %pv1 = gpu.shuffle idx %u1#3, %cci, %c32i : f32 - %pcv1 = vector.broadcast %pc1 : f32 to vector<4xf32> - %on1 = vector.fma %vf, %pcv1, %oa1 : vector<4xf32> - %pc2, %pv2 = gpu.shuffle idx %u2#3, %cci, %c32i : f32 - %pcv2 = vector.broadcast %pc2 : f32 to vector<4xf32> - %on2 = vector.fma %vf, %pcv2, %oa2 : vector<4xf32> - %pc3, %pv3 = gpu.shuffle idx %u3#3, %cci, %c32i : f32 - %pcv3 = vector.broadcast %pc3 : f32 to vector<4xf32> - %on3 = vector.fma %vf, %pcv3, %oa3 : vector<4xf32> - %pc4, %pv4 = gpu.shuffle idx %u4#3, %cci, %c32i : f32 - %pcv4 = vector.broadcast %pc4 : f32 to vector<4xf32> - %on4 = vector.fma %vf, %pcv4, %oa4 : vector<4xf32> - scf.yield %on0, %on1, %on2, %on3, %on4 : vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32> + let b0 = 132 * (t0 + 0); + part[h][w][b0 + d + 0] = o0_0; + part[h][w][b0 + d + 1] = o0_1; + part[h][w][b0 + d + 2] = o0_2; + part[h][w][b0 + d + 3] = o0_3; + let b1 = 132 * (t0 + 1); + part[h][w][b1 + d + 0] = o1_0; + part[h][w][b1 + d + 1] = o1_1; + part[h][w][b1 + d + 2] = o1_2; + part[h][w][b1 + d + 3] = o1_3; + let b2 = 132 * (t0 + 2); + part[h][w][b2 + d + 0] = o2_0; + part[h][w][b2 + d + 1] = o2_1; + part[h][w][b2 + d + 2] = o2_2; + part[h][w][b2 + d + 3] = o2_3; + let b3 = 132 * (t0 + 3); + part[h][w][b3 + d + 0] = o3_0; + part[h][w][b3 + d + 1] = o3_1; + part[h][w][b3 + d + 2] = o3_2; + part[h][w][b3 + d + 3] = o3_3; + let b4 = 132 * (t0 + 4); + part[h][w][b4 + d + 0] = o4_0; + part[h][w][b4 + d + 1] = o4_1; + part[h][w][b4 + d + 2] = o4_2; + part[h][w][b4 + d + 3] = o4_3; + // Every lane has the same largest score and sum of the weights of a query. Lanes 0 and 1 keep them + // for the next loop. + if l < 2 { + let mut x0 = big0; + if l == 1 { + x0 = total0; + } + stats[s][0][l] = x0; + let mut x1 = big1; + if l == 1 { + x1 = total1; + } + stats[s][1][l] = x1; + let mut x2 = big2; + if l == 1 { + x2 = total2; + } + stats[s][2][l] = x2; + let mut x3 = big3; + if l == 1 { + x3 = total3; + } + stats[s][3][l] = x3; + let mut x4 = big4; + if l == 1 { + x4 = total4; + } + stats[s][4][l] = x4; } - scf.yield %u0#0, %u0#1, %ov#0, %u1#0, %u1#1, %ov#1, %u2#0, %u2#1, %ov#2, %u3#0, %u3#1, %ov#3, %u4#0, %u4#1, %ov#4 : f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32> - } - %lane0 = arith.cmpi eq, %l, %c0 : index - %base0 = arith.muli %qt0, %c132 : index - %at0 = arith.addi %base0, %l4 : index - vector.store %st#2, %part[%hi, %wi, %at0] : memref, vector<4xf32> - %am0 = arith.addi %base0, %c128 : index - %as0 = arith.addi %base0, %c129 : index - scf.if %lane0 { - memref.store %st#0, %part[%hi, %wi, %am0] : memref - memref.store %st#1, %part[%hi, %wi, %as0] : memref - } - %base1 = arith.muli %qt1, %c132 : index - %at1 = arith.addi %base1, %l4 : index - vector.store %st#5, %part[%hi, %wi, %at1] : memref, vector<4xf32> - %am1 = arith.addi %base1, %c128 : index - %as1 = arith.addi %base1, %c129 : index - scf.if %lane0 { - memref.store %st#3, %part[%hi, %wi, %am1] : memref - memref.store %st#4, %part[%hi, %wi, %as1] : memref - } - %base2 = arith.muli %qt2, %c132 : index - %at2 = arith.addi %base2, %l4 : index - vector.store %st#8, %part[%hi, %wi, %at2] : memref, vector<4xf32> - %am2 = arith.addi %base2, %c128 : index - %as2 = arith.addi %base2, %c129 : index - scf.if %lane0 { - memref.store %st#6, %part[%hi, %wi, %am2] : memref - memref.store %st#7, %part[%hi, %wi, %as2] : memref - } - %base3 = arith.muli %qt3, %c132 : index - %at3 = arith.addi %base3, %l4 : index - vector.store %st#11, %part[%hi, %wi, %at3] : memref, vector<4xf32> - %am3 = arith.addi %base3, %c128 : index - %as3 = arith.addi %base3, %c129 : index - scf.if %lane0 { - memref.store %st#9, %part[%hi, %wi, %am3] : memref - memref.store %st#10, %part[%hi, %wi, %as3] : memref } - %base4 = arith.muli %qt4, %c132 : index - %at4 = arith.addi %base4, %l4 : index - vector.store %st#14, %part[%hi, %wi, %at4] : memref, vector<4xf32> - %am4 = arith.addi %base4, %c128 : index - %as4 = arith.addi %base4, %c129 : index - scf.if %lane0 { - memref.store %st#12, %part[%hi, %wi, %am4] : memref - memref.store %st#13, %part[%hi, %wi, %as4] : memref + for l in 0..2 across lanes(32) { + part[h][w][132 * (t0 + 0) + 128 + l] = stats[s][0][l]; + part[h][w][132 * (t0 + 1) + 128 + l] = stats[s][1][l]; + part[h][w][132 * (t0 + 2) + 128 + l] = stats[s][2][l]; + part[h][w][132 * (t0 + 3) + 128 + l] = stats[s][3][l]; + part[h][w][132 * (t0 + 4) + 128 + l] = stats[s][4][l]; } - macro.yield %h : i32 - }; + } } } } @@ -1104,310 +1085,312 @@ fn round_attention_parts_6(part : &mut Tensor, q : 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, %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])]) { - %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 - %c132 = arith.constant 132 : 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 - %t0i = arith.index_cast %t0 : 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> - %scv = vector.broadcast %scale : f32 to vector<4xf32> - %ct0 = arith.constant 0 : index - %pos0 = arith.addi %posi, %ct0 : index - %n0 = arith.addi %pos0, %c32 : index - %chunks0 = arith.divui %n0, %c32 : index - %qt0 = arith.addi %t0i, %ct0 : index - %qv0 = vector.load %q[%qt0, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs0 = arith.mulf %qv0, %scv : vector<4xf32> - %ct1 = arith.constant 1 : index - %pos1 = arith.addi %posi, %ct1 : index - %n1 = arith.addi %pos1, %c32 : index - %chunks1 = arith.divui %n1, %c32 : index - %qt1 = arith.addi %t0i, %ct1 : index - %qv1 = vector.load %q[%qt1, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs1 = arith.mulf %qv1, %scv : vector<4xf32> - %ct2 = arith.constant 2 : index - %pos2 = arith.addi %posi, %ct2 : index - %n2 = arith.addi %pos2, %c32 : index - %chunks2 = arith.divui %n2, %c32 : index - %qt2 = arith.addi %t0i, %ct2 : index - %qv2 = vector.load %q[%qt2, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs2 = arith.mulf %qv2, %scv : vector<4xf32> - %ct3 = arith.constant 3 : index - %pos3 = arith.addi %posi, %ct3 : index - %n3 = arith.addi %pos3, %c32 : index - %chunks3 = arith.divui %n3, %c32 : index - %qt3 = arith.addi %t0i, %ct3 : index - %qv3 = vector.load %q[%qt3, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs3 = arith.mulf %qv3, %scv : vector<4xf32> - %ct4 = arith.constant 4 : index - %pos4 = arith.addi %posi, %ct4 : index - %n4 = arith.addi %pos4, %c32 : index - %chunks4 = arith.divui %n4, %c32 : index - %qt4 = arith.addi %t0i, %ct4 : index - %qv4 = vector.load %q[%qt4, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs4 = arith.mulf %qv4, %scv : vector<4xf32> - %ct5 = arith.constant 5 : index - %pos5 = arith.addi %posi, %ct5 : index - %n5 = arith.addi %pos5, %c32 : index - %chunks5 = arith.divui %n5, %c32 : index - %qt5 = arith.addi %t0i, %ct5 : index - %qv5 = vector.load %q[%qt5, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs5 = arith.mulf %qv5, %scv : vector<4xf32> - %st:18 = scf.for %ic = %wi to %chunks5 step %nwgi iter_args(%M0 = %neg, %S0 = %zero, %o0 = %vz4, %M1 = %neg, %S1 = %zero, %o1 = %vz4, %M2 = %neg, %S2 = %zero, %o2 = %vz4, %M3 = %neg, %S3 = %zero, %o3 = %vz4, %M4 = %neg, %S4 = %zero, %o4 = %vz4, %M5 = %neg, %S5 = %zero, %o5 = %vz4) -> (f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>) { - %r0 = arith.muli %ic, %c32 : index - %my:6 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%m0 = %neg, %m1 = %neg, %m2 = %neg, %m3 = %neg, %m4 = %neg, %m5 = %neg) -> (f32, f32, f32, f32, f32, f32) { - %row = arith.addi %r0, %cc : index - %rowc = arith.minui %row, %pos5 : index - %kh = vector.load %k[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> - %kf = arith.extf %kh : vector<4xf16> to vector<4xf32> - %mine = arith.cmpi eq, %cc, %l : index - %pr0 = arith.mulf %kf, %qs0 : vector<4xf32> - %pl0 = vector.reduction , %pr0 : vector<4xf32> into f32 - %sc0 = gpu.subgroup_reduce add %pl0 : (f32) -> f32 - %live0 = arith.cmpi ule, %row, %pos0 : index - %scm0 = arith.select %live0, %sc0, %neg : f32 - %mm0 = arith.select %mine, %scm0, %m0 : f32 - %pr1 = arith.mulf %kf, %qs1 : vector<4xf32> - %pl1 = vector.reduction , %pr1 : vector<4xf32> into f32 - %sc1 = gpu.subgroup_reduce add %pl1 : (f32) -> f32 - %live1 = arith.cmpi ule, %row, %pos1 : index - %scm1 = arith.select %live1, %sc1, %neg : f32 - %mm1 = arith.select %mine, %scm1, %m1 : f32 - %pr2 = arith.mulf %kf, %qs2 : vector<4xf32> - %pl2 = vector.reduction , %pr2 : vector<4xf32> into f32 - %sc2 = gpu.subgroup_reduce add %pl2 : (f32) -> f32 - %live2 = arith.cmpi ule, %row, %pos2 : index - %scm2 = arith.select %live2, %sc2, %neg : f32 - %mm2 = arith.select %mine, %scm2, %m2 : f32 - %pr3 = arith.mulf %kf, %qs3 : vector<4xf32> - %pl3 = vector.reduction , %pr3 : vector<4xf32> into f32 - %sc3 = gpu.subgroup_reduce add %pl3 : (f32) -> f32 - %live3 = arith.cmpi ule, %row, %pos3 : index - %scm3 = arith.select %live3, %sc3, %neg : f32 - %mm3 = arith.select %mine, %scm3, %m3 : f32 - %pr4 = arith.mulf %kf, %qs4 : vector<4xf32> - %pl4 = vector.reduction , %pr4 : vector<4xf32> into f32 - %sc4 = gpu.subgroup_reduce add %pl4 : (f32) -> f32 - %live4 = arith.cmpi ule, %row, %pos4 : index - %scm4 = arith.select %live4, %sc4, %neg : f32 - %mm4 = arith.select %mine, %scm4, %m4 : f32 - %pr5 = arith.mulf %kf, %qs5 : vector<4xf32> - %pl5 = vector.reduction , %pr5 : vector<4xf32> into f32 - %sc5 = gpu.subgroup_reduce add %pl5 : (f32) -> f32 - %live5 = arith.cmpi ule, %row, %pos5 : index - %scm5 = arith.select %live5, %sc5, %neg : f32 - %mm5 = arith.select %mine, %scm5, %m5 : f32 - scf.yield %mm0, %mm1, %mm2, %mm3, %mm4, %mm5 : f32, f32, f32, f32, f32, f32 - } - %act0 = arith.cmpi ult, %ic, %chunks0 : index - %u0:4 = scf.if %act0 -> (f32, f32, vector<4xf32>, f32) { - %bm0 = gpu.subgroup_reduce maxnumf %my#0 : (f32) -> f32 - %Mn0 = arith.maxnumf %M0, %bm0 : f32 - %dm0 = arith.subf %M0, %Mn0 : f32 - %ms0 = math.exp %dm0 : f32 - %dp0 = arith.subf %my#0, %Mn0 : f32 - %p0 = math.exp %dp0 : f32 - %bs0 = gpu.subgroup_reduce add %p0 : (f32) -> f32 - %Ss0 = arith.mulf %S0, %ms0 : f32 - %Sn0 = arith.addf %Ss0, %bs0 : f32 - %msv0 = vector.broadcast %ms0 : f32 to vector<4xf32> - %ox0 = arith.mulf %o0, %msv0 : vector<4xf32> - scf.yield %Mn0, %Sn0, %ox0, %p0 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M0, %S0, %o0, %zero : f32, f32, vector<4xf32>, f32 - } - %act1 = arith.cmpi ult, %ic, %chunks1 : index - %u1:4 = scf.if %act1 -> (f32, f32, vector<4xf32>, f32) { - %bm1 = gpu.subgroup_reduce maxnumf %my#1 : (f32) -> f32 - %Mn1 = arith.maxnumf %M1, %bm1 : f32 - %dm1 = arith.subf %M1, %Mn1 : f32 - %ms1 = math.exp %dm1 : f32 - %dp1 = arith.subf %my#1, %Mn1 : f32 - %p1 = math.exp %dp1 : f32 - %bs1 = gpu.subgroup_reduce add %p1 : (f32) -> f32 - %Ss1 = arith.mulf %S1, %ms1 : f32 - %Sn1 = arith.addf %Ss1, %bs1 : f32 - %msv1 = vector.broadcast %ms1 : f32 to vector<4xf32> - %ox1 = arith.mulf %o1, %msv1 : vector<4xf32> - scf.yield %Mn1, %Sn1, %ox1, %p1 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M1, %S1, %o1, %zero : f32, f32, vector<4xf32>, f32 - } - %act2 = arith.cmpi ult, %ic, %chunks2 : index - %u2:4 = scf.if %act2 -> (f32, f32, vector<4xf32>, f32) { - %bm2 = gpu.subgroup_reduce maxnumf %my#2 : (f32) -> f32 - %Mn2 = arith.maxnumf %M2, %bm2 : f32 - %dm2 = arith.subf %M2, %Mn2 : f32 - %ms2 = math.exp %dm2 : f32 - %dp2 = arith.subf %my#2, %Mn2 : f32 - %p2 = math.exp %dp2 : f32 - %bs2 = gpu.subgroup_reduce add %p2 : (f32) -> f32 - %Ss2 = arith.mulf %S2, %ms2 : f32 - %Sn2 = arith.addf %Ss2, %bs2 : f32 - %msv2 = vector.broadcast %ms2 : f32 to vector<4xf32> - %ox2 = arith.mulf %o2, %msv2 : vector<4xf32> - scf.yield %Mn2, %Sn2, %ox2, %p2 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M2, %S2, %o2, %zero : f32, f32, vector<4xf32>, f32 - } - %act3 = arith.cmpi ult, %ic, %chunks3 : index - %u3:4 = scf.if %act3 -> (f32, f32, vector<4xf32>, f32) { - %bm3 = gpu.subgroup_reduce maxnumf %my#3 : (f32) -> f32 - %Mn3 = arith.maxnumf %M3, %bm3 : f32 - %dm3 = arith.subf %M3, %Mn3 : f32 - %ms3 = math.exp %dm3 : f32 - %dp3 = arith.subf %my#3, %Mn3 : f32 - %p3 = math.exp %dp3 : f32 - %bs3 = gpu.subgroup_reduce add %p3 : (f32) -> f32 - %Ss3 = arith.mulf %S3, %ms3 : f32 - %Sn3 = arith.addf %Ss3, %bs3 : f32 - %msv3 = vector.broadcast %ms3 : f32 to vector<4xf32> - %ox3 = arith.mulf %o3, %msv3 : vector<4xf32> - scf.yield %Mn3, %Sn3, %ox3, %p3 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M3, %S3, %o3, %zero : f32, f32, vector<4xf32>, f32 - } - %act4 = arith.cmpi ult, %ic, %chunks4 : index - %u4:4 = scf.if %act4 -> (f32, f32, vector<4xf32>, f32) { - %bm4 = gpu.subgroup_reduce maxnumf %my#4 : (f32) -> f32 - %Mn4 = arith.maxnumf %M4, %bm4 : f32 - %dm4 = arith.subf %M4, %Mn4 : f32 - %ms4 = math.exp %dm4 : f32 - %dp4 = arith.subf %my#4, %Mn4 : f32 - %p4 = math.exp %dp4 : f32 - %bs4 = gpu.subgroup_reduce add %p4 : (f32) -> f32 - %Ss4 = arith.mulf %S4, %ms4 : f32 - %Sn4 = arith.addf %Ss4, %bs4 : f32 - %msv4 = vector.broadcast %ms4 : f32 to vector<4xf32> - %ox4 = arith.mulf %o4, %msv4 : vector<4xf32> - scf.yield %Mn4, %Sn4, %ox4, %p4 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M4, %S4, %o4, %zero : f32, f32, vector<4xf32>, f32 - } - %act5 = arith.cmpi ult, %ic, %chunks5 : index - %u5:4 = scf.if %act5 -> (f32, f32, vector<4xf32>, f32) { - %bm5 = gpu.subgroup_reduce maxnumf %my#5 : (f32) -> f32 - %Mn5 = arith.maxnumf %M5, %bm5 : f32 - %dm5 = arith.subf %M5, %Mn5 : f32 - %ms5 = math.exp %dm5 : f32 - %dp5 = arith.subf %my#5, %Mn5 : f32 - %p5 = math.exp %dp5 : f32 - %bs5 = gpu.subgroup_reduce add %p5 : (f32) -> f32 - %Ss5 = arith.mulf %S5, %ms5 : f32 - %Sn5 = arith.addf %Ss5, %bs5 : f32 - %msv5 = vector.broadcast %ms5 : f32 to vector<4xf32> - %ox5 = arith.mulf %o5, %msv5 : vector<4xf32> - scf.yield %Mn5, %Sn5, %ox5, %p5 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M5, %S5, %o5, %zero : f32, f32, vector<4xf32>, f32 + 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 = 4 * l; + let last = pos + 5; + let q0_0 = q[t0 + 0][h][d + 0] * scale; + let q0_1 = q[t0 + 0][h][d + 1] * scale; + let q0_2 = q[t0 + 0][h][d + 2] * scale; + let q0_3 = q[t0 + 0][h][d + 3] * scale; + let mut big0 : f32 = -3.0e38; + let mut total0 : f32 = 0.0; + let mut o0_0 : f32 = 0.0; + let mut o0_1 : f32 = 0.0; + let mut o0_2 : f32 = 0.0; + let mut o0_3 : f32 = 0.0; + let q1_0 = q[t0 + 1][h][d + 0] * scale; + let q1_1 = q[t0 + 1][h][d + 1] * scale; + let q1_2 = q[t0 + 1][h][d + 2] * scale; + let q1_3 = q[t0 + 1][h][d + 3] * scale; + let mut big1 : f32 = -3.0e38; + let mut total1 : f32 = 0.0; + let mut o1_0 : f32 = 0.0; + let mut o1_1 : f32 = 0.0; + let mut o1_2 : f32 = 0.0; + let mut o1_3 : f32 = 0.0; + let q2_0 = q[t0 + 2][h][d + 0] * scale; + let q2_1 = q[t0 + 2][h][d + 1] * scale; + let q2_2 = q[t0 + 2][h][d + 2] * scale; + let q2_3 = q[t0 + 2][h][d + 3] * scale; + let mut big2 : f32 = -3.0e38; + let mut total2 : f32 = 0.0; + let mut o2_0 : f32 = 0.0; + let mut o2_1 : f32 = 0.0; + let mut o2_2 : f32 = 0.0; + let mut o2_3 : f32 = 0.0; + let q3_0 = q[t0 + 3][h][d + 0] * scale; + let q3_1 = q[t0 + 3][h][d + 1] * scale; + let q3_2 = q[t0 + 3][h][d + 2] * scale; + let q3_3 = q[t0 + 3][h][d + 3] * scale; + let mut big3 : f32 = -3.0e38; + let mut total3 : f32 = 0.0; + let mut o3_0 : f32 = 0.0; + let mut o3_1 : f32 = 0.0; + let mut o3_2 : f32 = 0.0; + let mut o3_3 : f32 = 0.0; + let q4_0 = q[t0 + 4][h][d + 0] * scale; + let q4_1 = q[t0 + 4][h][d + 1] * scale; + let q4_2 = q[t0 + 4][h][d + 2] * scale; + let q4_3 = q[t0 + 4][h][d + 3] * scale; + let mut big4 : f32 = -3.0e38; + let mut total4 : f32 = 0.0; + let mut o4_0 : f32 = 0.0; + let mut o4_1 : f32 = 0.0; + let mut o4_2 : f32 = 0.0; + let mut o4_3 : f32 = 0.0; + let q5_0 = q[t0 + 5][h][d + 0] * scale; + let q5_1 = q[t0 + 5][h][d + 1] * scale; + let q5_2 = q[t0 + 5][h][d + 2] * scale; + let q5_3 = q[t0 + 5][h][d + 3] * scale; + let mut big5 : f32 = -3.0e38; + let mut total5 : f32 = 0.0; + let mut o5_0 : f32 = 0.0; + let mut o5_1 : f32 = 0.0; + let mut o5_2 : f32 = 0.0; + let mut o5_3 : f32 = 0.0; + let chunks = (last + 32) / 32; + let mut c = w; + while c < chunks { + let r0 = c * 32; + let mut mine0 : f32 = -3.0e38; + let mut mine1 : f32 = -3.0e38; + let mut mine2 : f32 = -3.0e38; + let mut mine3 : f32 = -3.0e38; + let mut mine4 : f32 = -3.0e38; + let mut mine5 : f32 = -3.0e38; + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > last { + kept = last; + } + let k0 = half_at(k_cache, kept, g, d, 0); + let k1 = half_at(k_cache, kept, g, d, 1); + let k2 = half_at(k_cache, kept, g, d, 2); + let k3 = half_at(k_cache, kept, g, d, 3); + let mut score0 = lane_sum(k0 * q0_0 + k1 * q0_1 + k2 * q0_2 + k3 * q0_3); + if row > pos + 0 { + score0 = -3.0e38; + } + let mut score1 = lane_sum(k0 * q1_0 + k1 * q1_1 + k2 * q1_2 + k3 * q1_3); + if row > pos + 1 { + score1 = -3.0e38; + } + let mut score2 = lane_sum(k0 * q2_0 + k1 * q2_1 + k2 * q2_2 + k3 * q2_3); + if row > pos + 2 { + score2 = -3.0e38; + } + let mut score3 = lane_sum(k0 * q3_0 + k1 * q3_1 + k2 * q3_2 + k3 * q3_3); + if row > pos + 3 { + score3 = -3.0e38; + } + let mut score4 = lane_sum(k0 * q4_0 + k1 * q4_1 + k2 * q4_2 + k3 * q4_3); + if row > pos + 4 { + score4 = -3.0e38; + } + let mut score5 = lane_sum(k0 * q5_0 + k1 * q5_1 + k2 * q5_2 + k3 * q5_3); + if row > pos + 5 { + score5 = -3.0e38; + } + if r == l { + mine0 = score0; + mine1 = score1; + mine2 = score2; + mine3 = score3; + mine4 = score4; + mine5 = score5; + } + } + let mut p0 : f32 = 0.0; + if c < (pos + 0 + 32) / 32 { + let top = big0.max(lane_max(mine0)); + let shrink = (big0 - top).fast_exp(); + p0 = (mine0 - top).fast_exp(); + total0 = total0 * shrink + lane_sum(p0); + o0_0 = o0_0 * shrink; + o0_1 = o0_1 * shrink; + o0_2 = o0_2 * shrink; + o0_3 = o0_3 * shrink; + big0 = top; + } + let mut p1 : f32 = 0.0; + if c < (pos + 1 + 32) / 32 { + let top = big1.max(lane_max(mine1)); + let shrink = (big1 - top).fast_exp(); + p1 = (mine1 - top).fast_exp(); + total1 = total1 * shrink + lane_sum(p1); + o1_0 = o1_0 * shrink; + o1_1 = o1_1 * shrink; + o1_2 = o1_2 * shrink; + o1_3 = o1_3 * shrink; + big1 = top; + } + let mut p2 : f32 = 0.0; + if c < (pos + 2 + 32) / 32 { + let top = big2.max(lane_max(mine2)); + let shrink = (big2 - top).fast_exp(); + p2 = (mine2 - top).fast_exp(); + total2 = total2 * shrink + lane_sum(p2); + o2_0 = o2_0 * shrink; + o2_1 = o2_1 * shrink; + o2_2 = o2_2 * shrink; + o2_3 = o2_3 * shrink; + big2 = top; + } + let mut p3 : f32 = 0.0; + if c < (pos + 3 + 32) / 32 { + let top = big3.max(lane_max(mine3)); + let shrink = (big3 - top).fast_exp(); + p3 = (mine3 - top).fast_exp(); + total3 = total3 * shrink + lane_sum(p3); + o3_0 = o3_0 * shrink; + o3_1 = o3_1 * shrink; + o3_2 = o3_2 * shrink; + o3_3 = o3_3 * shrink; + big3 = top; + } + let mut p4 : f32 = 0.0; + if c < (pos + 4 + 32) / 32 { + let top = big4.max(lane_max(mine4)); + let shrink = (big4 - top).fast_exp(); + p4 = (mine4 - top).fast_exp(); + total4 = total4 * shrink + lane_sum(p4); + o4_0 = o4_0 * shrink; + o4_1 = o4_1 * shrink; + o4_2 = o4_2 * shrink; + o4_3 = o4_3 * shrink; + big4 = top; + } + let mut p5 : f32 = 0.0; + if c < (pos + 5 + 32) / 32 { + let top = big5.max(lane_max(mine5)); + let shrink = (big5 - top).fast_exp(); + p5 = (mine5 - top).fast_exp(); + total5 = total5 * shrink + lane_sum(p5); + o5_0 = o5_0 * shrink; + o5_1 = o5_1 * shrink; + o5_2 = o5_2 * shrink; + o5_3 = o5_3 * shrink; + big5 = top; + } + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > last { + kept = last; + } + let pr0 = lane_value(p0, r); + o0_0 = fused(half_at(v_cache, kept, g, d, 0), pr0, o0_0); + o0_1 = fused(half_at(v_cache, kept, g, d, 1), pr0, o0_1); + o0_2 = fused(half_at(v_cache, kept, g, d, 2), pr0, o0_2); + o0_3 = fused(half_at(v_cache, kept, g, d, 3), pr0, o0_3); + let pr1 = lane_value(p1, r); + o1_0 = fused(half_at(v_cache, kept, g, d, 0), pr1, o1_0); + o1_1 = fused(half_at(v_cache, kept, g, d, 1), pr1, o1_1); + o1_2 = fused(half_at(v_cache, kept, g, d, 2), pr1, o1_2); + o1_3 = fused(half_at(v_cache, kept, g, d, 3), pr1, o1_3); + let pr2 = lane_value(p2, r); + o2_0 = fused(half_at(v_cache, kept, g, d, 0), pr2, o2_0); + o2_1 = fused(half_at(v_cache, kept, g, d, 1), pr2, o2_1); + o2_2 = fused(half_at(v_cache, kept, g, d, 2), pr2, o2_2); + o2_3 = fused(half_at(v_cache, kept, g, d, 3), pr2, o2_3); + let pr3 = lane_value(p3, r); + o3_0 = fused(half_at(v_cache, kept, g, d, 0), pr3, o3_0); + o3_1 = fused(half_at(v_cache, kept, g, d, 1), pr3, o3_1); + o3_2 = fused(half_at(v_cache, kept, g, d, 2), pr3, o3_2); + o3_3 = fused(half_at(v_cache, kept, g, d, 3), pr3, o3_3); + let pr4 = lane_value(p4, r); + o4_0 = fused(half_at(v_cache, kept, g, d, 0), pr4, o4_0); + o4_1 = fused(half_at(v_cache, kept, g, d, 1), pr4, o4_1); + o4_2 = fused(half_at(v_cache, kept, g, d, 2), pr4, o4_2); + o4_3 = fused(half_at(v_cache, kept, g, d, 3), pr4, o4_3); + let pr5 = lane_value(p5, r); + o5_0 = fused(half_at(v_cache, kept, g, d, 0), pr5, o5_0); + o5_1 = fused(half_at(v_cache, kept, g, d, 1), pr5, o5_1); + o5_2 = fused(half_at(v_cache, kept, g, d, 2), pr5, o5_2); + o5_3 = fused(half_at(v_cache, kept, g, d, 3), pr5, o5_3); + } + c = c + nwg; } - %ov:6 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%oa0 = %u0#2, %oa1 = %u1#2, %oa2 = %u2#2, %oa3 = %u3#2, %oa4 = %u4#2, %oa5 = %u5#2) -> (vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>) { - %row = arith.addi %r0, %cc : index - %rowc = arith.minui %row, %pos5 : 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 - %pc0, %pv0 = gpu.shuffle idx %u0#3, %cci, %c32i : f32 - %pcv0 = vector.broadcast %pc0 : f32 to vector<4xf32> - %on0 = vector.fma %vf, %pcv0, %oa0 : vector<4xf32> - %pc1, %pv1 = gpu.shuffle idx %u1#3, %cci, %c32i : f32 - %pcv1 = vector.broadcast %pc1 : f32 to vector<4xf32> - %on1 = vector.fma %vf, %pcv1, %oa1 : vector<4xf32> - %pc2, %pv2 = gpu.shuffle idx %u2#3, %cci, %c32i : f32 - %pcv2 = vector.broadcast %pc2 : f32 to vector<4xf32> - %on2 = vector.fma %vf, %pcv2, %oa2 : vector<4xf32> - %pc3, %pv3 = gpu.shuffle idx %u3#3, %cci, %c32i : f32 - %pcv3 = vector.broadcast %pc3 : f32 to vector<4xf32> - %on3 = vector.fma %vf, %pcv3, %oa3 : vector<4xf32> - %pc4, %pv4 = gpu.shuffle idx %u4#3, %cci, %c32i : f32 - %pcv4 = vector.broadcast %pc4 : f32 to vector<4xf32> - %on4 = vector.fma %vf, %pcv4, %oa4 : vector<4xf32> - %pc5, %pv5 = gpu.shuffle idx %u5#3, %cci, %c32i : f32 - %pcv5 = vector.broadcast %pc5 : f32 to vector<4xf32> - %on5 = vector.fma %vf, %pcv5, %oa5 : vector<4xf32> - scf.yield %on0, %on1, %on2, %on3, %on4, %on5 : vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32> + let b0 = 132 * (t0 + 0); + part[h][w][b0 + d + 0] = o0_0; + part[h][w][b0 + d + 1] = o0_1; + part[h][w][b0 + d + 2] = o0_2; + part[h][w][b0 + d + 3] = o0_3; + let b1 = 132 * (t0 + 1); + part[h][w][b1 + d + 0] = o1_0; + part[h][w][b1 + d + 1] = o1_1; + part[h][w][b1 + d + 2] = o1_2; + part[h][w][b1 + d + 3] = o1_3; + let b2 = 132 * (t0 + 2); + part[h][w][b2 + d + 0] = o2_0; + part[h][w][b2 + d + 1] = o2_1; + part[h][w][b2 + d + 2] = o2_2; + part[h][w][b2 + d + 3] = o2_3; + let b3 = 132 * (t0 + 3); + part[h][w][b3 + d + 0] = o3_0; + part[h][w][b3 + d + 1] = o3_1; + part[h][w][b3 + d + 2] = o3_2; + part[h][w][b3 + d + 3] = o3_3; + let b4 = 132 * (t0 + 4); + part[h][w][b4 + d + 0] = o4_0; + part[h][w][b4 + d + 1] = o4_1; + part[h][w][b4 + d + 2] = o4_2; + part[h][w][b4 + d + 3] = o4_3; + let b5 = 132 * (t0 + 5); + part[h][w][b5 + d + 0] = o5_0; + part[h][w][b5 + d + 1] = o5_1; + part[h][w][b5 + d + 2] = o5_2; + part[h][w][b5 + d + 3] = o5_3; + // Every lane has the same largest score and sum of the weights of a query. Lanes 0 and 1 keep them + // for the next loop. + if l < 2 { + let mut x0 = big0; + if l == 1 { + x0 = total0; + } + stats[s][0][l] = x0; + let mut x1 = big1; + if l == 1 { + x1 = total1; + } + stats[s][1][l] = x1; + let mut x2 = big2; + if l == 1 { + x2 = total2; + } + stats[s][2][l] = x2; + let mut x3 = big3; + if l == 1 { + x3 = total3; + } + stats[s][3][l] = x3; + let mut x4 = big4; + if l == 1 { + x4 = total4; + } + stats[s][4][l] = x4; + let mut x5 = big5; + if l == 1 { + x5 = total5; + } + stats[s][5][l] = x5; } - scf.yield %u0#0, %u0#1, %ov#0, %u1#0, %u1#1, %ov#1, %u2#0, %u2#1, %ov#2, %u3#0, %u3#1, %ov#3, %u4#0, %u4#1, %ov#4, %u5#0, %u5#1, %ov#5 : f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32> - } - %lane0 = arith.cmpi eq, %l, %c0 : index - %base0 = arith.muli %qt0, %c132 : index - %at0 = arith.addi %base0, %l4 : index - vector.store %st#2, %part[%hi, %wi, %at0] : memref, vector<4xf32> - %am0 = arith.addi %base0, %c128 : index - %as0 = arith.addi %base0, %c129 : index - scf.if %lane0 { - memref.store %st#0, %part[%hi, %wi, %am0] : memref - memref.store %st#1, %part[%hi, %wi, %as0] : memref - } - %base1 = arith.muli %qt1, %c132 : index - %at1 = arith.addi %base1, %l4 : index - vector.store %st#5, %part[%hi, %wi, %at1] : memref, vector<4xf32> - %am1 = arith.addi %base1, %c128 : index - %as1 = arith.addi %base1, %c129 : index - scf.if %lane0 { - memref.store %st#3, %part[%hi, %wi, %am1] : memref - memref.store %st#4, %part[%hi, %wi, %as1] : memref - } - %base2 = arith.muli %qt2, %c132 : index - %at2 = arith.addi %base2, %l4 : index - vector.store %st#8, %part[%hi, %wi, %at2] : memref, vector<4xf32> - %am2 = arith.addi %base2, %c128 : index - %as2 = arith.addi %base2, %c129 : index - scf.if %lane0 { - memref.store %st#6, %part[%hi, %wi, %am2] : memref - memref.store %st#7, %part[%hi, %wi, %as2] : memref - } - %base3 = arith.muli %qt3, %c132 : index - %at3 = arith.addi %base3, %l4 : index - vector.store %st#11, %part[%hi, %wi, %at3] : memref, vector<4xf32> - %am3 = arith.addi %base3, %c128 : index - %as3 = arith.addi %base3, %c129 : index - scf.if %lane0 { - memref.store %st#9, %part[%hi, %wi, %am3] : memref - memref.store %st#10, %part[%hi, %wi, %as3] : memref - } - %base4 = arith.muli %qt4, %c132 : index - %at4 = arith.addi %base4, %l4 : index - vector.store %st#14, %part[%hi, %wi, %at4] : memref, vector<4xf32> - %am4 = arith.addi %base4, %c128 : index - %as4 = arith.addi %base4, %c129 : index - scf.if %lane0 { - memref.store %st#12, %part[%hi, %wi, %am4] : memref - memref.store %st#13, %part[%hi, %wi, %as4] : memref } - %base5 = arith.muli %qt5, %c132 : index - %at5 = arith.addi %base5, %l4 : index - vector.store %st#17, %part[%hi, %wi, %at5] : memref, vector<4xf32> - %am5 = arith.addi %base5, %c128 : index - %as5 = arith.addi %base5, %c129 : index - scf.if %lane0 { - memref.store %st#15, %part[%hi, %wi, %am5] : memref - memref.store %st#16, %part[%hi, %wi, %as5] : memref + for l in 0..2 across lanes(32) { + part[h][w][132 * (t0 + 0) + 128 + l] = stats[s][0][l]; + part[h][w][132 * (t0 + 1) + 128 + l] = stats[s][1][l]; + part[h][w][132 * (t0 + 2) + 128 + l] = stats[s][2][l]; + part[h][w][132 * (t0 + 3) + 128 + l] = stats[s][3][l]; + part[h][w][132 * (t0 + 4) + 128 + l] = stats[s][4][l]; + part[h][w][132 * (t0 + 5) + 128 + l] = stats[s][5][l]; } - macro.yield %h : i32 - }; + } } } } @@ -1420,352 +1403,356 @@ fn round_attention_parts_7(part : &mut Tensor, q : 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, %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])]) { - %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 - %c132 = arith.constant 132 : 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 - %t0i = arith.index_cast %t0 : 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> - %scv = vector.broadcast %scale : f32 to vector<4xf32> - %ct0 = arith.constant 0 : index - %pos0 = arith.addi %posi, %ct0 : index - %n0 = arith.addi %pos0, %c32 : index - %chunks0 = arith.divui %n0, %c32 : index - %qt0 = arith.addi %t0i, %ct0 : index - %qv0 = vector.load %q[%qt0, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs0 = arith.mulf %qv0, %scv : vector<4xf32> - %ct1 = arith.constant 1 : index - %pos1 = arith.addi %posi, %ct1 : index - %n1 = arith.addi %pos1, %c32 : index - %chunks1 = arith.divui %n1, %c32 : index - %qt1 = arith.addi %t0i, %ct1 : index - %qv1 = vector.load %q[%qt1, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs1 = arith.mulf %qv1, %scv : vector<4xf32> - %ct2 = arith.constant 2 : index - %pos2 = arith.addi %posi, %ct2 : index - %n2 = arith.addi %pos2, %c32 : index - %chunks2 = arith.divui %n2, %c32 : index - %qt2 = arith.addi %t0i, %ct2 : index - %qv2 = vector.load %q[%qt2, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs2 = arith.mulf %qv2, %scv : vector<4xf32> - %ct3 = arith.constant 3 : index - %pos3 = arith.addi %posi, %ct3 : index - %n3 = arith.addi %pos3, %c32 : index - %chunks3 = arith.divui %n3, %c32 : index - %qt3 = arith.addi %t0i, %ct3 : index - %qv3 = vector.load %q[%qt3, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs3 = arith.mulf %qv3, %scv : vector<4xf32> - %ct4 = arith.constant 4 : index - %pos4 = arith.addi %posi, %ct4 : index - %n4 = arith.addi %pos4, %c32 : index - %chunks4 = arith.divui %n4, %c32 : index - %qt4 = arith.addi %t0i, %ct4 : index - %qv4 = vector.load %q[%qt4, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs4 = arith.mulf %qv4, %scv : vector<4xf32> - %ct5 = arith.constant 5 : index - %pos5 = arith.addi %posi, %ct5 : index - %n5 = arith.addi %pos5, %c32 : index - %chunks5 = arith.divui %n5, %c32 : index - %qt5 = arith.addi %t0i, %ct5 : index - %qv5 = vector.load %q[%qt5, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs5 = arith.mulf %qv5, %scv : vector<4xf32> - %ct6 = arith.constant 6 : index - %pos6 = arith.addi %posi, %ct6 : index - %n6 = arith.addi %pos6, %c32 : index - %chunks6 = arith.divui %n6, %c32 : index - %qt6 = arith.addi %t0i, %ct6 : index - %qv6 = vector.load %q[%qt6, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs6 = arith.mulf %qv6, %scv : vector<4xf32> - %st:21 = scf.for %ic = %wi to %chunks6 step %nwgi iter_args(%M0 = %neg, %S0 = %zero, %o0 = %vz4, %M1 = %neg, %S1 = %zero, %o1 = %vz4, %M2 = %neg, %S2 = %zero, %o2 = %vz4, %M3 = %neg, %S3 = %zero, %o3 = %vz4, %M4 = %neg, %S4 = %zero, %o4 = %vz4, %M5 = %neg, %S5 = %zero, %o5 = %vz4, %M6 = %neg, %S6 = %zero, %o6 = %vz4) -> (f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>) { - %r0 = arith.muli %ic, %c32 : index - %my:7 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%m0 = %neg, %m1 = %neg, %m2 = %neg, %m3 = %neg, %m4 = %neg, %m5 = %neg, %m6 = %neg) -> (f32, f32, f32, f32, f32, f32, f32) { - %row = arith.addi %r0, %cc : index - %rowc = arith.minui %row, %pos6 : index - %kh = vector.load %k[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> - %kf = arith.extf %kh : vector<4xf16> to vector<4xf32> - %mine = arith.cmpi eq, %cc, %l : index - %pr0 = arith.mulf %kf, %qs0 : vector<4xf32> - %pl0 = vector.reduction , %pr0 : vector<4xf32> into f32 - %sc0 = gpu.subgroup_reduce add %pl0 : (f32) -> f32 - %live0 = arith.cmpi ule, %row, %pos0 : index - %scm0 = arith.select %live0, %sc0, %neg : f32 - %mm0 = arith.select %mine, %scm0, %m0 : f32 - %pr1 = arith.mulf %kf, %qs1 : vector<4xf32> - %pl1 = vector.reduction , %pr1 : vector<4xf32> into f32 - %sc1 = gpu.subgroup_reduce add %pl1 : (f32) -> f32 - %live1 = arith.cmpi ule, %row, %pos1 : index - %scm1 = arith.select %live1, %sc1, %neg : f32 - %mm1 = arith.select %mine, %scm1, %m1 : f32 - %pr2 = arith.mulf %kf, %qs2 : vector<4xf32> - %pl2 = vector.reduction , %pr2 : vector<4xf32> into f32 - %sc2 = gpu.subgroup_reduce add %pl2 : (f32) -> f32 - %live2 = arith.cmpi ule, %row, %pos2 : index - %scm2 = arith.select %live2, %sc2, %neg : f32 - %mm2 = arith.select %mine, %scm2, %m2 : f32 - %pr3 = arith.mulf %kf, %qs3 : vector<4xf32> - %pl3 = vector.reduction , %pr3 : vector<4xf32> into f32 - %sc3 = gpu.subgroup_reduce add %pl3 : (f32) -> f32 - %live3 = arith.cmpi ule, %row, %pos3 : index - %scm3 = arith.select %live3, %sc3, %neg : f32 - %mm3 = arith.select %mine, %scm3, %m3 : f32 - %pr4 = arith.mulf %kf, %qs4 : vector<4xf32> - %pl4 = vector.reduction , %pr4 : vector<4xf32> into f32 - %sc4 = gpu.subgroup_reduce add %pl4 : (f32) -> f32 - %live4 = arith.cmpi ule, %row, %pos4 : index - %scm4 = arith.select %live4, %sc4, %neg : f32 - %mm4 = arith.select %mine, %scm4, %m4 : f32 - %pr5 = arith.mulf %kf, %qs5 : vector<4xf32> - %pl5 = vector.reduction , %pr5 : vector<4xf32> into f32 - %sc5 = gpu.subgroup_reduce add %pl5 : (f32) -> f32 - %live5 = arith.cmpi ule, %row, %pos5 : index - %scm5 = arith.select %live5, %sc5, %neg : f32 - %mm5 = arith.select %mine, %scm5, %m5 : f32 - %pr6 = arith.mulf %kf, %qs6 : vector<4xf32> - %pl6 = vector.reduction , %pr6 : vector<4xf32> into f32 - %sc6 = gpu.subgroup_reduce add %pl6 : (f32) -> f32 - %live6 = arith.cmpi ule, %row, %pos6 : index - %scm6 = arith.select %live6, %sc6, %neg : f32 - %mm6 = arith.select %mine, %scm6, %m6 : f32 - scf.yield %mm0, %mm1, %mm2, %mm3, %mm4, %mm5, %mm6 : f32, f32, f32, f32, f32, f32, f32 - } - %act0 = arith.cmpi ult, %ic, %chunks0 : index - %u0:4 = scf.if %act0 -> (f32, f32, vector<4xf32>, f32) { - %bm0 = gpu.subgroup_reduce maxnumf %my#0 : (f32) -> f32 - %Mn0 = arith.maxnumf %M0, %bm0 : f32 - %dm0 = arith.subf %M0, %Mn0 : f32 - %ms0 = math.exp %dm0 : f32 - %dp0 = arith.subf %my#0, %Mn0 : f32 - %p0 = math.exp %dp0 : f32 - %bs0 = gpu.subgroup_reduce add %p0 : (f32) -> f32 - %Ss0 = arith.mulf %S0, %ms0 : f32 - %Sn0 = arith.addf %Ss0, %bs0 : f32 - %msv0 = vector.broadcast %ms0 : f32 to vector<4xf32> - %ox0 = arith.mulf %o0, %msv0 : vector<4xf32> - scf.yield %Mn0, %Sn0, %ox0, %p0 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M0, %S0, %o0, %zero : f32, f32, vector<4xf32>, f32 - } - %act1 = arith.cmpi ult, %ic, %chunks1 : index - %u1:4 = scf.if %act1 -> (f32, f32, vector<4xf32>, f32) { - %bm1 = gpu.subgroup_reduce maxnumf %my#1 : (f32) -> f32 - %Mn1 = arith.maxnumf %M1, %bm1 : f32 - %dm1 = arith.subf %M1, %Mn1 : f32 - %ms1 = math.exp %dm1 : f32 - %dp1 = arith.subf %my#1, %Mn1 : f32 - %p1 = math.exp %dp1 : f32 - %bs1 = gpu.subgroup_reduce add %p1 : (f32) -> f32 - %Ss1 = arith.mulf %S1, %ms1 : f32 - %Sn1 = arith.addf %Ss1, %bs1 : f32 - %msv1 = vector.broadcast %ms1 : f32 to vector<4xf32> - %ox1 = arith.mulf %o1, %msv1 : vector<4xf32> - scf.yield %Mn1, %Sn1, %ox1, %p1 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M1, %S1, %o1, %zero : f32, f32, vector<4xf32>, f32 - } - %act2 = arith.cmpi ult, %ic, %chunks2 : index - %u2:4 = scf.if %act2 -> (f32, f32, vector<4xf32>, f32) { - %bm2 = gpu.subgroup_reduce maxnumf %my#2 : (f32) -> f32 - %Mn2 = arith.maxnumf %M2, %bm2 : f32 - %dm2 = arith.subf %M2, %Mn2 : f32 - %ms2 = math.exp %dm2 : f32 - %dp2 = arith.subf %my#2, %Mn2 : f32 - %p2 = math.exp %dp2 : f32 - %bs2 = gpu.subgroup_reduce add %p2 : (f32) -> f32 - %Ss2 = arith.mulf %S2, %ms2 : f32 - %Sn2 = arith.addf %Ss2, %bs2 : f32 - %msv2 = vector.broadcast %ms2 : f32 to vector<4xf32> - %ox2 = arith.mulf %o2, %msv2 : vector<4xf32> - scf.yield %Mn2, %Sn2, %ox2, %p2 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M2, %S2, %o2, %zero : f32, f32, vector<4xf32>, f32 - } - %act3 = arith.cmpi ult, %ic, %chunks3 : index - %u3:4 = scf.if %act3 -> (f32, f32, vector<4xf32>, f32) { - %bm3 = gpu.subgroup_reduce maxnumf %my#3 : (f32) -> f32 - %Mn3 = arith.maxnumf %M3, %bm3 : f32 - %dm3 = arith.subf %M3, %Mn3 : f32 - %ms3 = math.exp %dm3 : f32 - %dp3 = arith.subf %my#3, %Mn3 : f32 - %p3 = math.exp %dp3 : f32 - %bs3 = gpu.subgroup_reduce add %p3 : (f32) -> f32 - %Ss3 = arith.mulf %S3, %ms3 : f32 - %Sn3 = arith.addf %Ss3, %bs3 : f32 - %msv3 = vector.broadcast %ms3 : f32 to vector<4xf32> - %ox3 = arith.mulf %o3, %msv3 : vector<4xf32> - scf.yield %Mn3, %Sn3, %ox3, %p3 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M3, %S3, %o3, %zero : f32, f32, vector<4xf32>, f32 - } - %act4 = arith.cmpi ult, %ic, %chunks4 : index - %u4:4 = scf.if %act4 -> (f32, f32, vector<4xf32>, f32) { - %bm4 = gpu.subgroup_reduce maxnumf %my#4 : (f32) -> f32 - %Mn4 = arith.maxnumf %M4, %bm4 : f32 - %dm4 = arith.subf %M4, %Mn4 : f32 - %ms4 = math.exp %dm4 : f32 - %dp4 = arith.subf %my#4, %Mn4 : f32 - %p4 = math.exp %dp4 : f32 - %bs4 = gpu.subgroup_reduce add %p4 : (f32) -> f32 - %Ss4 = arith.mulf %S4, %ms4 : f32 - %Sn4 = arith.addf %Ss4, %bs4 : f32 - %msv4 = vector.broadcast %ms4 : f32 to vector<4xf32> - %ox4 = arith.mulf %o4, %msv4 : vector<4xf32> - scf.yield %Mn4, %Sn4, %ox4, %p4 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M4, %S4, %o4, %zero : f32, f32, vector<4xf32>, f32 - } - %act5 = arith.cmpi ult, %ic, %chunks5 : index - %u5:4 = scf.if %act5 -> (f32, f32, vector<4xf32>, f32) { - %bm5 = gpu.subgroup_reduce maxnumf %my#5 : (f32) -> f32 - %Mn5 = arith.maxnumf %M5, %bm5 : f32 - %dm5 = arith.subf %M5, %Mn5 : f32 - %ms5 = math.exp %dm5 : f32 - %dp5 = arith.subf %my#5, %Mn5 : f32 - %p5 = math.exp %dp5 : f32 - %bs5 = gpu.subgroup_reduce add %p5 : (f32) -> f32 - %Ss5 = arith.mulf %S5, %ms5 : f32 - %Sn5 = arith.addf %Ss5, %bs5 : f32 - %msv5 = vector.broadcast %ms5 : f32 to vector<4xf32> - %ox5 = arith.mulf %o5, %msv5 : vector<4xf32> - scf.yield %Mn5, %Sn5, %ox5, %p5 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M5, %S5, %o5, %zero : f32, f32, vector<4xf32>, f32 - } - %act6 = arith.cmpi ult, %ic, %chunks6 : index - %u6:4 = scf.if %act6 -> (f32, f32, vector<4xf32>, f32) { - %bm6 = gpu.subgroup_reduce maxnumf %my#6 : (f32) -> f32 - %Mn6 = arith.maxnumf %M6, %bm6 : f32 - %dm6 = arith.subf %M6, %Mn6 : f32 - %ms6 = math.exp %dm6 : f32 - %dp6 = arith.subf %my#6, %Mn6 : f32 - %p6 = math.exp %dp6 : f32 - %bs6 = gpu.subgroup_reduce add %p6 : (f32) -> f32 - %Ss6 = arith.mulf %S6, %ms6 : f32 - %Sn6 = arith.addf %Ss6, %bs6 : f32 - %msv6 = vector.broadcast %ms6 : f32 to vector<4xf32> - %ox6 = arith.mulf %o6, %msv6 : vector<4xf32> - scf.yield %Mn6, %Sn6, %ox6, %p6 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M6, %S6, %o6, %zero : f32, f32, vector<4xf32>, f32 + 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 = 4 * l; + let last = pos + 6; + let q0_0 = q[t0 + 0][h][d + 0] * scale; + let q0_1 = q[t0 + 0][h][d + 1] * scale; + let q0_2 = q[t0 + 0][h][d + 2] * scale; + let q0_3 = q[t0 + 0][h][d + 3] * scale; + let mut big0 : f32 = -3.0e38; + let mut total0 : f32 = 0.0; + let mut o0_0 : f32 = 0.0; + let mut o0_1 : f32 = 0.0; + let mut o0_2 : f32 = 0.0; + let mut o0_3 : f32 = 0.0; + let q1_0 = q[t0 + 1][h][d + 0] * scale; + let q1_1 = q[t0 + 1][h][d + 1] * scale; + let q1_2 = q[t0 + 1][h][d + 2] * scale; + let q1_3 = q[t0 + 1][h][d + 3] * scale; + let mut big1 : f32 = -3.0e38; + let mut total1 : f32 = 0.0; + let mut o1_0 : f32 = 0.0; + let mut o1_1 : f32 = 0.0; + let mut o1_2 : f32 = 0.0; + let mut o1_3 : f32 = 0.0; + let q2_0 = q[t0 + 2][h][d + 0] * scale; + let q2_1 = q[t0 + 2][h][d + 1] * scale; + let q2_2 = q[t0 + 2][h][d + 2] * scale; + let q2_3 = q[t0 + 2][h][d + 3] * scale; + let mut big2 : f32 = -3.0e38; + let mut total2 : f32 = 0.0; + let mut o2_0 : f32 = 0.0; + let mut o2_1 : f32 = 0.0; + let mut o2_2 : f32 = 0.0; + let mut o2_3 : f32 = 0.0; + let q3_0 = q[t0 + 3][h][d + 0] * scale; + let q3_1 = q[t0 + 3][h][d + 1] * scale; + let q3_2 = q[t0 + 3][h][d + 2] * scale; + let q3_3 = q[t0 + 3][h][d + 3] * scale; + let mut big3 : f32 = -3.0e38; + let mut total3 : f32 = 0.0; + let mut o3_0 : f32 = 0.0; + let mut o3_1 : f32 = 0.0; + let mut o3_2 : f32 = 0.0; + let mut o3_3 : f32 = 0.0; + let q4_0 = q[t0 + 4][h][d + 0] * scale; + let q4_1 = q[t0 + 4][h][d + 1] * scale; + let q4_2 = q[t0 + 4][h][d + 2] * scale; + let q4_3 = q[t0 + 4][h][d + 3] * scale; + let mut big4 : f32 = -3.0e38; + let mut total4 : f32 = 0.0; + let mut o4_0 : f32 = 0.0; + let mut o4_1 : f32 = 0.0; + let mut o4_2 : f32 = 0.0; + let mut o4_3 : f32 = 0.0; + let q5_0 = q[t0 + 5][h][d + 0] * scale; + let q5_1 = q[t0 + 5][h][d + 1] * scale; + let q5_2 = q[t0 + 5][h][d + 2] * scale; + let q5_3 = q[t0 + 5][h][d + 3] * scale; + let mut big5 : f32 = -3.0e38; + let mut total5 : f32 = 0.0; + let mut o5_0 : f32 = 0.0; + let mut o5_1 : f32 = 0.0; + let mut o5_2 : f32 = 0.0; + let mut o5_3 : f32 = 0.0; + let q6_0 = q[t0 + 6][h][d + 0] * scale; + let q6_1 = q[t0 + 6][h][d + 1] * scale; + let q6_2 = q[t0 + 6][h][d + 2] * scale; + let q6_3 = q[t0 + 6][h][d + 3] * scale; + let mut big6 : f32 = -3.0e38; + let mut total6 : f32 = 0.0; + let mut o6_0 : f32 = 0.0; + let mut o6_1 : f32 = 0.0; + let mut o6_2 : f32 = 0.0; + let mut o6_3 : f32 = 0.0; + let chunks = (last + 32) / 32; + let mut c = w; + while c < chunks { + let r0 = c * 32; + let mut mine0 : f32 = -3.0e38; + let mut mine1 : f32 = -3.0e38; + let mut mine2 : f32 = -3.0e38; + let mut mine3 : f32 = -3.0e38; + let mut mine4 : f32 = -3.0e38; + let mut mine5 : f32 = -3.0e38; + let mut mine6 : f32 = -3.0e38; + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > last { + kept = last; + } + let k0 = half_at(k_cache, kept, g, d, 0); + let k1 = half_at(k_cache, kept, g, d, 1); + let k2 = half_at(k_cache, kept, g, d, 2); + let k3 = half_at(k_cache, kept, g, d, 3); + let mut score0 = lane_sum(k0 * q0_0 + k1 * q0_1 + k2 * q0_2 + k3 * q0_3); + if row > pos + 0 { + score0 = -3.0e38; + } + let mut score1 = lane_sum(k0 * q1_0 + k1 * q1_1 + k2 * q1_2 + k3 * q1_3); + if row > pos + 1 { + score1 = -3.0e38; + } + let mut score2 = lane_sum(k0 * q2_0 + k1 * q2_1 + k2 * q2_2 + k3 * q2_3); + if row > pos + 2 { + score2 = -3.0e38; + } + let mut score3 = lane_sum(k0 * q3_0 + k1 * q3_1 + k2 * q3_2 + k3 * q3_3); + if row > pos + 3 { + score3 = -3.0e38; + } + let mut score4 = lane_sum(k0 * q4_0 + k1 * q4_1 + k2 * q4_2 + k3 * q4_3); + if row > pos + 4 { + score4 = -3.0e38; + } + let mut score5 = lane_sum(k0 * q5_0 + k1 * q5_1 + k2 * q5_2 + k3 * q5_3); + if row > pos + 5 { + score5 = -3.0e38; + } + let mut score6 = lane_sum(k0 * q6_0 + k1 * q6_1 + k2 * q6_2 + k3 * q6_3); + if row > pos + 6 { + score6 = -3.0e38; + } + if r == l { + mine0 = score0; + mine1 = score1; + mine2 = score2; + mine3 = score3; + mine4 = score4; + mine5 = score5; + mine6 = score6; + } + } + let mut p0 : f32 = 0.0; + if c < (pos + 0 + 32) / 32 { + let top = big0.max(lane_max(mine0)); + let shrink = (big0 - top).fast_exp(); + p0 = (mine0 - top).fast_exp(); + total0 = total0 * shrink + lane_sum(p0); + o0_0 = o0_0 * shrink; + o0_1 = o0_1 * shrink; + o0_2 = o0_2 * shrink; + o0_3 = o0_3 * shrink; + big0 = top; + } + let mut p1 : f32 = 0.0; + if c < (pos + 1 + 32) / 32 { + let top = big1.max(lane_max(mine1)); + let shrink = (big1 - top).fast_exp(); + p1 = (mine1 - top).fast_exp(); + total1 = total1 * shrink + lane_sum(p1); + o1_0 = o1_0 * shrink; + o1_1 = o1_1 * shrink; + o1_2 = o1_2 * shrink; + o1_3 = o1_3 * shrink; + big1 = top; + } + let mut p2 : f32 = 0.0; + if c < (pos + 2 + 32) / 32 { + let top = big2.max(lane_max(mine2)); + let shrink = (big2 - top).fast_exp(); + p2 = (mine2 - top).fast_exp(); + total2 = total2 * shrink + lane_sum(p2); + o2_0 = o2_0 * shrink; + o2_1 = o2_1 * shrink; + o2_2 = o2_2 * shrink; + o2_3 = o2_3 * shrink; + big2 = top; + } + let mut p3 : f32 = 0.0; + if c < (pos + 3 + 32) / 32 { + let top = big3.max(lane_max(mine3)); + let shrink = (big3 - top).fast_exp(); + p3 = (mine3 - top).fast_exp(); + total3 = total3 * shrink + lane_sum(p3); + o3_0 = o3_0 * shrink; + o3_1 = o3_1 * shrink; + o3_2 = o3_2 * shrink; + o3_3 = o3_3 * shrink; + big3 = top; + } + let mut p4 : f32 = 0.0; + if c < (pos + 4 + 32) / 32 { + let top = big4.max(lane_max(mine4)); + let shrink = (big4 - top).fast_exp(); + p4 = (mine4 - top).fast_exp(); + total4 = total4 * shrink + lane_sum(p4); + o4_0 = o4_0 * shrink; + o4_1 = o4_1 * shrink; + o4_2 = o4_2 * shrink; + o4_3 = o4_3 * shrink; + big4 = top; + } + let mut p5 : f32 = 0.0; + if c < (pos + 5 + 32) / 32 { + let top = big5.max(lane_max(mine5)); + let shrink = (big5 - top).fast_exp(); + p5 = (mine5 - top).fast_exp(); + total5 = total5 * shrink + lane_sum(p5); + o5_0 = o5_0 * shrink; + o5_1 = o5_1 * shrink; + o5_2 = o5_2 * shrink; + o5_3 = o5_3 * shrink; + big5 = top; + } + let mut p6 : f32 = 0.0; + if c < (pos + 6 + 32) / 32 { + let top = big6.max(lane_max(mine6)); + let shrink = (big6 - top).fast_exp(); + p6 = (mine6 - top).fast_exp(); + total6 = total6 * shrink + lane_sum(p6); + o6_0 = o6_0 * shrink; + o6_1 = o6_1 * shrink; + o6_2 = o6_2 * shrink; + o6_3 = o6_3 * shrink; + big6 = top; + } + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > last { + kept = last; + } + let pr0 = lane_value(p0, r); + o0_0 = fused(half_at(v_cache, kept, g, d, 0), pr0, o0_0); + o0_1 = fused(half_at(v_cache, kept, g, d, 1), pr0, o0_1); + o0_2 = fused(half_at(v_cache, kept, g, d, 2), pr0, o0_2); + o0_3 = fused(half_at(v_cache, kept, g, d, 3), pr0, o0_3); + let pr1 = lane_value(p1, r); + o1_0 = fused(half_at(v_cache, kept, g, d, 0), pr1, o1_0); + o1_1 = fused(half_at(v_cache, kept, g, d, 1), pr1, o1_1); + o1_2 = fused(half_at(v_cache, kept, g, d, 2), pr1, o1_2); + o1_3 = fused(half_at(v_cache, kept, g, d, 3), pr1, o1_3); + let pr2 = lane_value(p2, r); + o2_0 = fused(half_at(v_cache, kept, g, d, 0), pr2, o2_0); + o2_1 = fused(half_at(v_cache, kept, g, d, 1), pr2, o2_1); + o2_2 = fused(half_at(v_cache, kept, g, d, 2), pr2, o2_2); + o2_3 = fused(half_at(v_cache, kept, g, d, 3), pr2, o2_3); + let pr3 = lane_value(p3, r); + o3_0 = fused(half_at(v_cache, kept, g, d, 0), pr3, o3_0); + o3_1 = fused(half_at(v_cache, kept, g, d, 1), pr3, o3_1); + o3_2 = fused(half_at(v_cache, kept, g, d, 2), pr3, o3_2); + o3_3 = fused(half_at(v_cache, kept, g, d, 3), pr3, o3_3); + let pr4 = lane_value(p4, r); + o4_0 = fused(half_at(v_cache, kept, g, d, 0), pr4, o4_0); + o4_1 = fused(half_at(v_cache, kept, g, d, 1), pr4, o4_1); + o4_2 = fused(half_at(v_cache, kept, g, d, 2), pr4, o4_2); + o4_3 = fused(half_at(v_cache, kept, g, d, 3), pr4, o4_3); + let pr5 = lane_value(p5, r); + o5_0 = fused(half_at(v_cache, kept, g, d, 0), pr5, o5_0); + o5_1 = fused(half_at(v_cache, kept, g, d, 1), pr5, o5_1); + o5_2 = fused(half_at(v_cache, kept, g, d, 2), pr5, o5_2); + o5_3 = fused(half_at(v_cache, kept, g, d, 3), pr5, o5_3); + let pr6 = lane_value(p6, r); + o6_0 = fused(half_at(v_cache, kept, g, d, 0), pr6, o6_0); + o6_1 = fused(half_at(v_cache, kept, g, d, 1), pr6, o6_1); + o6_2 = fused(half_at(v_cache, kept, g, d, 2), pr6, o6_2); + o6_3 = fused(half_at(v_cache, kept, g, d, 3), pr6, o6_3); + } + c = c + nwg; } - %ov:7 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%oa0 = %u0#2, %oa1 = %u1#2, %oa2 = %u2#2, %oa3 = %u3#2, %oa4 = %u4#2, %oa5 = %u5#2, %oa6 = %u6#2) -> (vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>) { - %row = arith.addi %r0, %cc : index - %rowc = arith.minui %row, %pos6 : 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 - %pc0, %pv0 = gpu.shuffle idx %u0#3, %cci, %c32i : f32 - %pcv0 = vector.broadcast %pc0 : f32 to vector<4xf32> - %on0 = vector.fma %vf, %pcv0, %oa0 : vector<4xf32> - %pc1, %pv1 = gpu.shuffle idx %u1#3, %cci, %c32i : f32 - %pcv1 = vector.broadcast %pc1 : f32 to vector<4xf32> - %on1 = vector.fma %vf, %pcv1, %oa1 : vector<4xf32> - %pc2, %pv2 = gpu.shuffle idx %u2#3, %cci, %c32i : f32 - %pcv2 = vector.broadcast %pc2 : f32 to vector<4xf32> - %on2 = vector.fma %vf, %pcv2, %oa2 : vector<4xf32> - %pc3, %pv3 = gpu.shuffle idx %u3#3, %cci, %c32i : f32 - %pcv3 = vector.broadcast %pc3 : f32 to vector<4xf32> - %on3 = vector.fma %vf, %pcv3, %oa3 : vector<4xf32> - %pc4, %pv4 = gpu.shuffle idx %u4#3, %cci, %c32i : f32 - %pcv4 = vector.broadcast %pc4 : f32 to vector<4xf32> - %on4 = vector.fma %vf, %pcv4, %oa4 : vector<4xf32> - %pc5, %pv5 = gpu.shuffle idx %u5#3, %cci, %c32i : f32 - %pcv5 = vector.broadcast %pc5 : f32 to vector<4xf32> - %on5 = vector.fma %vf, %pcv5, %oa5 : vector<4xf32> - %pc6, %pv6 = gpu.shuffle idx %u6#3, %cci, %c32i : f32 - %pcv6 = vector.broadcast %pc6 : f32 to vector<4xf32> - %on6 = vector.fma %vf, %pcv6, %oa6 : vector<4xf32> - scf.yield %on0, %on1, %on2, %on3, %on4, %on5, %on6 : vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32> + let b0 = 132 * (t0 + 0); + part[h][w][b0 + d + 0] = o0_0; + part[h][w][b0 + d + 1] = o0_1; + part[h][w][b0 + d + 2] = o0_2; + part[h][w][b0 + d + 3] = o0_3; + let b1 = 132 * (t0 + 1); + part[h][w][b1 + d + 0] = o1_0; + part[h][w][b1 + d + 1] = o1_1; + part[h][w][b1 + d + 2] = o1_2; + part[h][w][b1 + d + 3] = o1_3; + let b2 = 132 * (t0 + 2); + part[h][w][b2 + d + 0] = o2_0; + part[h][w][b2 + d + 1] = o2_1; + part[h][w][b2 + d + 2] = o2_2; + part[h][w][b2 + d + 3] = o2_3; + let b3 = 132 * (t0 + 3); + part[h][w][b3 + d + 0] = o3_0; + part[h][w][b3 + d + 1] = o3_1; + part[h][w][b3 + d + 2] = o3_2; + part[h][w][b3 + d + 3] = o3_3; + let b4 = 132 * (t0 + 4); + part[h][w][b4 + d + 0] = o4_0; + part[h][w][b4 + d + 1] = o4_1; + part[h][w][b4 + d + 2] = o4_2; + part[h][w][b4 + d + 3] = o4_3; + let b5 = 132 * (t0 + 5); + part[h][w][b5 + d + 0] = o5_0; + part[h][w][b5 + d + 1] = o5_1; + part[h][w][b5 + d + 2] = o5_2; + part[h][w][b5 + d + 3] = o5_3; + let b6 = 132 * (t0 + 6); + part[h][w][b6 + d + 0] = o6_0; + part[h][w][b6 + d + 1] = o6_1; + part[h][w][b6 + d + 2] = o6_2; + part[h][w][b6 + d + 3] = o6_3; + // Every lane has the same largest score and sum of the weights of a query. Lanes 0 and 1 keep them + // for the next loop. + if l < 2 { + let mut x0 = big0; + if l == 1 { + x0 = total0; + } + stats[s][0][l] = x0; + let mut x1 = big1; + if l == 1 { + x1 = total1; + } + stats[s][1][l] = x1; + let mut x2 = big2; + if l == 1 { + x2 = total2; + } + stats[s][2][l] = x2; + let mut x3 = big3; + if l == 1 { + x3 = total3; + } + stats[s][3][l] = x3; + let mut x4 = big4; + if l == 1 { + x4 = total4; + } + stats[s][4][l] = x4; + let mut x5 = big5; + if l == 1 { + x5 = total5; + } + stats[s][5][l] = x5; + let mut x6 = big6; + if l == 1 { + x6 = total6; + } + stats[s][6][l] = x6; } - scf.yield %u0#0, %u0#1, %ov#0, %u1#0, %u1#1, %ov#1, %u2#0, %u2#1, %ov#2, %u3#0, %u3#1, %ov#3, %u4#0, %u4#1, %ov#4, %u5#0, %u5#1, %ov#5, %u6#0, %u6#1, %ov#6 : f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32> - } - %lane0 = arith.cmpi eq, %l, %c0 : index - %base0 = arith.muli %qt0, %c132 : index - %at0 = arith.addi %base0, %l4 : index - vector.store %st#2, %part[%hi, %wi, %at0] : memref, vector<4xf32> - %am0 = arith.addi %base0, %c128 : index - %as0 = arith.addi %base0, %c129 : index - scf.if %lane0 { - memref.store %st#0, %part[%hi, %wi, %am0] : memref - memref.store %st#1, %part[%hi, %wi, %as0] : memref - } - %base1 = arith.muli %qt1, %c132 : index - %at1 = arith.addi %base1, %l4 : index - vector.store %st#5, %part[%hi, %wi, %at1] : memref, vector<4xf32> - %am1 = arith.addi %base1, %c128 : index - %as1 = arith.addi %base1, %c129 : index - scf.if %lane0 { - memref.store %st#3, %part[%hi, %wi, %am1] : memref - memref.store %st#4, %part[%hi, %wi, %as1] : memref - } - %base2 = arith.muli %qt2, %c132 : index - %at2 = arith.addi %base2, %l4 : index - vector.store %st#8, %part[%hi, %wi, %at2] : memref, vector<4xf32> - %am2 = arith.addi %base2, %c128 : index - %as2 = arith.addi %base2, %c129 : index - scf.if %lane0 { - memref.store %st#6, %part[%hi, %wi, %am2] : memref - memref.store %st#7, %part[%hi, %wi, %as2] : memref - } - %base3 = arith.muli %qt3, %c132 : index - %at3 = arith.addi %base3, %l4 : index - vector.store %st#11, %part[%hi, %wi, %at3] : memref, vector<4xf32> - %am3 = arith.addi %base3, %c128 : index - %as3 = arith.addi %base3, %c129 : index - scf.if %lane0 { - memref.store %st#9, %part[%hi, %wi, %am3] : memref - memref.store %st#10, %part[%hi, %wi, %as3] : memref - } - %base4 = arith.muli %qt4, %c132 : index - %at4 = arith.addi %base4, %l4 : index - vector.store %st#14, %part[%hi, %wi, %at4] : memref, vector<4xf32> - %am4 = arith.addi %base4, %c128 : index - %as4 = arith.addi %base4, %c129 : index - scf.if %lane0 { - memref.store %st#12, %part[%hi, %wi, %am4] : memref - memref.store %st#13, %part[%hi, %wi, %as4] : memref - } - %base5 = arith.muli %qt5, %c132 : index - %at5 = arith.addi %base5, %l4 : index - vector.store %st#17, %part[%hi, %wi, %at5] : memref, vector<4xf32> - %am5 = arith.addi %base5, %c128 : index - %as5 = arith.addi %base5, %c129 : index - scf.if %lane0 { - memref.store %st#15, %part[%hi, %wi, %am5] : memref - memref.store %st#16, %part[%hi, %wi, %as5] : memref } - %base6 = arith.muli %qt6, %c132 : index - %at6 = arith.addi %base6, %l4 : index - vector.store %st#20, %part[%hi, %wi, %at6] : memref, vector<4xf32> - %am6 = arith.addi %base6, %c128 : index - %as6 = arith.addi %base6, %c129 : index - scf.if %lane0 { - memref.store %st#18, %part[%hi, %wi, %am6] : memref - memref.store %st#19, %part[%hi, %wi, %as6] : memref + for l in 0..2 across lanes(32) { + part[h][w][132 * (t0 + 0) + 128 + l] = stats[s][0][l]; + part[h][w][132 * (t0 + 1) + 128 + l] = stats[s][1][l]; + part[h][w][132 * (t0 + 2) + 128 + l] = stats[s][2][l]; + part[h][w][132 * (t0 + 3) + 128 + l] = stats[s][3][l]; + part[h][w][132 * (t0 + 4) + 128 + l] = stats[s][4][l]; + part[h][w][132 * (t0 + 5) + 128 + l] = stats[s][5][l]; + part[h][w][132 * (t0 + 6) + 128 + l] = stats[s][6][l]; } - macro.yield %h : i32 - }; + } } } } @@ -1778,394 +1765,400 @@ fn round_attention_parts_8(part : &mut Tensor, q : 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, %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])]) { - %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 - %c132 = arith.constant 132 : 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 - %t0i = arith.index_cast %t0 : 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> - %scv = vector.broadcast %scale : f32 to vector<4xf32> - %ct0 = arith.constant 0 : index - %pos0 = arith.addi %posi, %ct0 : index - %n0 = arith.addi %pos0, %c32 : index - %chunks0 = arith.divui %n0, %c32 : index - %qt0 = arith.addi %t0i, %ct0 : index - %qv0 = vector.load %q[%qt0, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs0 = arith.mulf %qv0, %scv : vector<4xf32> - %ct1 = arith.constant 1 : index - %pos1 = arith.addi %posi, %ct1 : index - %n1 = arith.addi %pos1, %c32 : index - %chunks1 = arith.divui %n1, %c32 : index - %qt1 = arith.addi %t0i, %ct1 : index - %qv1 = vector.load %q[%qt1, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs1 = arith.mulf %qv1, %scv : vector<4xf32> - %ct2 = arith.constant 2 : index - %pos2 = arith.addi %posi, %ct2 : index - %n2 = arith.addi %pos2, %c32 : index - %chunks2 = arith.divui %n2, %c32 : index - %qt2 = arith.addi %t0i, %ct2 : index - %qv2 = vector.load %q[%qt2, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs2 = arith.mulf %qv2, %scv : vector<4xf32> - %ct3 = arith.constant 3 : index - %pos3 = arith.addi %posi, %ct3 : index - %n3 = arith.addi %pos3, %c32 : index - %chunks3 = arith.divui %n3, %c32 : index - %qt3 = arith.addi %t0i, %ct3 : index - %qv3 = vector.load %q[%qt3, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs3 = arith.mulf %qv3, %scv : vector<4xf32> - %ct4 = arith.constant 4 : index - %pos4 = arith.addi %posi, %ct4 : index - %n4 = arith.addi %pos4, %c32 : index - %chunks4 = arith.divui %n4, %c32 : index - %qt4 = arith.addi %t0i, %ct4 : index - %qv4 = vector.load %q[%qt4, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs4 = arith.mulf %qv4, %scv : vector<4xf32> - %ct5 = arith.constant 5 : index - %pos5 = arith.addi %posi, %ct5 : index - %n5 = arith.addi %pos5, %c32 : index - %chunks5 = arith.divui %n5, %c32 : index - %qt5 = arith.addi %t0i, %ct5 : index - %qv5 = vector.load %q[%qt5, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs5 = arith.mulf %qv5, %scv : vector<4xf32> - %ct6 = arith.constant 6 : index - %pos6 = arith.addi %posi, %ct6 : index - %n6 = arith.addi %pos6, %c32 : index - %chunks6 = arith.divui %n6, %c32 : index - %qt6 = arith.addi %t0i, %ct6 : index - %qv6 = vector.load %q[%qt6, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs6 = arith.mulf %qv6, %scv : vector<4xf32> - %ct7 = arith.constant 7 : index - %pos7 = arith.addi %posi, %ct7 : index - %n7 = arith.addi %pos7, %c32 : index - %chunks7 = arith.divui %n7, %c32 : index - %qt7 = arith.addi %t0i, %ct7 : index - %qv7 = vector.load %q[%qt7, %hi, %l4] {alignment = 16} : memref, vector<4xf32> - %qs7 = arith.mulf %qv7, %scv : vector<4xf32> - %st:24 = scf.for %ic = %wi to %chunks7 step %nwgi iter_args(%M0 = %neg, %S0 = %zero, %o0 = %vz4, %M1 = %neg, %S1 = %zero, %o1 = %vz4, %M2 = %neg, %S2 = %zero, %o2 = %vz4, %M3 = %neg, %S3 = %zero, %o3 = %vz4, %M4 = %neg, %S4 = %zero, %o4 = %vz4, %M5 = %neg, %S5 = %zero, %o5 = %vz4, %M6 = %neg, %S6 = %zero, %o6 = %vz4, %M7 = %neg, %S7 = %zero, %o7 = %vz4) -> (f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>) { - %r0 = arith.muli %ic, %c32 : index - %my:8 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%m0 = %neg, %m1 = %neg, %m2 = %neg, %m3 = %neg, %m4 = %neg, %m5 = %neg, %m6 = %neg, %m7 = %neg) -> (f32, f32, f32, f32, f32, f32, f32, f32) { - %row = arith.addi %r0, %cc : index - %rowc = arith.minui %row, %pos7 : index - %kh = vector.load %k[%rowc, %kd] {alignment = 8} : memref>, vector<4xf16> - %kf = arith.extf %kh : vector<4xf16> to vector<4xf32> - %mine = arith.cmpi eq, %cc, %l : index - %pr0 = arith.mulf %kf, %qs0 : vector<4xf32> - %pl0 = vector.reduction , %pr0 : vector<4xf32> into f32 - %sc0 = gpu.subgroup_reduce add %pl0 : (f32) -> f32 - %live0 = arith.cmpi ule, %row, %pos0 : index - %scm0 = arith.select %live0, %sc0, %neg : f32 - %mm0 = arith.select %mine, %scm0, %m0 : f32 - %pr1 = arith.mulf %kf, %qs1 : vector<4xf32> - %pl1 = vector.reduction , %pr1 : vector<4xf32> into f32 - %sc1 = gpu.subgroup_reduce add %pl1 : (f32) -> f32 - %live1 = arith.cmpi ule, %row, %pos1 : index - %scm1 = arith.select %live1, %sc1, %neg : f32 - %mm1 = arith.select %mine, %scm1, %m1 : f32 - %pr2 = arith.mulf %kf, %qs2 : vector<4xf32> - %pl2 = vector.reduction , %pr2 : vector<4xf32> into f32 - %sc2 = gpu.subgroup_reduce add %pl2 : (f32) -> f32 - %live2 = arith.cmpi ule, %row, %pos2 : index - %scm2 = arith.select %live2, %sc2, %neg : f32 - %mm2 = arith.select %mine, %scm2, %m2 : f32 - %pr3 = arith.mulf %kf, %qs3 : vector<4xf32> - %pl3 = vector.reduction , %pr3 : vector<4xf32> into f32 - %sc3 = gpu.subgroup_reduce add %pl3 : (f32) -> f32 - %live3 = arith.cmpi ule, %row, %pos3 : index - %scm3 = arith.select %live3, %sc3, %neg : f32 - %mm3 = arith.select %mine, %scm3, %m3 : f32 - %pr4 = arith.mulf %kf, %qs4 : vector<4xf32> - %pl4 = vector.reduction , %pr4 : vector<4xf32> into f32 - %sc4 = gpu.subgroup_reduce add %pl4 : (f32) -> f32 - %live4 = arith.cmpi ule, %row, %pos4 : index - %scm4 = arith.select %live4, %sc4, %neg : f32 - %mm4 = arith.select %mine, %scm4, %m4 : f32 - %pr5 = arith.mulf %kf, %qs5 : vector<4xf32> - %pl5 = vector.reduction , %pr5 : vector<4xf32> into f32 - %sc5 = gpu.subgroup_reduce add %pl5 : (f32) -> f32 - %live5 = arith.cmpi ule, %row, %pos5 : index - %scm5 = arith.select %live5, %sc5, %neg : f32 - %mm5 = arith.select %mine, %scm5, %m5 : f32 - %pr6 = arith.mulf %kf, %qs6 : vector<4xf32> - %pl6 = vector.reduction , %pr6 : vector<4xf32> into f32 - %sc6 = gpu.subgroup_reduce add %pl6 : (f32) -> f32 - %live6 = arith.cmpi ule, %row, %pos6 : index - %scm6 = arith.select %live6, %sc6, %neg : f32 - %mm6 = arith.select %mine, %scm6, %m6 : f32 - %pr7 = arith.mulf %kf, %qs7 : vector<4xf32> - %pl7 = vector.reduction , %pr7 : vector<4xf32> into f32 - %sc7 = gpu.subgroup_reduce add %pl7 : (f32) -> f32 - %live7 = arith.cmpi ule, %row, %pos7 : index - %scm7 = arith.select %live7, %sc7, %neg : f32 - %mm7 = arith.select %mine, %scm7, %m7 : f32 - scf.yield %mm0, %mm1, %mm2, %mm3, %mm4, %mm5, %mm6, %mm7 : f32, f32, f32, f32, f32, f32, f32, f32 - } - %act0 = arith.cmpi ult, %ic, %chunks0 : index - %u0:4 = scf.if %act0 -> (f32, f32, vector<4xf32>, f32) { - %bm0 = gpu.subgroup_reduce maxnumf %my#0 : (f32) -> f32 - %Mn0 = arith.maxnumf %M0, %bm0 : f32 - %dm0 = arith.subf %M0, %Mn0 : f32 - %ms0 = math.exp %dm0 : f32 - %dp0 = arith.subf %my#0, %Mn0 : f32 - %p0 = math.exp %dp0 : f32 - %bs0 = gpu.subgroup_reduce add %p0 : (f32) -> f32 - %Ss0 = arith.mulf %S0, %ms0 : f32 - %Sn0 = arith.addf %Ss0, %bs0 : f32 - %msv0 = vector.broadcast %ms0 : f32 to vector<4xf32> - %ox0 = arith.mulf %o0, %msv0 : vector<4xf32> - scf.yield %Mn0, %Sn0, %ox0, %p0 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M0, %S0, %o0, %zero : f32, f32, vector<4xf32>, f32 - } - %act1 = arith.cmpi ult, %ic, %chunks1 : index - %u1:4 = scf.if %act1 -> (f32, f32, vector<4xf32>, f32) { - %bm1 = gpu.subgroup_reduce maxnumf %my#1 : (f32) -> f32 - %Mn1 = arith.maxnumf %M1, %bm1 : f32 - %dm1 = arith.subf %M1, %Mn1 : f32 - %ms1 = math.exp %dm1 : f32 - %dp1 = arith.subf %my#1, %Mn1 : f32 - %p1 = math.exp %dp1 : f32 - %bs1 = gpu.subgroup_reduce add %p1 : (f32) -> f32 - %Ss1 = arith.mulf %S1, %ms1 : f32 - %Sn1 = arith.addf %Ss1, %bs1 : f32 - %msv1 = vector.broadcast %ms1 : f32 to vector<4xf32> - %ox1 = arith.mulf %o1, %msv1 : vector<4xf32> - scf.yield %Mn1, %Sn1, %ox1, %p1 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M1, %S1, %o1, %zero : f32, f32, vector<4xf32>, f32 - } - %act2 = arith.cmpi ult, %ic, %chunks2 : index - %u2:4 = scf.if %act2 -> (f32, f32, vector<4xf32>, f32) { - %bm2 = gpu.subgroup_reduce maxnumf %my#2 : (f32) -> f32 - %Mn2 = arith.maxnumf %M2, %bm2 : f32 - %dm2 = arith.subf %M2, %Mn2 : f32 - %ms2 = math.exp %dm2 : f32 - %dp2 = arith.subf %my#2, %Mn2 : f32 - %p2 = math.exp %dp2 : f32 - %bs2 = gpu.subgroup_reduce add %p2 : (f32) -> f32 - %Ss2 = arith.mulf %S2, %ms2 : f32 - %Sn2 = arith.addf %Ss2, %bs2 : f32 - %msv2 = vector.broadcast %ms2 : f32 to vector<4xf32> - %ox2 = arith.mulf %o2, %msv2 : vector<4xf32> - scf.yield %Mn2, %Sn2, %ox2, %p2 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M2, %S2, %o2, %zero : f32, f32, vector<4xf32>, f32 - } - %act3 = arith.cmpi ult, %ic, %chunks3 : index - %u3:4 = scf.if %act3 -> (f32, f32, vector<4xf32>, f32) { - %bm3 = gpu.subgroup_reduce maxnumf %my#3 : (f32) -> f32 - %Mn3 = arith.maxnumf %M3, %bm3 : f32 - %dm3 = arith.subf %M3, %Mn3 : f32 - %ms3 = math.exp %dm3 : f32 - %dp3 = arith.subf %my#3, %Mn3 : f32 - %p3 = math.exp %dp3 : f32 - %bs3 = gpu.subgroup_reduce add %p3 : (f32) -> f32 - %Ss3 = arith.mulf %S3, %ms3 : f32 - %Sn3 = arith.addf %Ss3, %bs3 : f32 - %msv3 = vector.broadcast %ms3 : f32 to vector<4xf32> - %ox3 = arith.mulf %o3, %msv3 : vector<4xf32> - scf.yield %Mn3, %Sn3, %ox3, %p3 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M3, %S3, %o3, %zero : f32, f32, vector<4xf32>, f32 - } - %act4 = arith.cmpi ult, %ic, %chunks4 : index - %u4:4 = scf.if %act4 -> (f32, f32, vector<4xf32>, f32) { - %bm4 = gpu.subgroup_reduce maxnumf %my#4 : (f32) -> f32 - %Mn4 = arith.maxnumf %M4, %bm4 : f32 - %dm4 = arith.subf %M4, %Mn4 : f32 - %ms4 = math.exp %dm4 : f32 - %dp4 = arith.subf %my#4, %Mn4 : f32 - %p4 = math.exp %dp4 : f32 - %bs4 = gpu.subgroup_reduce add %p4 : (f32) -> f32 - %Ss4 = arith.mulf %S4, %ms4 : f32 - %Sn4 = arith.addf %Ss4, %bs4 : f32 - %msv4 = vector.broadcast %ms4 : f32 to vector<4xf32> - %ox4 = arith.mulf %o4, %msv4 : vector<4xf32> - scf.yield %Mn4, %Sn4, %ox4, %p4 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M4, %S4, %o4, %zero : f32, f32, vector<4xf32>, f32 - } - %act5 = arith.cmpi ult, %ic, %chunks5 : index - %u5:4 = scf.if %act5 -> (f32, f32, vector<4xf32>, f32) { - %bm5 = gpu.subgroup_reduce maxnumf %my#5 : (f32) -> f32 - %Mn5 = arith.maxnumf %M5, %bm5 : f32 - %dm5 = arith.subf %M5, %Mn5 : f32 - %ms5 = math.exp %dm5 : f32 - %dp5 = arith.subf %my#5, %Mn5 : f32 - %p5 = math.exp %dp5 : f32 - %bs5 = gpu.subgroup_reduce add %p5 : (f32) -> f32 - %Ss5 = arith.mulf %S5, %ms5 : f32 - %Sn5 = arith.addf %Ss5, %bs5 : f32 - %msv5 = vector.broadcast %ms5 : f32 to vector<4xf32> - %ox5 = arith.mulf %o5, %msv5 : vector<4xf32> - scf.yield %Mn5, %Sn5, %ox5, %p5 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M5, %S5, %o5, %zero : f32, f32, vector<4xf32>, f32 - } - %act6 = arith.cmpi ult, %ic, %chunks6 : index - %u6:4 = scf.if %act6 -> (f32, f32, vector<4xf32>, f32) { - %bm6 = gpu.subgroup_reduce maxnumf %my#6 : (f32) -> f32 - %Mn6 = arith.maxnumf %M6, %bm6 : f32 - %dm6 = arith.subf %M6, %Mn6 : f32 - %ms6 = math.exp %dm6 : f32 - %dp6 = arith.subf %my#6, %Mn6 : f32 - %p6 = math.exp %dp6 : f32 - %bs6 = gpu.subgroup_reduce add %p6 : (f32) -> f32 - %Ss6 = arith.mulf %S6, %ms6 : f32 - %Sn6 = arith.addf %Ss6, %bs6 : f32 - %msv6 = vector.broadcast %ms6 : f32 to vector<4xf32> - %ox6 = arith.mulf %o6, %msv6 : vector<4xf32> - scf.yield %Mn6, %Sn6, %ox6, %p6 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M6, %S6, %o6, %zero : f32, f32, vector<4xf32>, f32 - } - %act7 = arith.cmpi ult, %ic, %chunks7 : index - %u7:4 = scf.if %act7 -> (f32, f32, vector<4xf32>, f32) { - %bm7 = gpu.subgroup_reduce maxnumf %my#7 : (f32) -> f32 - %Mn7 = arith.maxnumf %M7, %bm7 : f32 - %dm7 = arith.subf %M7, %Mn7 : f32 - %ms7 = math.exp %dm7 : f32 - %dp7 = arith.subf %my#7, %Mn7 : f32 - %p7 = math.exp %dp7 : f32 - %bs7 = gpu.subgroup_reduce add %p7 : (f32) -> f32 - %Ss7 = arith.mulf %S7, %ms7 : f32 - %Sn7 = arith.addf %Ss7, %bs7 : f32 - %msv7 = vector.broadcast %ms7 : f32 to vector<4xf32> - %ox7 = arith.mulf %o7, %msv7 : vector<4xf32> - scf.yield %Mn7, %Sn7, %ox7, %p7 : f32, f32, vector<4xf32>, f32 - } else { - scf.yield %M7, %S7, %o7, %zero : f32, f32, vector<4xf32>, f32 + 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 = 4 * l; + let last = pos + 7; + let q0_0 = q[t0 + 0][h][d + 0] * scale; + let q0_1 = q[t0 + 0][h][d + 1] * scale; + let q0_2 = q[t0 + 0][h][d + 2] * scale; + let q0_3 = q[t0 + 0][h][d + 3] * scale; + let mut big0 : f32 = -3.0e38; + let mut total0 : f32 = 0.0; + let mut o0_0 : f32 = 0.0; + let mut o0_1 : f32 = 0.0; + let mut o0_2 : f32 = 0.0; + let mut o0_3 : f32 = 0.0; + let q1_0 = q[t0 + 1][h][d + 0] * scale; + let q1_1 = q[t0 + 1][h][d + 1] * scale; + let q1_2 = q[t0 + 1][h][d + 2] * scale; + let q1_3 = q[t0 + 1][h][d + 3] * scale; + let mut big1 : f32 = -3.0e38; + let mut total1 : f32 = 0.0; + let mut o1_0 : f32 = 0.0; + let mut o1_1 : f32 = 0.0; + let mut o1_2 : f32 = 0.0; + let mut o1_3 : f32 = 0.0; + let q2_0 = q[t0 + 2][h][d + 0] * scale; + let q2_1 = q[t0 + 2][h][d + 1] * scale; + let q2_2 = q[t0 + 2][h][d + 2] * scale; + let q2_3 = q[t0 + 2][h][d + 3] * scale; + let mut big2 : f32 = -3.0e38; + let mut total2 : f32 = 0.0; + let mut o2_0 : f32 = 0.0; + let mut o2_1 : f32 = 0.0; + let mut o2_2 : f32 = 0.0; + let mut o2_3 : f32 = 0.0; + let q3_0 = q[t0 + 3][h][d + 0] * scale; + let q3_1 = q[t0 + 3][h][d + 1] * scale; + let q3_2 = q[t0 + 3][h][d + 2] * scale; + let q3_3 = q[t0 + 3][h][d + 3] * scale; + let mut big3 : f32 = -3.0e38; + let mut total3 : f32 = 0.0; + let mut o3_0 : f32 = 0.0; + let mut o3_1 : f32 = 0.0; + let mut o3_2 : f32 = 0.0; + let mut o3_3 : f32 = 0.0; + let q4_0 = q[t0 + 4][h][d + 0] * scale; + let q4_1 = q[t0 + 4][h][d + 1] * scale; + let q4_2 = q[t0 + 4][h][d + 2] * scale; + let q4_3 = q[t0 + 4][h][d + 3] * scale; + let mut big4 : f32 = -3.0e38; + let mut total4 : f32 = 0.0; + let mut o4_0 : f32 = 0.0; + let mut o4_1 : f32 = 0.0; + let mut o4_2 : f32 = 0.0; + let mut o4_3 : f32 = 0.0; + let q5_0 = q[t0 + 5][h][d + 0] * scale; + let q5_1 = q[t0 + 5][h][d + 1] * scale; + let q5_2 = q[t0 + 5][h][d + 2] * scale; + let q5_3 = q[t0 + 5][h][d + 3] * scale; + let mut big5 : f32 = -3.0e38; + let mut total5 : f32 = 0.0; + let mut o5_0 : f32 = 0.0; + let mut o5_1 : f32 = 0.0; + let mut o5_2 : f32 = 0.0; + let mut o5_3 : f32 = 0.0; + let q6_0 = q[t0 + 6][h][d + 0] * scale; + let q6_1 = q[t0 + 6][h][d + 1] * scale; + let q6_2 = q[t0 + 6][h][d + 2] * scale; + let q6_3 = q[t0 + 6][h][d + 3] * scale; + let mut big6 : f32 = -3.0e38; + let mut total6 : f32 = 0.0; + let mut o6_0 : f32 = 0.0; + let mut o6_1 : f32 = 0.0; + let mut o6_2 : f32 = 0.0; + let mut o6_3 : f32 = 0.0; + let q7_0 = q[t0 + 7][h][d + 0] * scale; + let q7_1 = q[t0 + 7][h][d + 1] * scale; + let q7_2 = q[t0 + 7][h][d + 2] * scale; + let q7_3 = q[t0 + 7][h][d + 3] * scale; + let mut big7 : f32 = -3.0e38; + let mut total7 : f32 = 0.0; + let mut o7_0 : f32 = 0.0; + let mut o7_1 : f32 = 0.0; + let mut o7_2 : f32 = 0.0; + let mut o7_3 : f32 = 0.0; + let chunks = (last + 32) / 32; + let mut c = w; + while c < chunks { + let r0 = c * 32; + let mut mine0 : f32 = -3.0e38; + let mut mine1 : f32 = -3.0e38; + let mut mine2 : f32 = -3.0e38; + let mut mine3 : f32 = -3.0e38; + let mut mine4 : f32 = -3.0e38; + let mut mine5 : f32 = -3.0e38; + let mut mine6 : f32 = -3.0e38; + let mut mine7 : f32 = -3.0e38; + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > last { + kept = last; + } + let k0 = half_at(k_cache, kept, g, d, 0); + let k1 = half_at(k_cache, kept, g, d, 1); + let k2 = half_at(k_cache, kept, g, d, 2); + let k3 = half_at(k_cache, kept, g, d, 3); + let mut score0 = lane_sum(k0 * q0_0 + k1 * q0_1 + k2 * q0_2 + k3 * q0_3); + if row > pos + 0 { + score0 = -3.0e38; + } + let mut score1 = lane_sum(k0 * q1_0 + k1 * q1_1 + k2 * q1_2 + k3 * q1_3); + if row > pos + 1 { + score1 = -3.0e38; + } + let mut score2 = lane_sum(k0 * q2_0 + k1 * q2_1 + k2 * q2_2 + k3 * q2_3); + if row > pos + 2 { + score2 = -3.0e38; + } + let mut score3 = lane_sum(k0 * q3_0 + k1 * q3_1 + k2 * q3_2 + k3 * q3_3); + if row > pos + 3 { + score3 = -3.0e38; + } + let mut score4 = lane_sum(k0 * q4_0 + k1 * q4_1 + k2 * q4_2 + k3 * q4_3); + if row > pos + 4 { + score4 = -3.0e38; + } + let mut score5 = lane_sum(k0 * q5_0 + k1 * q5_1 + k2 * q5_2 + k3 * q5_3); + if row > pos + 5 { + score5 = -3.0e38; + } + let mut score6 = lane_sum(k0 * q6_0 + k1 * q6_1 + k2 * q6_2 + k3 * q6_3); + if row > pos + 6 { + score6 = -3.0e38; + } + let mut score7 = lane_sum(k0 * q7_0 + k1 * q7_1 + k2 * q7_2 + k3 * q7_3); + if row > pos + 7 { + score7 = -3.0e38; + } + if r == l { + mine0 = score0; + mine1 = score1; + mine2 = score2; + mine3 = score3; + mine4 = score4; + mine5 = score5; + mine6 = score6; + mine7 = score7; + } + } + let mut p0 : f32 = 0.0; + if c < (pos + 0 + 32) / 32 { + let top = big0.max(lane_max(mine0)); + let shrink = (big0 - top).fast_exp(); + p0 = (mine0 - top).fast_exp(); + total0 = total0 * shrink + lane_sum(p0); + o0_0 = o0_0 * shrink; + o0_1 = o0_1 * shrink; + o0_2 = o0_2 * shrink; + o0_3 = o0_3 * shrink; + big0 = top; + } + let mut p1 : f32 = 0.0; + if c < (pos + 1 + 32) / 32 { + let top = big1.max(lane_max(mine1)); + let shrink = (big1 - top).fast_exp(); + p1 = (mine1 - top).fast_exp(); + total1 = total1 * shrink + lane_sum(p1); + o1_0 = o1_0 * shrink; + o1_1 = o1_1 * shrink; + o1_2 = o1_2 * shrink; + o1_3 = o1_3 * shrink; + big1 = top; + } + let mut p2 : f32 = 0.0; + if c < (pos + 2 + 32) / 32 { + let top = big2.max(lane_max(mine2)); + let shrink = (big2 - top).fast_exp(); + p2 = (mine2 - top).fast_exp(); + total2 = total2 * shrink + lane_sum(p2); + o2_0 = o2_0 * shrink; + o2_1 = o2_1 * shrink; + o2_2 = o2_2 * shrink; + o2_3 = o2_3 * shrink; + big2 = top; + } + let mut p3 : f32 = 0.0; + if c < (pos + 3 + 32) / 32 { + let top = big3.max(lane_max(mine3)); + let shrink = (big3 - top).fast_exp(); + p3 = (mine3 - top).fast_exp(); + total3 = total3 * shrink + lane_sum(p3); + o3_0 = o3_0 * shrink; + o3_1 = o3_1 * shrink; + o3_2 = o3_2 * shrink; + o3_3 = o3_3 * shrink; + big3 = top; + } + let mut p4 : f32 = 0.0; + if c < (pos + 4 + 32) / 32 { + let top = big4.max(lane_max(mine4)); + let shrink = (big4 - top).fast_exp(); + p4 = (mine4 - top).fast_exp(); + total4 = total4 * shrink + lane_sum(p4); + o4_0 = o4_0 * shrink; + o4_1 = o4_1 * shrink; + o4_2 = o4_2 * shrink; + o4_3 = o4_3 * shrink; + big4 = top; + } + let mut p5 : f32 = 0.0; + if c < (pos + 5 + 32) / 32 { + let top = big5.max(lane_max(mine5)); + let shrink = (big5 - top).fast_exp(); + p5 = (mine5 - top).fast_exp(); + total5 = total5 * shrink + lane_sum(p5); + o5_0 = o5_0 * shrink; + o5_1 = o5_1 * shrink; + o5_2 = o5_2 * shrink; + o5_3 = o5_3 * shrink; + big5 = top; + } + let mut p6 : f32 = 0.0; + if c < (pos + 6 + 32) / 32 { + let top = big6.max(lane_max(mine6)); + let shrink = (big6 - top).fast_exp(); + p6 = (mine6 - top).fast_exp(); + total6 = total6 * shrink + lane_sum(p6); + o6_0 = o6_0 * shrink; + o6_1 = o6_1 * shrink; + o6_2 = o6_2 * shrink; + o6_3 = o6_3 * shrink; + big6 = top; + } + let mut p7 : f32 = 0.0; + if c < (pos + 7 + 32) / 32 { + let top = big7.max(lane_max(mine7)); + let shrink = (big7 - top).fast_exp(); + p7 = (mine7 - top).fast_exp(); + total7 = total7 * shrink + lane_sum(p7); + o7_0 = o7_0 * shrink; + o7_1 = o7_1 * shrink; + o7_2 = o7_2 * shrink; + o7_3 = o7_3 * shrink; + big7 = top; + } + for r in 0..32 { + let row = r0 + r; + let mut kept = row; + if row > last { + kept = last; + } + let pr0 = lane_value(p0, r); + o0_0 = fused(half_at(v_cache, kept, g, d, 0), pr0, o0_0); + o0_1 = fused(half_at(v_cache, kept, g, d, 1), pr0, o0_1); + o0_2 = fused(half_at(v_cache, kept, g, d, 2), pr0, o0_2); + o0_3 = fused(half_at(v_cache, kept, g, d, 3), pr0, o0_3); + let pr1 = lane_value(p1, r); + o1_0 = fused(half_at(v_cache, kept, g, d, 0), pr1, o1_0); + o1_1 = fused(half_at(v_cache, kept, g, d, 1), pr1, o1_1); + o1_2 = fused(half_at(v_cache, kept, g, d, 2), pr1, o1_2); + o1_3 = fused(half_at(v_cache, kept, g, d, 3), pr1, o1_3); + let pr2 = lane_value(p2, r); + o2_0 = fused(half_at(v_cache, kept, g, d, 0), pr2, o2_0); + o2_1 = fused(half_at(v_cache, kept, g, d, 1), pr2, o2_1); + o2_2 = fused(half_at(v_cache, kept, g, d, 2), pr2, o2_2); + o2_3 = fused(half_at(v_cache, kept, g, d, 3), pr2, o2_3); + let pr3 = lane_value(p3, r); + o3_0 = fused(half_at(v_cache, kept, g, d, 0), pr3, o3_0); + o3_1 = fused(half_at(v_cache, kept, g, d, 1), pr3, o3_1); + o3_2 = fused(half_at(v_cache, kept, g, d, 2), pr3, o3_2); + o3_3 = fused(half_at(v_cache, kept, g, d, 3), pr3, o3_3); + let pr4 = lane_value(p4, r); + o4_0 = fused(half_at(v_cache, kept, g, d, 0), pr4, o4_0); + o4_1 = fused(half_at(v_cache, kept, g, d, 1), pr4, o4_1); + o4_2 = fused(half_at(v_cache, kept, g, d, 2), pr4, o4_2); + o4_3 = fused(half_at(v_cache, kept, g, d, 3), pr4, o4_3); + let pr5 = lane_value(p5, r); + o5_0 = fused(half_at(v_cache, kept, g, d, 0), pr5, o5_0); + o5_1 = fused(half_at(v_cache, kept, g, d, 1), pr5, o5_1); + o5_2 = fused(half_at(v_cache, kept, g, d, 2), pr5, o5_2); + o5_3 = fused(half_at(v_cache, kept, g, d, 3), pr5, o5_3); + let pr6 = lane_value(p6, r); + o6_0 = fused(half_at(v_cache, kept, g, d, 0), pr6, o6_0); + o6_1 = fused(half_at(v_cache, kept, g, d, 1), pr6, o6_1); + o6_2 = fused(half_at(v_cache, kept, g, d, 2), pr6, o6_2); + o6_3 = fused(half_at(v_cache, kept, g, d, 3), pr6, o6_3); + let pr7 = lane_value(p7, r); + o7_0 = fused(half_at(v_cache, kept, g, d, 0), pr7, o7_0); + o7_1 = fused(half_at(v_cache, kept, g, d, 1), pr7, o7_1); + o7_2 = fused(half_at(v_cache, kept, g, d, 2), pr7, o7_2); + o7_3 = fused(half_at(v_cache, kept, g, d, 3), pr7, o7_3); + } + c = c + nwg; } - %ov:8 = scf.for %cc = %c0 to %c32 step %c1 iter_args(%oa0 = %u0#2, %oa1 = %u1#2, %oa2 = %u2#2, %oa3 = %u3#2, %oa4 = %u4#2, %oa5 = %u5#2, %oa6 = %u6#2, %oa7 = %u7#2) -> (vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>) { - %row = arith.addi %r0, %cc : index - %rowc = arith.minui %row, %pos7 : 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 - %pc0, %pv0 = gpu.shuffle idx %u0#3, %cci, %c32i : f32 - %pcv0 = vector.broadcast %pc0 : f32 to vector<4xf32> - %on0 = vector.fma %vf, %pcv0, %oa0 : vector<4xf32> - %pc1, %pv1 = gpu.shuffle idx %u1#3, %cci, %c32i : f32 - %pcv1 = vector.broadcast %pc1 : f32 to vector<4xf32> - %on1 = vector.fma %vf, %pcv1, %oa1 : vector<4xf32> - %pc2, %pv2 = gpu.shuffle idx %u2#3, %cci, %c32i : f32 - %pcv2 = vector.broadcast %pc2 : f32 to vector<4xf32> - %on2 = vector.fma %vf, %pcv2, %oa2 : vector<4xf32> - %pc3, %pv3 = gpu.shuffle idx %u3#3, %cci, %c32i : f32 - %pcv3 = vector.broadcast %pc3 : f32 to vector<4xf32> - %on3 = vector.fma %vf, %pcv3, %oa3 : vector<4xf32> - %pc4, %pv4 = gpu.shuffle idx %u4#3, %cci, %c32i : f32 - %pcv4 = vector.broadcast %pc4 : f32 to vector<4xf32> - %on4 = vector.fma %vf, %pcv4, %oa4 : vector<4xf32> - %pc5, %pv5 = gpu.shuffle idx %u5#3, %cci, %c32i : f32 - %pcv5 = vector.broadcast %pc5 : f32 to vector<4xf32> - %on5 = vector.fma %vf, %pcv5, %oa5 : vector<4xf32> - %pc6, %pv6 = gpu.shuffle idx %u6#3, %cci, %c32i : f32 - %pcv6 = vector.broadcast %pc6 : f32 to vector<4xf32> - %on6 = vector.fma %vf, %pcv6, %oa6 : vector<4xf32> - %pc7, %pv7 = gpu.shuffle idx %u7#3, %cci, %c32i : f32 - %pcv7 = vector.broadcast %pc7 : f32 to vector<4xf32> - %on7 = vector.fma %vf, %pcv7, %oa7 : vector<4xf32> - scf.yield %on0, %on1, %on2, %on3, %on4, %on5, %on6, %on7 : vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32> + let b0 = 132 * (t0 + 0); + part[h][w][b0 + d + 0] = o0_0; + part[h][w][b0 + d + 1] = o0_1; + part[h][w][b0 + d + 2] = o0_2; + part[h][w][b0 + d + 3] = o0_3; + let b1 = 132 * (t0 + 1); + part[h][w][b1 + d + 0] = o1_0; + part[h][w][b1 + d + 1] = o1_1; + part[h][w][b1 + d + 2] = o1_2; + part[h][w][b1 + d + 3] = o1_3; + let b2 = 132 * (t0 + 2); + part[h][w][b2 + d + 0] = o2_0; + part[h][w][b2 + d + 1] = o2_1; + part[h][w][b2 + d + 2] = o2_2; + part[h][w][b2 + d + 3] = o2_3; + let b3 = 132 * (t0 + 3); + part[h][w][b3 + d + 0] = o3_0; + part[h][w][b3 + d + 1] = o3_1; + part[h][w][b3 + d + 2] = o3_2; + part[h][w][b3 + d + 3] = o3_3; + let b4 = 132 * (t0 + 4); + part[h][w][b4 + d + 0] = o4_0; + part[h][w][b4 + d + 1] = o4_1; + part[h][w][b4 + d + 2] = o4_2; + part[h][w][b4 + d + 3] = o4_3; + let b5 = 132 * (t0 + 5); + part[h][w][b5 + d + 0] = o5_0; + part[h][w][b5 + d + 1] = o5_1; + part[h][w][b5 + d + 2] = o5_2; + part[h][w][b5 + d + 3] = o5_3; + let b6 = 132 * (t0 + 6); + part[h][w][b6 + d + 0] = o6_0; + part[h][w][b6 + d + 1] = o6_1; + part[h][w][b6 + d + 2] = o6_2; + part[h][w][b6 + d + 3] = o6_3; + let b7 = 132 * (t0 + 7); + part[h][w][b7 + d + 0] = o7_0; + part[h][w][b7 + d + 1] = o7_1; + part[h][w][b7 + d + 2] = o7_2; + part[h][w][b7 + d + 3] = o7_3; + // Every lane has the same largest score and sum of the weights of a query. Lanes 0 and 1 keep them + // for the next loop. + if l < 2 { + let mut x0 = big0; + if l == 1 { + x0 = total0; + } + stats[s][0][l] = x0; + let mut x1 = big1; + if l == 1 { + x1 = total1; + } + stats[s][1][l] = x1; + let mut x2 = big2; + if l == 1 { + x2 = total2; + } + stats[s][2][l] = x2; + let mut x3 = big3; + if l == 1 { + x3 = total3; + } + stats[s][3][l] = x3; + let mut x4 = big4; + if l == 1 { + x4 = total4; + } + stats[s][4][l] = x4; + let mut x5 = big5; + if l == 1 { + x5 = total5; + } + stats[s][5][l] = x5; + let mut x6 = big6; + if l == 1 { + x6 = total6; + } + stats[s][6][l] = x6; + let mut x7 = big7; + if l == 1 { + x7 = total7; + } + stats[s][7][l] = x7; } - scf.yield %u0#0, %u0#1, %ov#0, %u1#0, %u1#1, %ov#1, %u2#0, %u2#1, %ov#2, %u3#0, %u3#1, %ov#3, %u4#0, %u4#1, %ov#4, %u5#0, %u5#1, %ov#5, %u6#0, %u6#1, %ov#6, %u7#0, %u7#1, %ov#7 : f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32>, f32, f32, vector<4xf32> - } - %lane0 = arith.cmpi eq, %l, %c0 : index - %base0 = arith.muli %qt0, %c132 : index - %at0 = arith.addi %base0, %l4 : index - vector.store %st#2, %part[%hi, %wi, %at0] : memref, vector<4xf32> - %am0 = arith.addi %base0, %c128 : index - %as0 = arith.addi %base0, %c129 : index - scf.if %lane0 { - memref.store %st#0, %part[%hi, %wi, %am0] : memref - memref.store %st#1, %part[%hi, %wi, %as0] : memref - } - %base1 = arith.muli %qt1, %c132 : index - %at1 = arith.addi %base1, %l4 : index - vector.store %st#5, %part[%hi, %wi, %at1] : memref, vector<4xf32> - %am1 = arith.addi %base1, %c128 : index - %as1 = arith.addi %base1, %c129 : index - scf.if %lane0 { - memref.store %st#3, %part[%hi, %wi, %am1] : memref - memref.store %st#4, %part[%hi, %wi, %as1] : memref - } - %base2 = arith.muli %qt2, %c132 : index - %at2 = arith.addi %base2, %l4 : index - vector.store %st#8, %part[%hi, %wi, %at2] : memref, vector<4xf32> - %am2 = arith.addi %base2, %c128 : index - %as2 = arith.addi %base2, %c129 : index - scf.if %lane0 { - memref.store %st#6, %part[%hi, %wi, %am2] : memref - memref.store %st#7, %part[%hi, %wi, %as2] : memref } - %base3 = arith.muli %qt3, %c132 : index - %at3 = arith.addi %base3, %l4 : index - vector.store %st#11, %part[%hi, %wi, %at3] : memref, vector<4xf32> - %am3 = arith.addi %base3, %c128 : index - %as3 = arith.addi %base3, %c129 : index - scf.if %lane0 { - memref.store %st#9, %part[%hi, %wi, %am3] : memref - memref.store %st#10, %part[%hi, %wi, %as3] : memref + for l in 0..2 across lanes(32) { + part[h][w][132 * (t0 + 0) + 128 + l] = stats[s][0][l]; + part[h][w][132 * (t0 + 1) + 128 + l] = stats[s][1][l]; + part[h][w][132 * (t0 + 2) + 128 + l] = stats[s][2][l]; + part[h][w][132 * (t0 + 3) + 128 + l] = stats[s][3][l]; + part[h][w][132 * (t0 + 4) + 128 + l] = stats[s][4][l]; + part[h][w][132 * (t0 + 5) + 128 + l] = stats[s][5][l]; + part[h][w][132 * (t0 + 6) + 128 + l] = stats[s][6][l]; + part[h][w][132 * (t0 + 7) + 128 + l] = stats[s][7][l]; } - %base4 = arith.muli %qt4, %c132 : index - %at4 = arith.addi %base4, %l4 : index - vector.store %st#14, %part[%hi, %wi, %at4] : memref, vector<4xf32> - %am4 = arith.addi %base4, %c128 : index - %as4 = arith.addi %base4, %c129 : index - scf.if %lane0 { - memref.store %st#12, %part[%hi, %wi, %am4] : memref - memref.store %st#13, %part[%hi, %wi, %as4] : memref - } - %base5 = arith.muli %qt5, %c132 : index - %at5 = arith.addi %base5, %l4 : index - vector.store %st#17, %part[%hi, %wi, %at5] : memref, vector<4xf32> - %am5 = arith.addi %base5, %c128 : index - %as5 = arith.addi %base5, %c129 : index - scf.if %lane0 { - memref.store %st#15, %part[%hi, %wi, %am5] : memref - memref.store %st#16, %part[%hi, %wi, %as5] : memref - } - %base6 = arith.muli %qt6, %c132 : index - %at6 = arith.addi %base6, %l4 : index - vector.store %st#20, %part[%hi, %wi, %at6] : memref, vector<4xf32> - %am6 = arith.addi %base6, %c128 : index - %as6 = arith.addi %base6, %c129 : index - scf.if %lane0 { - memref.store %st#18, %part[%hi, %wi, %am6] : memref - memref.store %st#19, %part[%hi, %wi, %as6] : memref - } - %base7 = arith.muli %qt7, %c132 : index - %at7 = arith.addi %base7, %l4 : index - vector.store %st#23, %part[%hi, %wi, %at7] : memref, vector<4xf32> - %am7 = arith.addi %base7, %c128 : index - %as7 = arith.addi %base7, %c129 : index - scf.if %lane0 { - memref.store %st#21, %part[%hi, %wi, %am7] : memref - memref.store %st#22, %part[%hi, %wi, %as7] : memref - } - macro.yield %h : i32 - }; + } } } } From 5bc57dff0ff291d4c7e2cffccd15011c8bd5bdb6 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:14:53 -0800 Subject: [PATCH 05/60] Qwen3.6-35B-A3B: weight file version 2, converter, NumPy reference and tiny model This is the Python side of the move to Qwen3.6-35B-A3B. Its architecture is Qwen3.5 MoE, arch 1 in the weight file. Three of every four layers have a Gated DeltaNet, a linear attention. The fourth layer has full attention with a gate on its output. Each layer also has a shared expert. - qwen_weights.py: version 2 of the weight file, with room for 32 config integers. Files of the older models keep version 1 and the same bytes. - convert.py: converts the Hugging Face folder. It stores each norm that multiplies by 1 + w as 1 + w in f32, so a program uses a plain RMSNorm. - reference.py: computes the new layers in float32. --dump-layer writes each stage of one DeltaNet layer, for the checks of the Vx kernels. - make_tiny_model.py --qwen35: a tiny model with the head sizes of the real model, so that it runs the same kernels. On the tiny model, reference.py matches MLX within 5.3e-4 of a logit, with the same 16 greedy tokens. Refs: #89 --- README.md | 6 +- scripts/check_against_mlx.py | 4 +- scripts/convert.py | 64 ++++++++++- scripts/make_tiny_model.py | 123 +++++++++++++++++++-- scripts/qwen_weights.py | 206 +++++++++++++++++++++++++++++++---- scripts/reference.py | 202 ++++++++++++++++++++++++++++++---- scripts/test_qwen_weights.py | 76 +++++++++++++ 7 files changed, 626 insertions(+), 55 deletions(-) diff --git a/README.md b/README.md index 646b592..21094d4 100644 --- a/README.md +++ b/README.md @@ -139,13 +139,13 @@ of Qwen3-Coder-30B-A3B. | Script | What it does | | --- | --- | -| `scripts/convert.py` | Converts a Hugging Face Qwen2 or Qwen3 MoE folder into a weight file. | +| `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. | +| `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 and the quantized weight files. | +| `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. | 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..e8b96f5 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,70 @@ 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"] + heads, head_dim, hidden = config["num_q_heads"], config["head_dim"], config["hidden_size"] + experts, moe_inter = config["num_experts"], config["moe_intermediate_size"] + 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): + 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"] + 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"] + 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"] + return config, tensors + + 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/make_tiny_model.py b/scripts/make_tiny_model.py index 6091942..5f63149 100644 --- a/scripts/make_tiny_model.py +++ b/scripts/make_tiny_model.py @@ -17,6 +17,12 @@ 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. + 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 +85,46 @@ "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, +} SEED = 0x2545F4914F6CDD1D @@ -190,6 +236,67 @@ def tiny_moe_model(): return tensors +def tiny_qwen35_model(): + """The tensors of the tiny Qwen3.5 MoE model, as bf16 bits with their Hugging Face names.""" + 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)} + for layer, kind in enumerate(c["layer_types"]): + p = f"{src}layers.{layer}." + 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) + # 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 +323,21 @@ 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("--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() + if args.moe or args.qwen35: + hf_config, hf = (MOE_CONFIG, tiny_moe_model()) if args.moe else (QWEN35_CONFIG, tiny_qwen35_model()) 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/qwen_weights.py b/scripts/qwen_weights.py index 7d5a73f..c26a355 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,33 @@ 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. + 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 +86,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 +108,22 @@ "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", ] -# 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 +134,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") BLOCK = 128 Q4_GROUP = 32 # A 6-bit matrix has one f16 scale for each Q6_GROUP weights of a row. @@ -134,6 +178,29 @@ 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): + """The names of the tensors of one layer of an arch 1 model, in file order.""" + prefix = f"layers.{layer}." + if has_full_attention(config, layer): + 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 +208,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") @@ -177,6 +247,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"]: @@ -208,6 +281,42 @@ def tensor_shapes(config): return shapes +def arch1_layer_shapes(config, layer): + """The shape of each tensor of one layer of an arch 1 model, by name.""" + prefix = 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 has_full_attention(config, layer): + 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 +340,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 +379,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/test_qwen_weights.py b/scripts/test_qwen_weights.py index 40b71fc..e8c74ac 100644 --- a/scripts/test_qwen_weights.py +++ b/scripts/test_qwen_weights.py @@ -398,5 +398,81 @@ 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]) + + if __name__ == "__main__": unittest.main() From 148546a33bf240459b06a07919f3ee60f9783711 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:29:40 -0800 Subject: [PATCH 06/60] Qwen3.6-35B-A3B: load weight file version 2 into GPU memory src/weights.vx reads version 1 and version 2 of the weight file. load_qwen35_weights loads a Qwen3.5 MoE model (arch 1) into Qwen35Weights, with one Qwen35Layer for each layer. Its norms stay f32, as 1 + w. weight_file_arch reads only the header, so that a program can choose the loader. load_weights and its structs do not change for the older models. tests/print_qwen35_weights.vx prints every tensor of the tiny Qwen3.5 model after it reaches GPU memory: in bf16, and in Q4_0 with a 6-bit lm_head. Its lines equal those of reference.py --tensors. Refs: #89 --- src/weights.vx | 288 ++++++++++++++++++++++++++++++---- tests/print_qwen35_weights.vx | 176 +++++++++++++++++++++ 2 files changed, 435 insertions(+), 29 deletions(-) create mode 100644 tests/print_qwen35_weights.vx diff --git a/src/weights.vx b/src/weights.vx index 25fa3e6..771f24c 100644 --- a/src/weights.vx +++ b/src/weights.vx @@ -24,7 +24,11 @@ extern { /// The bytes "VXQWEN01" at the start of the file, read as one little-endian i64. const MAGIC : i64 = 3544418966465239126; -const VERSION : i64 = 1; +// Version 1 has room for 16 config integers, and version 2, which arch 1 uses, for 32. +const VERSION_1 : i64 = 1; +const VERSION_2 : i64 = 2; +// Qwen3.5 MoE, which Qwen3.6 also uses. arch 0 is Qwen2 and Qwen3 MoE. +const ARCH_QWEN35 : i32 = 1; const ENTRY_WORDS : i64 = 16; const F32 : i64 = 0; const BF16 : i64 = 1; @@ -66,6 +70,19 @@ struct Config { moe_intermediate_size : i32, // Whether an RMSNorm over each head of Q and of K comes before RoPE. qk_norm : bool, + // The fields from here to rotary_dim are in a version 2 file only, and 0 in a version 1 file. + arch : i32, + // In arch 1, layer l has full attention when (l + 1) % full_attention_interval is 0, and a + // Gated DeltaNet otherwise. + full_attention_interval : i32, + linear_k_heads : i32, + linear_v_heads : i32, + linear_k_dim : i32, + linear_v_dim : i32, + conv_width : i32, + shared_expert_inter : i32, + // RoPE turns the first rotary_dim values of each head: head_dim in a version 1 file. + rotary_dim : i32, rope_theta : f64, rms_norm_eps : f64, } @@ -118,6 +135,46 @@ struct Weights { lm_head : WeightMatrix, } +/// The weights of one layer of an arch 1 model (Qwen3.5 MoE), in GPU memory. Each norm except +/// `linear_norm` holds 1 + w as f32, so that a plain RMSNorm multiplies by it. A layer with full +/// attention fills the fields up to `attn_out`, and a Gated DeltaNet layer the fields from +/// `linear_in` to `linear_out`. The other ones hold one row of zeros. +struct Qwen35Layer { + full_attention : bool, + attn_norm : Tensor, + // The rows of q, k and v, then the rows of the gate of each query head. + qkv : WeightMatrix, + q_norm : Tensor, + k_norm : Tensor, + attn_out : WeightMatrix, + // The rows of q, k, v, z, b and a. + linear_in : WeightMatrix, + // The causal convolution of q, k and v: channel c at c * conv_width, and its last value + // multiplies the current token. + conv : Tensor, + neg_a : Tensor, + dt_bias : Tensor, + // The RMSNorm of each head of the output. It holds w, not 1 + w. + linear_norm : Tensor, + linear_out : WeightMatrix, + mlp_norm : Tensor, + // One row for each expert, then the gate of the shared expert. + router : Tensor, + gate_up : WeightMatrix, + down : WeightMatrix, + shared_gate_up : WeightMatrix, + shared_down : WeightMatrix, +} + +/// All the weights of an arch 1 model, in GPU memory. +struct Qwen35Weights { + config : Config, + embed : Tensor, + layers : Vec, + final_norm : Tensor, + lm_head : WeightMatrix, +} + /// A weight file mapped into memory, and the position of the next tensor to load. struct Reader { base : *mut i8, @@ -125,6 +182,8 @@ struct Reader { table : i64, count : i64, next : i64, + fd : i32, + version : i64, } /// The i64 word at `index` of the file. @@ -209,7 +268,8 @@ fn load_f16(r : &mut Reader, kind : *const i8, rows : i32, cols : i32) -> Tensor return transfer(&view, Memory::HBM); } -/// Puts the next tensor, of f32 values, in GPU memory. +/// Puts the next tensor, of f32 values, in GPU memory: scales, or a norm or other small tensor +/// of arch 1. fn load_scales(r : &mut Reader, kind : *const i8, rows : i32, cols : i32) -> Tensor { let offset = next_tensor(r, kind, F32, 32, rows, cols); let count = values(rows, cols); @@ -292,8 +352,8 @@ fn map_failed(p : *mut i8) -> bool { return eq(p as *const i8, failed as *const i8); } -/// Loads the weight file at `path` into GPU memory. -fn load_weights(path : *const i8) -> Weights { +/// Maps the weight file at `path` into memory, and checks its magic word and version. +fn open_weight_file(path : *const i8) -> Reader { let fd : i32 = unsafe { open(path, 0) }; assert(fd >= 0, "cannot open the weight file"); let size : i64 = unsafe { lseek(fd, 0, 2) }; @@ -301,36 +361,208 @@ fn load_weights(path : *const i8) -> Weights { let base : *mut i8 = unsafe { mmap(0 as *mut i8, size, 1, 1, fd, 0) }; assert(!map_failed(base), "cannot map the weight file into memory"); let mut r = Reader { - base: base, size: size, table: 0, count: 0, next: 0 + base: base, size: size, table: 0, count: 0, next: 0, fd: fd, version: 0 }; assert(size >= 4096 && word(&r, 0) == MAGIC, "this is not a weight file of the Qwen app"); - assert(word(&r, 1) == VERSION, "the weight file has another format version"); + r.version = word(&r, 1); + assert(r.version == VERSION_1 || r.version == VERSION_2, "the weight file has another format version"); r.count = word(&r, 2); r.table = word(&r, 4); + return r; +} + +/// Unmaps the weight file. The tensors in GPU memory stay. +fn close_weight_file(r : &Reader) -> void { + unsafe { munmap(r.base, r.size); close(r.fd); } + return; +} + +/// Config integer `index` of a version 2 file, or `otherwise` in a version 1 file, which has no +/// room for it. +fn v2_int(r : &Reader, index : i64, otherwise : i32) -> i32 { + if r.version == VERSION_1 { + return otherwise; + } + return word(r, 5 + index) as i32; +} - let floats : *mut f64 = base; +/// The config in the header of the weight file. +fn read_config(r : &Reader) -> Config { + let floats : *mut f64 = r.base; + // Words 5 and up hold the config integers, and the two f64 values follow the room for them. + let floats_at : i64 = if r.version == VERSION_1 { + 5 + 16 + } else { + 5 + 32 + }; + let head_dim = word(r, 10) as i32; let config = Config { - hidden_size: word(&r, 5) as i32, - intermediate_size: word(&r, 6) as i32, - num_layers: word(&r, 7) as i32, - num_q_heads: word(&r, 8) as i32, - num_kv_heads: word(&r, 9) as i32, - head_dim: word(&r, 10) as i32, - vocab_size: word(&r, 11) as i32, - max_positions: word(&r, 12) as i32, - tied_embeddings: word(&r, 13) != 0, - qkv_bias: word(&r, 14) != 0, - eos_token_id: word(&r, 15) as i32, - weight_format: word(&r, 16) as i32, - num_experts: word(&r, 17) as i32, - experts_per_token: word(&r, 18) as i32, - moe_intermediate_size: word(&r, 19) as i32, - qk_norm: word(&r, 20) != 0, - rope_theta: unsafe { floats[21] }, - rms_norm_eps: unsafe { floats[22] }, + hidden_size: word(r, 5) as i32, + intermediate_size: word(r, 6) as i32, + num_layers: word(r, 7) as i32, + num_q_heads: word(r, 8) as i32, + num_kv_heads: word(r, 9) as i32, + head_dim: head_dim, + vocab_size: word(r, 11) as i32, + max_positions: word(r, 12) as i32, + tied_embeddings: word(r, 13) != 0, + qkv_bias: word(r, 14) != 0, + eos_token_id: word(r, 15) as i32, + weight_format: word(r, 16) as i32, + num_experts: word(r, 17) as i32, + experts_per_token: word(r, 18) as i32, + moe_intermediate_size: word(r, 19) as i32, + qk_norm: word(r, 20) != 0, + arch: v2_int(r, 16, 0), + full_attention_interval: v2_int(r, 17, 0), + linear_k_heads: v2_int(r, 18, 0), + linear_v_heads: v2_int(r, 19, 0), + linear_k_dim: v2_int(r, 20, 0), + linear_v_dim: v2_int(r, 21, 0), + conv_width: v2_int(r, 22, 0), + shared_expert_inter: v2_int(r, 24, 0), + rotary_dim: v2_int(r, 23, head_dim), + rope_theta: unsafe { floats[floats_at] }, + rms_norm_eps: unsafe { floats[floats_at + 1] }, }; assert(config.weight_format >= FORMAT_BF16 && config.weight_format <= FORMAT_Q4_0_Q6, "the weight file has an unknown weight format"); assert(config.num_experts == 0 || (config.experts_per_token > 0 && config.experts_per_token <= config.num_experts), "a model must use between 1 and all of its experts for each token"); + assert((r.version == VERSION_2) == (config.arch == ARCH_QWEN35), "an arch 1 model needs a version 2 file, and only it"); + return config; +} + +/// The arch of the model in the weight file at `path`: 0 for `load_weights`, and 1 for +/// `load_qwen35_weights`. It reads only the header. +fn weight_file_arch(path : *const i8) -> i32 { + let r = open_weight_file(path); + let arch = read_config(&r).arch; + close_weight_file(&r); + return arch; +} + +/// A weight matrix that a layer does not have: one row of bf16 zeros. +fn empty_matrix() -> WeightMatrix { + return WeightMatrix { + dtype: BF16, bf16: zeros(8), codes: zero_words(8), high: zero_words(8), scales: zero_scales(8), group_scales: zero_f16(8) + }; +} + +/// Loads the weight file at `path`, of an arch 1 model, into GPU memory. +fn load_qwen35_weights(path : *const i8) -> Qwen35Weights { + let mut r = open_weight_file(path); + let config = read_config(&r); + assert(config.arch == ARCH_QWEN35, "this weight file is not of a Qwen3.5 MoE model; use load_weights"); + assert(config.full_attention_interval > 0 && config.num_experts > 0 && config.shared_expert_inter > 0, "a Qwen3.5 MoE model has full attention layers, experts and a shared expert"); + assert(config.linear_k_heads > 0 && config.linear_v_heads % config.linear_k_heads == 0, "each key head of a Gated DeltaNet must serve the same number of value heads"); + assert(!config.tied_embeddings, "a Qwen3.5 MoE weight file has its own lm_head"); + let hidden = config.hidden_size; + let head_dim = config.head_dim; + let heads = config.num_q_heads; + let k_total = config.linear_k_heads * config.linear_k_dim; + let v_heads = config.linear_v_heads; + let v_total = v_heads * config.linear_v_dim; + let experts = config.num_experts; + let moe_inter = config.moe_intermediate_size; + let shared = config.shared_expert_inter; + let dtype = matrix_dtype(config.weight_format, false); + let embed = load_next(&mut r, "embed", config.vocab_size, hidden); + let mut layers = Vec::new(); + for l in 0..config.num_layers { + // The tensors come in file order: those of the attention or the Gated DeltaNet, then those + // of the experts. + let full = (l + 1) % config.full_attention_interval == 0; + let attn_norm = load_scales(&mut r, ".attn_norm", hidden, 0); + let qkv = if full { + load_matrix(&mut r, dtype, ".qkv", ".qkv.scale", 2 * heads * head_dim + 2 * config.num_kv_heads * head_dim, hidden) + } else { + empty_matrix() + }; + let q_norm = if full { + load_scales(&mut r, ".q_norm", head_dim, 0) + } else { + zero_scales(8) + }; + let k_norm = if full { + load_scales(&mut r, ".k_norm", head_dim, 0) + } else { + zero_scales(8) + }; + let attn_out = if full { + load_matrix(&mut r, dtype, ".attn_out", ".attn_out.scale", hidden, heads * head_dim) + } else { + empty_matrix() + }; + let linear_in = if full { + empty_matrix() + } else { + load_matrix(&mut r, dtype, ".linear_in", ".linear_in.scale", 2 * k_total + 2 * v_total + 2 * v_heads, hidden) + }; + let conv = if full { + zero_scales(8) + } else { + load_scales(&mut r, ".conv", 2 * k_total + v_total, config.conv_width) + }; + let neg_a = if full { + zero_scales(8) + } else { + load_scales(&mut r, ".neg_A", v_heads, 0) + }; + let dt_bias = if full { + zero_scales(8) + } else { + load_scales(&mut r, ".dt_bias", v_heads, 0) + }; + let linear_norm = if full { + zero_scales(8) + } else { + load_scales(&mut r, ".linear_norm", config.linear_v_dim, 0) + }; + let linear_out = if full { + empty_matrix() + } else { + load_matrix(&mut r, dtype, ".linear_out", ".linear_out.scale", hidden, v_total) + }; + let mlp_norm = load_scales(&mut r, ".mlp_norm", hidden, 0); + let router = load_next(&mut r, ".router", experts + 1, hidden); + let gate_up = load_matrix(&mut r, dtype, ".experts_gate_up", ".experts_gate_up.scale", experts * 2 * moe_inter, hidden); + let down = load_matrix(&mut r, dtype, ".experts_down", ".experts_down.scale", experts * hidden, moe_inter); + let shared_gate_up = load_matrix(&mut r, dtype, ".shared_gate_up", ".shared_gate_up.scale", 2 * shared, hidden); + let shared_down = load_matrix(&mut r, dtype, ".shared_down", ".shared_down.scale", hidden, shared); + layers.push(Qwen35Layer { + full_attention: full, + attn_norm: attn_norm, + qkv: qkv, + q_norm: q_norm, + k_norm: k_norm, + attn_out: attn_out, + linear_in: linear_in, + conv: conv, + neg_a: neg_a, + dt_bias: dt_bias, + linear_norm: linear_norm, + linear_out: linear_out, + mlp_norm: mlp_norm, + router: router, + gate_up: gate_up, + down: down, + shared_gate_up: shared_gate_up, + shared_down: shared_down, + }); + } + let final_norm = load_scales(&mut r, "final_norm", hidden, 0); + let lm_head = load_matrix(&mut r, matrix_dtype(config.weight_format, true), "lm_head", "lm_head.scale", config.vocab_size, hidden); + assert(r.next == r.count, "the weight file has more tensors than the config needs"); + close_weight_file(&r); + return Qwen35Weights { + config: config, embed: embed, layers: layers, final_norm: final_norm, lm_head: lm_head + }; +} + +/// Loads the weight file at `path`, of an arch 0 model, into GPU memory. +fn load_weights(path : *const i8) -> Weights { + let mut r = open_weight_file(path); + let config = read_config(&r); + assert(config.arch == 0, "this weight file is of a Qwen3.5 MoE model; use load_qwen35_weights"); let hidden = config.hidden_size; let q_rows = config.num_q_heads * config.head_dim; @@ -392,14 +624,12 @@ fn load_weights(path : *const i8) -> Weights { let final_norm = load_next(&mut r, "final_norm", hidden, 0); assert(config.weight_format == FORMAT_BF16 || !config.tied_embeddings, "an fp8 or Q4_0 weight file must have its own lm_head"); let lm_head = if config.tied_embeddings { - WeightMatrix { - dtype: BF16, bf16: zeros(8), codes: zero_words(8), high: zero_words(8), scales: zero_scales(8), group_scales: zero_f16(8) - } + empty_matrix() } else { load_matrix(&mut r, matrix_dtype(config.weight_format, true), "lm_head", "lm_head.scale", config.vocab_size, hidden) }; assert(r.next == r.count, "the weight file has more tensors than the config needs"); - unsafe { munmap(base, size); close(fd); } + close_weight_file(&r); return Weights { config: config, embed: embed, layers: layers, final_norm: final_norm, lm_head: lm_head }; diff --git a/tests/print_qwen35_weights.vx b/tests/print_qwen35_weights.vx new file mode 100644 index 0000000..db69725 --- /dev/null +++ b/tests/print_qwen35_weights.vx @@ -0,0 +1,176 @@ +// Loads the weight file of a Qwen3.5 MoE model (arch 1, format version 2) into GPU memory, copies +// each tensor back, and prints its first codes and the sum of all its codes, as +// print_weights.vx does for the older models. `reference.py --tensors` prints the same lines +// from the file, so no output of `diff` means that each tensor reached GPU memory whole and in +// the right place. The first line also gives the config of version 2. The tiny model is in bf16, +// then in Q4_0 with a 6-bit lm_head. +// +// RUN: python3 %S/../scripts/make_tiny_model.py --qwen35 %t.vxw > /dev/null +// RUN: vxc %s --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx -- %t.vxw | grep -v -e '^\[JIT\]' -e '^$' > %t.out +// RUN: head -1 %t.out | FileCheck %s +// RUN: python3 %S/../scripts/reference.py %t.vxw --tensors | diff - <(tail -n +2 %t.out) +// RUN: python3 %S/../scripts/make_tiny_model.py --qwen35 --q4 --q6-lm-head %t-q4.vxw > /dev/null +// RUN: vxc %s --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx -- %t-q4.vxw | grep -v -e '^\[JIT\]' -e '^$' > %t-q4.out +// RUN: python3 %S/../scripts/reference.py %t-q4.vxw --tensors | diff - <(tail -n +2 %t-q4.out) +// +// CHECK: {{^}}arch=1 interval=4 k_heads=2 v_heads=4 k_dim=128 v_dim=128 conv=4 shared=128 rotary=64 full=3;{{$}} + +import qwen::weights; +import core::num; +import core::convert; + +/// The 16 bits of a bf16 value. +fn code(v : bf16) -> u32 { + return (v as f32).to_bits() >> 16; +} + +/// Prints `name count=N codes=a,b,c,d sum=S;`, with the first `shown` codes of `first`. +fn print_line(name : *const i8, layer : i32, count : i64, first : &Tensor, shown : i32, sum : u64) -> void { + if layer >= 0 { + print!("layers.{}.", layer); + } + print!("{} count={} codes=", name, count); + for i in 0..shown { + if i > 0 { + print!(","); + } + print!("{}", first[i]); + } + println!(" sum={};", sum); + return; +} + +/// The line of a tensor of bf16 values in GPU memory. A code is the 16 bits of a value. +fn report(name : *const i8, layer : i32, t : &Tensor) -> void { + let h = transfer(t, Memory::CPU_DRAM); + let n = h.len(); + let mut first = Tensor([4]); + let mut sum : u64 = 0; + for i in 0..n { + if i < 4 { + first[i] = code(h[i]); + } + sum = sum + u64::from(code(h[i])); + } + print_line(name, layer, i64::from(n), &first, i32::min(n, 4), sum); + return; +} + +/// The line of a tensor of codes in GPU memory, 4 bytes in each u32 word: Q4_0 codes, two in each +/// byte, or the high 2 bits of 6-bit codes, four in each byte. A code here is one byte. +fn report_codes(name : *const i8, layer : i32, t : &Tensor) -> void { + let h = transfer(t, Memory::CPU_DRAM); + let n = h.len(); + let mut first = Tensor([4]); + for k in 0..4 { + first[k] = (h[0] >> ((8 * k) as u32)) & 255u32; + } + let mut sum : u64 = 0; + for i in 0..n { + let w = h[i]; + sum = sum + u64::from((w & 255u32) + ((w >> 8u32) & 255u32) + ((w >> 16u32) & 255u32) + (w >> 24u32)); + } + print_line(name, layer, 4 * i64::from(n), &first, 4, sum); + return; +} + +/// The line of a tensor of f32 values in GPU memory. A code is the 32 bits of a value. +fn report_f32(name : *const i8, layer : i32, t : &Tensor) -> void { + let h = transfer(t, Memory::CPU_DRAM); + let n = h.len(); + let mut first = Tensor([4]); + let mut sum : u64 = 0; + for i in 0..n { + if i < 4 { + first[i] = h[i].to_bits(); + } + sum = sum + u64::from(h[i].to_bits()); + } + print_line(name, layer, i64::from(n), &first, i32::min(n, 4), sum); + return; +} + +/// The line of a tensor of f16 scales in GPU memory. A code is the 16 bits of a value. +fn report_f16(name : *const i8, layer : i32, t : &Tensor) -> void { + let h = transfer(t, Memory::CPU_DRAM); + let n = h.len(); + // A plain host tensor, whose memory a pointer can read as u16 bits. + let mut plain = Tensor([n]); + for i in 0..n { + plain[i] = h[i]; + } + let raw : *mut i8 = plain.as_mut_ptr(); + let bits : *mut u16 = raw; + let mut first = Tensor([4]); + let mut sum : u64 = 0; + for i in 0..n { + let code = u32::from(unsafe { bits[i] }); + if i < 4 { + first[i] = code; + } + sum = sum + u64::from(code); + } + print_line(name, layer, i64::from(n), &first, i32::min(n, 4), sum); + return; +} + +/// The lines of a weight matrix, as the file has its tensors: bf16 values, Q4_0 codes and their +/// scales, or the low 4 bits of 6-bit codes, their high 2 bits, and their scales. +fn report_matrix(name : *const i8, high_name : *const i8, scale_name : *const i8, layer : i32, m : &WeightMatrix) -> void { + if m.dtype == U4 { + report_codes(name, layer, &m.codes); + report_f16(scale_name, layer, &m.group_scales); + } else if m.dtype == U6 { + report_codes(name, layer, &m.codes); + report_codes(high_name, layer, &m.high); + report_f16(scale_name, layer, &m.group_scales); + } else { + assert(m.dtype == BF16, "the tiny Qwen3.5 files have no fp8 matrices"); + report(name, layer, &m.bf16); + } + return; +} + +fn main(argc : i32, argv : *mut *mut i8) -> i32 { + assert(argc == 2, "give the weight file as the only argument"); + let arch = weight_file_arch(unsafe { argv[1] }); + let w = load_qwen35_weights(unsafe { argv[1] }); + let c = &w.config; + let mut full = 0; + for l in 0..c.num_layers { + if w.layers[l].full_attention { + full = full + l; + } + } + println!("arch={} interval={} k_heads={} v_heads={} k_dim={} v_dim={} conv={} shared={} rotary={} full={};", + arch, c.full_attention_interval, c.linear_k_heads, c.linear_v_heads, c.linear_k_dim, c.linear_v_dim, c.conv_width, + c.shared_expert_inter, c.rotary_dim, full); + println!("config hidden={} layers={} vocab={};", c.hidden_size, c.num_layers, c.vocab_size); + report("embed", -1, &w.embed); + for l in 0..c.num_layers { + let layer = &w.layers[l]; + report_f32("attn_norm", l, &layer.attn_norm); + if layer.full_attention { + report_matrix("qkv", "qkv.high", "qkv.scale", l, &layer.qkv); + report_f32("q_norm", l, &layer.q_norm); + report_f32("k_norm", l, &layer.k_norm); + report_matrix("attn_out", "attn_out.high", "attn_out.scale", l, &layer.attn_out); + } else { + report_matrix("linear_in", "linear_in.high", "linear_in.scale", l, &layer.linear_in); + report_f32("conv", l, &layer.conv); + report_f32("neg_A", l, &layer.neg_a); + report_f32("dt_bias", l, &layer.dt_bias); + report_f32("linear_norm", l, &layer.linear_norm); + report_matrix("linear_out", "linear_out.high", "linear_out.scale", l, &layer.linear_out); + } + report_f32("mlp_norm", l, &layer.mlp_norm); + report("router", l, &layer.router); + report_matrix("experts_gate_up", "experts_gate_up.high", "experts_gate_up.scale", l, &layer.gate_up); + report_matrix("experts_down", "experts_down.high", "experts_down.scale", l, &layer.down); + report_matrix("shared_gate_up", "shared_gate_up.high", "shared_gate_up.scale", l, &layer.shared_gate_up); + report_matrix("shared_down", "shared_down.high", "shared_down.scale", l, &layer.shared_down); + } + report_f32("final_norm", -1, &w.final_norm); + report_matrix("lm_head", "lm_head.high", "lm_head.scale", -1, &w.lm_head); + return 0; +} From 2a2153727e4204bb24af138f2211cebf9f2bdad4 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:57:12 -0800 Subject: [PATCH 07/60] qwen app: the Gated DeltaNet of one token, for Qwen3.6 (#89) src/deltanet.vx runs the linear attention of a Qwen3.5/Qwen3.6 layer for one token, between the products linear_in and linear_out, with the math of transformers' modeling_qwen3_5_moe.py: the causal depthwise convolution of width 4 and SiLU, the L2 norms of q and k, beta and the decay, the update of the state S and q . S, and the gated RMS norm. Four kernels. In the update, a SIMD group does 32 values of v of one head, and lane l owns 4 values of k, so that the lanes read a row of S in one load. The state is [v_heads, v, k], k last. tests/deltanet.vx checks 6 tokens against the same math on the CPU, at the shapes of Qwen3.6-35B-A3B. Breaking the head map, the decay, the order of the taps or the scale of q makes it fail. On the M4, 30 layers take about 1.7 ms a token; the update of the state is 1.5 ms of it (2 MB read and written for each layer, about 80 GB/s). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- src/deltanet.vx | 244 ++++++++++++++++++++++++++++++++++++++++++++++ tests/deltanet.vx | 206 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 450 insertions(+) create mode 100644 src/deltanet.vx create mode 100644 tests/deltanet.vx diff --git a/src/deltanet.vx b/src/deltanet.vx new file mode 100644 index 0000000..985a288 --- /dev/null +++ b/src/deltanet.vx @@ -0,0 +1,244 @@ +//===- 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; + +/// The sum of `x` over the 32 lanes of a SIMD group. Each lane gets the sum. +fn dn_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 natural logarithm of x. (The Metal code generator of Vx v0.0.5 cannot print `math.log1p`.) +fn dn_log(x : f32) on Topology::Device -> f32 +ensures writes_only() +{ + return mlir!( inputs : (%x = x : f32), returns : f32, dialects : ["math"], ensures : [writes_only()]) { + %r = math.log %x : f32 + macro.yield %r : f32 + }; +} + +/// 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` is +/// [2 k_heads + v_heads, 4] times 128 channels, as [channel, tap], oldest tap first; `neg_a`, +/// `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.extent(0) == channels && conv.extent(1) == 4, "deltanet_step: conv must be [channels, 4]"); + 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][0] * x0 + conv[c][1] * x1 + conv[c][2] * x2 + conv[c][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 = dn_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 = dn_lane_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 = dn_lane_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/tests/deltanet.vx b/tests/deltanet.vx new file mode 100644 index 0000000..7af0a16 --- /dev/null +++ b/tests/deltanet.vx @@ -0,0 +1,206 @@ +//===- 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 +// +//===----------------------------------------------------------------------===// +// `deltanet_step` (src/deltanet.vx) against the same math on the CPU, for 6 tokens, with random +// values and the shapes of Qwen3.6-35B-A3B: 16 heads of q and k, 32 of v, 128 values each. A value +// is off when it differs from the CPU value by more than 2e-4 (1 + |value|). +// +// RUN: vxc %s --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx | FileCheck %s +// +// CHECK: {{^}}step 0: 0 off{{$}} +// CHECK: {{^}}step 1: 0 off{{$}} +// CHECK: {{^}}step 2: 0 off{{$}} +// CHECK: {{^}}step 3: 0 off{{$}} +// CHECK: {{^}}step 4: 0 off{{$}} +// CHECK: {{^}}step 5: 0 off{{$}} +// CHECK: {{^}}state: 0 off{{$}} +// CHECK: {{^}}conv state: 0 off{{$}} +import core::convert; +import core::num; +import std::nn; +import std::vec; +import qwen::deltanet; + +const K_HEADS : i32 = 16; +const V_HEADS : i32 = 32; +const STEPS : i32 = 6; + +/// A number in [-1, 1) from the state `s` of a linear congruential generator. +fn random(s : &mut i64) -> f32 { + *s = (*s * 1103515245 + 12345) % 2147483648; + return (*s as f32) / 1073741824.0 - 1.0; +} + +fn off(a : f32, b : f32) -> bool { + return (a - b).abs() > 0.0002 * (1.0 + b.abs()); +} + +fn silu(x : f32) -> f32 { + return x / (1.0 + (0.0 - x).exp()); +} + +fn main() -> i32 { + let mut seed : i64 = 7; + let s = &mut seed; + let heads = 2 * K_HEADS + V_HEADS; + let channels = heads * 128; + let z_at = channels; + let b_at = z_at + V_HEADS * 128; + let a_at = b_at + V_HEADS; + let width = a_at + V_HEADS; + let eps : f32 = 0.000001; + + let mut hconv = Tensor([channels, 4]); + for c in 0..channels { + for t in 0..4 { + hconv[c][t] = random(s) * 0.5; + } + } + let mut hneg_a = Tensor([V_HEADS]); + let mut hdt = Tensor([V_HEADS]); + for j in 0..V_HEADS { + hneg_a[j] = 0.0 - (random(s) * 2.0).exp(); + hdt[j] = random(s) * 2.0; + } + let mut hnorm = Tensor([128]); + for i in 0..128 { + hnorm[i] = 1.0 + random(s) * 0.5; + } + let conv = transfer(&hconv, Memory::HBM); + let neg_a = transfer(&hneg_a, Memory::HBM); + let dt_bias = transfer(&hdt, Memory::HBM); + let norm = transfer(&hnorm, Memory::HBM); + + let mut conv_state = deltanet_conv_state(K_HEADS, V_HEADS); + let mut state = deltanet_state(V_HEADS); + let mut t = deltanet_scratch(K_HEADS, V_HEADS); + let mut y = transfer(Tensor([V_HEADS * 128]), Memory::HBM); + + // The CPU state: the last 3 inputs of each channel, and S[h][k][v] as in transformers. + let mut cs = Vec::new(); + for i in 0..channels * 3 { + cs.push(0.0); + } + let mut cS = Vec::new(); + for i in 0..V_HEADS * 128 * 128 { + cS.push(0.0); + } + let group = V_HEADS / K_HEADS; + + for step in 0..STEPS { + let mut hproj = Tensor([width]); + for i in 0..width { + hproj[i] = random(s) * 2.0; + } + let proj = transfer(&hproj, Memory::HBM); + deltanet_step(&mut y, &mut conv_state, &mut state, &mut t, &proj, &conv, &neg_a, &dt_bias, &norm, z_at, b_at, a_at, K_HEADS, V_HEADS, eps); + + // The CPU: the convolution and the SiLU. + let mut x = Vec::new(); + for c in 0..channels { + let x0 = cs[c * 3]; + let x1 = cs[c * 3 + 1]; + let x2 = cs[c * 3 + 2]; + let x3 = hproj[c]; + x.push(silu(hconv[c][0] * x0 + hconv[c][1] * x1 + hconv[c][2] * x2 + hconv[c][3] * x3)); + cs[c * 3] = x1; + cs[c * 3 + 1] = x2; + cs[c * 3 + 2] = x3; + } + // The L2 norms of q and k, and the scale of q. + for h in 0..2 * K_HEADS { + let mut ss : f32 = 0.0; + for i in 0..128 { + ss = ss + x[h * 128 + i] * x[h * 128 + i]; + } + let inv = 1.0 / (ss + 0.000001).sqrt(); + for i in 0..128 { + let mut a = x[h * 128 + i] * inv; + if h < K_HEADS { + a = a * (1.0 / (128.0 as f32).sqrt()); + } + x[h * 128 + i] = a; + } + } + let mut yc = Vec::new(); + for h in 0..V_HEADS { + let g = h / group; + let q_at = g * 128; + let k_at = (K_HEADS + g) * 128; + let v_at = (2 * K_HEADS + h) * 128; + let beta = 1.0 / (1.0 + (0.0 - hproj[b_at + h]).exp()); + let xa = hproj[a_at + h] + hdt[h]; + let mut sp = xa; + if xa <= 20.0 { + sp = xa.exp().ln_1p(); + } + let decay = (hneg_a[h] * sp).exp(); + let base = h * 128 * 128; + for i in 0..128 * 128 { + cS[base + i] = cS[base + i] * decay; + } + let mut o = Vec::new(); + for v in 0..128 { + let mut mem : f32 = 0.0; + for k in 0..128 { + mem = mem + cS[base + k * 128 + v] * x[k_at + k]; + } + let delta = (x[v_at + v] - mem) * beta; + let mut out : f32 = 0.0; + for k in 0..128 { + let n = cS[base + k * 128 + v] + x[k_at + k] * delta; + cS[base + k * 128 + v] = n; + out = out + n * x[q_at + k]; + } + o.push(out); + } + let mut ss : f32 = 0.0; + for v in 0..128 { + ss = ss + o[v] * o[v]; + } + let inv = 1.0 / (ss / 128.0 + eps).sqrt(); + for v in 0..128 { + yc.push(o[v] * inv * hnorm[v] * silu(hproj[z_at + h * 128 + v])); + } + } + + let hy = transfer(&y, Memory::CPU_DRAM); + let mut count = 0; + for i in 0..V_HEADS * 128 { + if off(hy[i], yc[i]) { + count = count + 1; + } + } + println!("step {}: {} off", step, count); + } + + let hs = transfer(&state, Memory::CPU_DRAM); + let mut count = 0; + for h in 0..V_HEADS { + for v in 0..128 { + for k in 0..128 { + if off(hs[h][v][k], cS[h * 128 * 128 + k * 128 + v]) { + count = count + 1; + } + } + } + } + println!("state: {} off", count); + let hc = transfer(&conv_state, Memory::CPU_DRAM); + count = 0; + for h in 0..heads { + for i in 0..128 { + for j in 0..3 { + if hc[h][i][j] != cs[(h * 128 + i) * 3 + j] { + count = count + 1; + } + } + } + } + println!("conv state: {} off", count); + return 0; +} From f4740e3c0dbd3bb7997510dde7ab32f345cd0325 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:00:03 -0800 Subject: [PATCH 08/60] qwen app: the gated full attention of one token, for Qwen3.6 (#89) src/gated_attention.vx runs the full attention of a Qwen3.5/Qwen3.6 layer for one token, between the products qkv and attn_out: - gated_norm_rope_and_store: the RMS norms of the q and k heads (256 values, weights stored as 1 + w), RoPE on the first `rot` values of each head, and the store of k and v into the f16 caches. - gated_attention: the attention with the scale 1/16, in the design of vec_attention (llama.cpp's kernel_flash_attn_ext_vec) for 256 values a head, with 8 values for each lane; then the merge, which multiplies by sigmoid(gate). src/simd.vx holds the small mlir! functions of both new files (a sum, a largest value and a value across the lanes, a load of 4 halves, the logarithm). They are those of #87, under other names. tests/gated_attention.vx checks positions 0, 37, 700, 2047 and 2100 against the same math on the CPU, at the shapes of Qwen3.6-35B-A3B. A wrong RoPE sign, head map, gate offset or norm weight makes it fail. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- src/deltanet.vx | 27 +--- src/gated_attention.vx | 257 +++++++++++++++++++++++++++++++++++++++ src/simd.vx | 72 +++++++++++ tests/gated_attention.vx | 181 +++++++++++++++++++++++++++ 4 files changed, 514 insertions(+), 23 deletions(-) create mode 100644 src/gated_attention.vx create mode 100644 src/simd.vx create mode 100644 tests/gated_attention.vx diff --git a/src/deltanet.vx b/src/deltanet.vx index 985a288..327a603 100644 --- a/src/deltanet.vx +++ b/src/deltanet.vx @@ -25,26 +25,7 @@ // a SIMD group read them in one load. Both start at zero. import core::num; import std::nn; - -/// The sum of `x` over the 32 lanes of a SIMD group. Each lane gets the sum. -fn dn_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 natural logarithm of x. (The Metal code generator of Vx v0.0.5 cannot print `math.log1p`.) -fn dn_log(x : f32) on Topology::Device -> f32 -ensures writes_only() -{ - return mlir!( inputs : (%x = x : f32), returns : f32, dialects : ["math"], ensures : [writes_only()]) { - %r = math.log %x : f32 - macro.yield %r : f32 - }; -} +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 @@ -160,7 +141,7 @@ fn deltanet_gates(beta : &mut Tensor, decay : &mut Tensor let x = proj[a_at + j] + dt_bias[j]; let mut sp = x; if x <= 20.0 { - sp = dn_log(1.0 + x.fast_exp()); + sp = simd_log(1.0 + x.fast_exp()); } decay[j] = (neg_a[j] * sp).fast_exp(); } @@ -199,7 +180,7 @@ fn deltanet_recur(o : &mut Tensor, state : &mut Tensor 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 = dn_lane_sum(s0 * k0 + s1 * k1 + s2 * k2 + s3 * k3); + 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; @@ -209,7 +190,7 @@ fn deltanet_recur(o : &mut Tensor, state : &mut Tensor state[h][v][d + 1] = n1; state[h][v][d + 2] = n2; state[h][v][d + 3] = n3; - let out = dn_lane_sum(n0 * q0 + n1 * q1 + n2 * q2 + n3 * q3); + let out = simd_sum(n0 * q0 + n1 * q1 + n2 * q2 + n3 * q3); if m == l { mine = out; } diff --git a/src/gated_attention.vx b/src/gated_attention.vx new file mode 100644 index 0000000..a6dd3ed --- /dev/null +++ b/src/gated_attention.vx @@ -0,0 +1,257 @@ +//===- 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; +} diff --git a/src/simd.vx b/src/simd.vx new file mode 100644 index 0000000..7273c7e --- /dev/null +++ b/src/simd.vx @@ -0,0 +1,72 @@ +//===- simd.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 +// +//===----------------------------------------------------------------------===// +// Small `mlir!` functions for the operations that a kernel of Vx v0.0.5 cannot write: a sum, a +// largest value or a value across the 32 lanes of a SIMD group, a load of 4 halves in 8 bytes, and +// the logarithm. The kernels of Qwen3.6 (#89) use them. They are the same as the functions of +// src/attention.vx in vx-lang/qwen-vx#87, under other names; one copy should go when both merge. +import core::num; + +/// The sum of `x` over the 32 lanes of a SIMD group. Each lane gets the sum. +fn simd_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 simd_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 simd_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 + }; +} + +/// 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 half4_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 + }; +} + +/// The natural logarithm of x. (The Metal code generator of Vx v0.0.5 cannot print `math.log1p`.) +fn simd_log(x : f32) on Topology::Device -> f32 +ensures writes_only() +{ + return mlir!( inputs : (%x = x : f32), returns : f32, dialects : ["math"], ensures : [writes_only()]) { + %r = math.log %x : f32 + macro.yield %r : f32 + }; +} diff --git a/tests/gated_attention.vx b/tests/gated_attention.vx new file mode 100644 index 0000000..60d64e1 --- /dev/null +++ b/tests/gated_attention.vx @@ -0,0 +1,181 @@ +//===- 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 +// +//===----------------------------------------------------------------------===// +// `gated_norm_rope_and_store` and `gated_attention` (src/gated_attention.vx) against the same math +// on the CPU, with random values and the shapes of Qwen3.6-35B-A3B: 16 heads of q, 2 of k and v, 256 +// values a head, RoPE on the first 64. The cache holds random rows before the position. The cases +// are position 0, positions in the first blocks, and positions past 2,048, where the attention goes +// from 32 to 64 SIMD groups for each head. A value is off when it differs from the CPU value by more +// than 1e-3 (1 + |value|); the cache is f16. +// +// RUN: vxc %s --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx | FileCheck %s +// +// CHECK: {{^}}pos 0: q 0 off, cache 0 off, y 0 off{{$}} +// CHECK: {{^}}pos 37: q 0 off, cache 0 off, y 0 off{{$}} +// CHECK: {{^}}pos 700: q 0 off, cache 0 off, y 0 off{{$}} +// CHECK: {{^}}pos 2047: q 0 off, cache 0 off, y 0 off{{$}} +// CHECK: {{^}}pos 2100: q 0 off, cache 0 off, y 0 off{{$}} +import core::convert; +import core::num; +import std::nn; +import std::vec; +import qwen::gated_attention; + +const Q_HEADS : i32 = 16; +const KV_HEADS : i32 = 2; +const ROT : i32 = 64; +const MAX_SEQ : i32 = 2112; + +/// A number in [-1, 1) from the state `s` of a linear congruential generator. +fn random(s : &mut i64) -> f32 { + *s = (*s * 1103515245 + 12345) % 2147483648; + return (*s as f32) / 1073741824.0 - 1.0; +} + +fn off(a : f32, b : f32) -> bool { + return (a - b).abs() > 0.001 * (1.0 + b.abs()); +} + +fn check(s : &mut i64, pos : i32) -> void { + let width = (2 * Q_HEADS + 2 * KV_HEADS) * 256; + let eps : f32 = 0.000001; + let mut hk = Tensor([MAX_SEQ, KV_HEADS, 256]); + let mut hv = Tensor([MAX_SEQ, KV_HEADS, 256]); + for p in 0..MAX_SEQ { + for g in 0..KV_HEADS { + for i in 0..256 { + hk[p][g][i] = (random(s) * 2.0) as f16; + hv[p][g][i] = random(s) as f16; + } + } + } + let mut hx = Tensor([width]); + for i in 0..width { + hx[i] = random(s) * 2.0; + } + let mut hqn = Tensor([256]); + let mut hkn = Tensor([256]); + for i in 0..256 { + hqn[i] = 1.0 + random(s) * 0.5; + hkn[i] = 1.0 + random(s) * 0.5; + } + let mut hcos = Tensor([MAX_SEQ, ROT / 2]); + let mut hsin = Tensor([MAX_SEQ, ROT / 2]); + for p in 0..MAX_SEQ { + for i in 0..ROT / 2 { + hcos[p][i] = random(s); + hsin[p][i] = random(s); + } + } + let mut k_cache = transfer(&hk, Memory::HBM); + let mut v_cache = transfer(&hv, Memory::HBM); + let qkvg = transfer(&hx, Memory::HBM); + let q_norm = transfer(&hqn, Memory::HBM); + let k_norm = transfer(&hkn, Memory::HBM); + let cos = transfer(&hcos, Memory::HBM); + let sin = transfer(&hsin, Memory::HBM); + let mut q = transfer(Tensor([Q_HEADS, 256]), Memory::HBM); + let mut y = transfer(Tensor([Q_HEADS * 256]), Memory::HBM); + let mut part = transfer(gated_attention_scratch(Q_HEADS), Memory::HBM); + gated_norm_rope_and_store(&mut q, &mut k_cache, &mut v_cache, &qkvg, &q_norm, &k_norm, &cos, &sin, pos, Q_HEADS, KV_HEADS, ROT, eps); + gated_attention(&mut y, &mut part, &q, &k_cache, &v_cache, &qkvg, pos, Q_HEADS, KV_HEADS); + + // The CPU: the norms and RoPE of the q heads and k heads. + let mut r = Vec::new(); + let half = ROT / 2; + for h in 0..Q_HEADS + KV_HEADS { + let mut ss : f32 = 0.0; + for i in 0..256 { + ss = ss + hx[h * 256 + i] * hx[h * 256 + i]; + } + let inv = 1.0 / (ss / 256.0 + eps).sqrt(); + let mut n = Vec::new(); + for i in 0..256 { + let mut w = hqn[i]; + if h >= Q_HEADS { + w = hkn[i]; + } + n.push(hx[h * 256 + i] * inv * w); + } + for i in 0..256 { + let mut a = n[i]; + if i < half { + a = n[i] * hcos[pos][i] - n[i + half] * hsin[pos][i]; + } else if i < ROT { + a = n[i] * hcos[pos][i - half] + n[i - half] * hsin[pos][i - half]; + } + r.push(a); + } + } + let hq = transfer(&q, Memory::CPU_DRAM); + let mut q_off = 0; + for h in 0..Q_HEADS { + for i in 0..256 { + if off(hq[h][i], r[h * 256 + i]) { + q_off = q_off + 1; + } + } + } + let hkc = transfer(&k_cache, Memory::CPU_DRAM); + let hvc = transfer(&v_cache, Memory::CPU_DRAM); + let mut cache_off = 0; + for g in 0..KV_HEADS { + for i in 0..256 { + if off(hkc[pos][g][i] as f32, r[(Q_HEADS + g) * 256 + i]) { + cache_off = cache_off + 1; + } + if (hvc[pos][g][i] as f32) != ((hx[(Q_HEADS + KV_HEADS + g) * 256 + i] as f16) as f32) { + cache_off = cache_off + 1; + } + } + } + // The attention over rows 0 to pos of the caches that the kernel wrote, then the gate. + let hy = transfer(&y, Memory::CPU_DRAM); + let mut y_off = 0; + for h in 0..Q_HEADS { + let g = h / (Q_HEADS / KV_HEADS); + let mut scores = Vec::new(); + let mut big : f32 = -3.0e38; + for p in 0..pos + 1 { + let mut dot : f32 = 0.0; + for i in 0..256 { + dot = dot + r[h * 256 + i] * (hkc[p][g][i] as f32); + } + let sc = dot * 0.0625; + scores.push(sc); + big = big.max(sc); + } + let mut total : f32 = 0.0; + for p in 0..pos + 1 { + scores[p] = (scores[p] - big).exp(); + total = total + scores[p]; + } + for i in 0..256 { + let mut acc : f32 = 0.0; + for p in 0..pos + 1 { + acc = acc + scores[p] * (hvc[p][g][i] as f32); + } + let gate = hx[(Q_HEADS + 2 * KV_HEADS + h) * 256 + i]; + let want = acc / total / (1.0 + (0.0 - gate).exp()); + if off(hy[h * 256 + i], want) { + y_off = y_off + 1; + } + } + } + println!("pos {}: q {} off, cache {} off, y {} off", pos, q_off, cache_off, y_off); + return; +} + +fn main() -> i32 { + let mut seed : i64 = 11; + check(&mut seed, 0); + check(&mut seed, 37); + check(&mut seed, 700); + check(&mut seed, 2047); + check(&mut seed, 2100); + return 0; +} From c1834656f80efc355c9c5c9331c02a80f21e7151 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:17:28 -0800 Subject: [PATCH 09/60] qwen app: conv of the DeltaNet as 4 taps for each channel in one row, as weight file v2 stores it Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- src/deltanet.vx | 14 +++++++------- tests/deltanet.vx | 6 +++--- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/deltanet.vx b/src/deltanet.vx index 327a603..75310eb 100644 --- a/src/deltanet.vx +++ b/src/deltanet.vx @@ -73,15 +73,15 @@ fn deltanet_state(v_heads : i32) -> Tensor { } /// 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` is -/// [2 k_heads + v_heads, 4] times 128 channels, as [channel, tap], oldest tap first; `neg_a`, -/// `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 { +/// (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.extent(0) == channels && conv.extent(1) == 4, "deltanet_step: conv must be [channels, 4]"); + 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); @@ -94,7 +94,7 @@ fn deltanet_step(y : &mut Tensor, conv_state : &mut Tenso /// 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 { +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() }; @@ -105,7 +105,7 @@ fn deltanet_conv(qn : &mut Tensor, kn : &mut Tensor i32 { let width = a_at + V_HEADS; let eps : f32 = 0.000001; - let mut hconv = Tensor([channels, 4]); + let mut hconv = Tensor([channels * 4]); for c in 0..channels { for t in 0..4 { - hconv[c][t] = random(s) * 0.5; + hconv[c * 4 + t] = random(s) * 0.5; } } let mut hneg_a = Tensor([V_HEADS]); @@ -106,7 +106,7 @@ fn main() -> i32 { let x1 = cs[c * 3 + 1]; let x2 = cs[c * 3 + 2]; let x3 = hproj[c]; - x.push(silu(hconv[c][0] * x0 + hconv[c][1] * x1 + hconv[c][2] * x2 + hconv[c][3] * x3)); + x.push(silu(hconv[c * 4] * x0 + hconv[c * 4 + 1] * x1 + hconv[c * 4 + 2] * x2 + hconv[c * 4 + 3] * x3)); cs[c * 3] = x1; cs[c * 3 + 1] = x2; cs[c * 3 + 2] = x3; From a86dc7e6817da7e823344858ecd7f0a331fc9c43 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:18:50 -0800 Subject: [PATCH 10/60] qwen app: draft of the token loop of Qwen3.5/Qwen3.6, on the structs planned for weight file v2 (#89, #90) It does not compile yet: Qwen35Weights, Qwen35Layer and the new Config fields come with the v2 loader of #90. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- src/qwen35.vx | 231 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 231 insertions(+) create mode 100644 src/qwen35.vx diff --git a/src/qwen35.vx b/src/qwen35.vx new file mode 100644 index 0000000..071368c --- /dev/null +++ b/src/qwen35.vx @@ -0,0 +1,231 @@ +//===- qwen35.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 Qwen3.5 or Qwen3.6 MoE decoder (arch 1 of weight file v2, #89) on the GPU. Each +// layer is a Gated DeltaNet (src/deltanet.vx) or, every `full_attention_interval` layers, a gated +// full attention (src/gated_attention.vx). Then a mixture of experts with a shared expert. +// +// `Qwen35State` holds every tensor that a token writes, and the state of each layer: the +// convolution inputs and S of a DeltaNet layer, or the KV cache of a full attention layer. 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::deltanet; +import qwen::gated_attention; +import qwen::model; +import qwen::products; +import qwen::weights; + +/// The state of one layer. A DeltaNet layer has `conv` and `s`, a full attention layer `k` and `v`; +/// the others have one value each. +struct Qwen35LayerState { + conv : Tensor, + s : Tensor, + k : Tensor, + v : Tensor, +} + +/// The tensors that a token writes, in GPU memory. `proj` is the output of `qkv` or `linear_in`, and +/// `y` the input of `attn_out` or `linear_out`. `cos` and `sin` are [max_seq, rotary_dim / 2]. +struct Qwen35State { + max_seq : i32, + x : Tensor, + xn : Tensor, + proj : Tensor, + y : Tensor, + q : Tensor, + parts : Tensor, + dn : DeltaNetScratch, + experts : Experts, + // The shared expert: its id (0), the sigmoid of its gate, and its SwiGLU output [1, inter]. + shared_id : Tensor, + shared_weight : Tensor, + shared_mlp : Tensor, + logits : Tensor, + cos : Tensor, + sin : Tensor, + layers : Vec, +} + +fn zeros_f32(n : i32) -> Tensor { + let mut x = Tensor([n]); + for i in 0..n { + x[i] = 0.0; + } + return transfer(x, Memory::HBM); +} + +/// 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_qwen35_state(c : &Config, max_seq : i32) -> Qwen35State { + assert(c.arch == 1, "new_qwen35_state: the model is not a Qwen3.5 model"); + assert(max_seq > 0 && max_seq <= c.max_positions, "max_seq must be between 1 and the max_positions of the model"); + assert(c.head_dim == 256 && c.rotary_dim % 2 == 0 && c.rotary_dim <= 256, "the full attention needs heads of 256 values"); + assert(c.linear_k_dim == 128 && c.linear_v_dim == 128 && c.conv_width == 4, "the DeltaNet needs heads of 128 values and a convolution of width 4"); + let half = c.rotary_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.rotary_dim)); + hcos[p][i] = f64::cos(angle) as f32; + hsin[p][i] = f64::sin(angle) as f32; + } + } + let mut layers = Vec::new(); + for l in 0..c.num_layers { + if (l + 1) % c.full_attention_interval == 0 { + layers.push(Qwen35LayerState { + conv: transfer(Tensor([1, 1, 1]), Memory::HBM), + s: transfer(Tensor([1, 1, 1]), Memory::HBM), + k: transfer(Tensor([max_seq, c.num_kv_heads, 256]), Memory::HBM), + v: transfer(Tensor([max_seq, c.num_kv_heads, 256]), Memory::HBM), + }); + } else { + layers.push(Qwen35LayerState { + conv: deltanet_conv_state(c.linear_k_heads, c.linear_v_heads), + s: deltanet_state(c.linear_v_heads), + k: transfer(Tensor([1, 1, 1]), Memory::HBM), + v: transfer(Tensor([1, 1, 1]), Memory::HBM), + }); + } + } + let qkv_rows = (2 * c.num_q_heads + 2 * c.num_kv_heads) * 256; + let in_rows = (2 * c.linear_k_heads + 2 * c.linear_v_heads) * 128 + 2 * c.linear_v_heads; + let mut shared_id = Tensor([1]); + shared_id[0] = 0; + return Qwen35State { + max_seq: max_seq, + x: transfer(Tensor([c.hidden_size]), Memory::HBM), + xn: transfer(Tensor([c.hidden_size]), Memory::HBM), + proj: transfer(Tensor([i32::max(qkv_rows, in_rows)]), Memory::HBM), + y: transfer(Tensor([i32::max(c.num_q_heads * 256, c.linear_v_heads * 128)]), Memory::HBM), + q: transfer(Tensor([c.num_q_heads, 256]), Memory::HBM), + parts: transfer(gated_attention_scratch(c.num_q_heads), Memory::HBM), + dn: deltanet_scratch(c.linear_k_heads, c.linear_v_heads), + experts: Experts { + router_logits: transfer(Tensor([c.num_experts + 1]), Memory::HBM), + ids: transfer(Tensor([c.experts_per_token]), Memory::HBM), + weights: transfer(Tensor([c.experts_per_token]), Memory::HBM), + mlp: transfer(Tensor([c.experts_per_token, c.moe_intermediate_size]), Memory::HBM), + }, + shared_id: transfer(shared_id, Memory::HBM), + shared_weight: zeros_f32(1), + shared_mlp: transfer(Tensor([1, c.shared_expert_inter]), Memory::HBM), + logits: transfer(Tensor([c.vocab_size]), Memory::HBM), + cos: transfer(hcos, Memory::HBM), + sin: transfer(hsin, Memory::HBM), + layers: layers, + }; +} + +/// y = x / sqrt(mean(x^2) + eps) * w, with f32 weights, as `nn_rms_norm` does with bf16 weights. +fn rms_norm_f32(y : &mut Tensor, x : &Tensor, w : &Tensor, n : i32, eps : f32) -> void { + assert(n > 0 && y.len() >= n && x.len() >= n && w.len() >= n, "rms_norm_f32: a tensor has fewer than n values"); + spawn on(Topology::Device) { + for b in 0..1 across blocks { + let mut part = unsafe { Tensor::uninit() }; + for l in 0..1024 across lanes { + let mut s : f32 = 0.0; + let mut i = l; + while i < n { + s = s + x[i] * x[i]; + i = i + 1024; + } + part[l] = s; + } + let ss = lanes::sum(&part, 1024); + let inv = 1.0 / (ss / (n as f32) + eps).sqrt(); + for l in 0..1024 across lanes { + for j in 0..(n + 1023) / 1024 { + let i = j * 1024 + l; + if i < n { + y[i] = x[i] * inv * w[i]; + } + } + } + } + } + return; +} + +/// out[0] = sigmoid(logits[at]): the weight of the shared expert. +fn shared_gate(out : &mut Tensor, logits : &Tensor, at : i32) -> void { + assert(out.len() >= 1 && logits.len() > at, "shared_gate: a tensor is too short"); + spawn on(Topology::Device) { + for b in 0..1 across blocks { + for l in 0..1 across lanes { + out[l] = 1.0 / (1.0 + (0.0 - logits[at]).fast_exp()); + } + } + } + return; +} + +/// The experts and the shared expert of a layer: x += the sum of the chosen experts for xn, each +/// times its weight, plus the shared expert times sigmoid(its gate). +fn add_experts_shared(e : &mut Experts, x : &mut Tensor, xn : &Tensor, shared_weight : &mut Tensor, shared_mlp : &mut Tensor, shared_id : &Tensor, layer : &Qwen35Layer, c : &Config) -> void { + let k = c.experts_per_token; + let inter = c.moe_intermediate_size; + let shared = c.shared_expert_inter; + nn_matvec(&mut e.router_logits, &layer.router, xn, c.num_experts + 1, c.hidden_size); + nn_top_k(&mut e.ids, &mut e.weights, &e.router_logits, c.num_experts, k); + shared_gate(shared_weight, &e.router_logits, c.num_experts); + assert(layer.gate_up.dtype == U4 && layer.down.dtype == U4 && layer.shared_gate_up.dtype == U4 && layer.shared_down.dtype == U4, "the experts of a Qwen3.5 model must be Q4_0"); + moe_swiglu_q4_blocks(&mut e.mlp, &layer.gate_up.codes, &layer.gate_up.group_scales, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + moe_down_q4_add_blocks(x, &layer.down.codes, &layer.down.group_scales, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + moe_swiglu_q4_blocks(shared_mlp, &layer.shared_gate_up.codes, &layer.shared_gate_up.group_scales, shared_id, xn, 1, shared, c.hidden_size, 1); + moe_down_q4_add_blocks(x, &layer.shared_down.codes, &layer.shared_down.group_scales, shared_id, shared_weight, shared_mlp, 1, c.hidden_size, shared, 1); + return; +} + +/// Runs the token in `token` at position `pos` through every layer. The hidden state of the token +/// is then in `s.x`, and the state of each layer is updated. +fn run_qwen35_layers(w : &Qwen35Weights, s : &mut Qwen35State, 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"); + let kh = c.linear_k_heads; + let vh = c.linear_v_heads; + let z_at = (2 * kh + vh) * 128; + let b_at = z_at + vh * 128; + let a_at = b_at + vh; + let qkv_rows = (2 * c.num_q_heads + 2 * c.num_kv_heads) * 256; + nn_embed(&mut s.x, &w.embed, token, c.hidden_size); + let mut l = 0; + for ls in s.layers.iter_mut() { + let layer = &w.layers[l]; + assert(layer.full_attention == ((l + 1) % c.full_attention_interval == 0), "the full attention layers of the file are not every full_attention_interval layers"); + rms_norm_f32(&mut s.xn, &s.x, &layer.attn_norm, c.hidden_size, eps); + if layer.full_attention { + matvec(&mut s.proj, &layer.qkv, &s.xn, qkv_rows, c.hidden_size); + gated_norm_rope_and_store(&mut s.q, &mut ls.k, &mut ls.v, &s.proj, &layer.q_norm, &layer.k_norm, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.rotary_dim, eps); + gated_attention(&mut s.y, &mut s.parts, &s.q, &ls.k, &ls.v, &s.proj, pos, c.num_q_heads, c.num_kv_heads); + matvec_add(&mut s.x, &layer.attn_out, &s.y, c.hidden_size, c.num_q_heads * 256); + } else { + matvec(&mut s.proj, &layer.linear_in, &s.xn, a_at + vh, c.hidden_size); + deltanet_step(&mut s.y, &mut ls.conv, &mut ls.s, &mut s.dn, &s.proj, &layer.conv, &layer.neg_a, &layer.dt_bias, &layer.linear_norm, z_at, b_at, a_at, kh, vh, eps); + matvec_add(&mut s.x, &layer.linear_out, &s.y, c.hidden_size, vh * 128); + } + rms_norm_f32(&mut s.xn, &s.x, &layer.mlp_norm, c.hidden_size, eps); + add_experts_shared(&mut s.experts, &mut s.x, &s.xn, &mut s.shared_weight, &mut s.shared_mlp, &s.shared_id, layer, c); + 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_qwen35(w : &Qwen35Weights, s : &mut Qwen35State, next : &mut Tensor) -> void { + let c = &w.config; + rms_norm_f32(&mut s.xn, &s.x, &w.final_norm, c.hidden_size, c.rms_norm_eps as f32); + matvec(&mut s.logits, &w.lm_head, &s.xn, c.vocab_size, c.hidden_size); + nn_argmax(next, &s.logits, c.vocab_size); + return; +} From 55ee7c4ba80736b21383ccf51bf1c7d90ca2ab5a Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:45:45 -0800 Subject: [PATCH 11/60] qwen app: run Qwen3.5 and Qwen3.6 models (arch 1 of weight file v2) end to end (#89) main.vx reads the arch in the header of the weight file. For arch 1 it loads the model with load_qwen35_weights and runs run_qwen35: the prompt one token at a time (no chunked prefill and no drafts yet), then the generated tokens, with the same output as for arch 0. src/qwen35.vx: the experts of a layer can now also be bf16, and the token loop asserts that the full attention layers are where the config puts them. tests/generate_qwen35.vx compares the tiny Qwen3.5 model with reference.py: the bf16 file, the Q4_0 file with a 6-bit lm_head, and the Q4_0 file after a prompt of 2,100 tokens. The tokens are the same, and the largest logit difference is 5.7e-5, 5.0e-5 and 4.3e-5. tests/run.sh: all 85 checks pass with vxc 0.0.5. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- src/main.vx | 95 ++++++++++++++++++++++++++++++++++++++++ src/qwen35.vx | 18 +++++--- tests/generate_qwen35.vx | 28 ++++++++++++ 3 files changed, 136 insertions(+), 5 deletions(-) create mode 100644 tests/generate_qwen35.vx diff --git a/src/main.vx b/src/main.vx index a8fcde7..508249c 100644 --- a/src/main.vx +++ b/src/main.vx @@ -25,6 +25,7 @@ import std::time; import std::vec; import qwen::weights; import qwen::model; +import qwen::qwen35; import qwen::prefill; import qwen::session; import qwen::speculate; @@ -354,6 +355,97 @@ fn generate_with_drafts(w : &Weights, s : &mut State, t : &Tokenizer, text_mode return step; } +/// `main` for a Qwen3.5 or Qwen3.6 model (weight file v2, arch 1). The prompt runs one token at a +/// time; it has no chunked prefill and no drafts yet (#89). Prints the same lines as `main`. +fn run_qwen35(path : *const i8, t : &Tokenizer, text_mode : bool, prompt : &Vec, steps : i32) -> i32 { + let w = load_qwen35_weights(path); + 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 { + for i in 0..count { + write_token(t, prompt[i]); + } + } else { + print!("prompt="); + for i in 0..count { + if i > 0 { + print!(","); + } + print!("{}", prompt[i]); + } + println!(";"); + } + let prompt_start = Instant::now(); + let mut ht = Tensor([1]); + for i in 0..count { + ht[0] = prompt[i]; + let token = transfer(&ht, Memory::HBM); + run_qwen35_layers(&w, &mut s, &token, i); + } + predict_qwen35(&w, &mut s, &mut slots[0].next); + let mut tokens = Vec::new(); + tokens.push(read_token(&slots[0].next)); + let prompt_ms = f64::from(prompt_start.elapsed().as_secs_f32()) * 1000.0; + let mut start = Instant::now(); + let mut decoded = 0; + for step in 0..steps { + let token = tokens[step]; + if text_mode { + if is_special(t, token) || token == w.config.eos_token_id { + break; + } + write_token(t, token); + } else { + println!("step={} token={} logit={};", step, token, read_logit(&s.logits, token)); + } + if step == 0 { + // The first token after the prompt compiles the kernels of a step, so the clock starts after it. + 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(argc : i32, argv : *mut *mut i8) -> i32 { let o = parse_options(argc, argv); if o.session { @@ -373,6 +465,9 @@ fn main(argc : i32, argv : *mut *mut i8) -> i32 { let count = prompt.len(); assert(steps > 0, "--steps must be at least 1"); + if weight_file_arch(o.weights) == 1 { + return run_qwen35(o.weights, &t, text_mode, &prompt, steps); + } let w = load_weights(o.weights); let mut s = new_state(&w.config, count + steps); for i in 0..count { diff --git a/src/qwen35.vx b/src/qwen35.vx index 071368c..8283763 100644 --- a/src/qwen35.vx +++ b/src/qwen35.vx @@ -177,11 +177,19 @@ fn add_experts_shared(e : &mut Experts, x : &mut Tensor, nn_matvec(&mut e.router_logits, &layer.router, xn, c.num_experts + 1, c.hidden_size); nn_top_k(&mut e.ids, &mut e.weights, &e.router_logits, c.num_experts, k); shared_gate(shared_weight, &e.router_logits, c.num_experts); - assert(layer.gate_up.dtype == U4 && layer.down.dtype == U4 && layer.shared_gate_up.dtype == U4 && layer.shared_down.dtype == U4, "the experts of a Qwen3.5 model must be Q4_0"); - moe_swiglu_q4_blocks(&mut e.mlp, &layer.gate_up.codes, &layer.gate_up.group_scales, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); - moe_down_q4_add_blocks(x, &layer.down.codes, &layer.down.group_scales, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); - moe_swiglu_q4_blocks(shared_mlp, &layer.shared_gate_up.codes, &layer.shared_gate_up.group_scales, shared_id, xn, 1, shared, c.hidden_size, 1); - moe_down_q4_add_blocks(x, &layer.shared_down.codes, &layer.shared_down.group_scales, shared_id, shared_weight, shared_mlp, 1, c.hidden_size, shared, 1); + if layer.gate_up.dtype == U4 { + assert(layer.down.dtype == U4 && layer.shared_gate_up.dtype == U4 && layer.shared_down.dtype == U4, "the experts of a Qwen3.5 model must all be Q4_0, or all bf16"); + moe_swiglu_q4_blocks(&mut e.mlp, &layer.gate_up.codes, &layer.gate_up.group_scales, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + moe_down_q4_add_blocks(x, &layer.down.codes, &layer.down.group_scales, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + moe_swiglu_q4_blocks(shared_mlp, &layer.shared_gate_up.codes, &layer.shared_gate_up.group_scales, shared_id, xn, 1, shared, c.hidden_size, 1); + moe_down_q4_add_blocks(x, &layer.shared_down.codes, &layer.shared_down.group_scales, shared_id, shared_weight, shared_mlp, 1, c.hidden_size, shared, 1); + } else { + assert(layer.gate_up.dtype == BF16 && layer.down.dtype == BF16 && layer.shared_gate_up.dtype == BF16 && layer.shared_down.dtype == BF16, "the experts of a Qwen3.5 model must all be Q4_0, or all bf16"); + nn_moe_swiglu(&mut e.mlp, &layer.gate_up.bf16, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); + nn_moe_down_add(x, &layer.down.bf16, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); + nn_moe_swiglu(shared_mlp, &layer.shared_gate_up.bf16, shared_id, xn, 1, shared, c.hidden_size, 1); + nn_moe_down_add(x, &layer.shared_down.bf16, shared_id, shared_weight, shared_mlp, 1, c.hidden_size, shared, 1); + } return; } diff --git a/tests/generate_qwen35.vx b/tests/generate_qwen35.vx new file mode 100644 index 0000000..c6101fc --- /dev/null +++ b/tests/generate_qwen35.vx @@ -0,0 +1,28 @@ +// Generates tokens of the tiny Qwen3.5 model (`make_tiny_model.py --qwen35`) on the GPU with +// `src/main.vx`, and compares them with `reference.py`. The tokens must be equal, and each logit +// within the tolerance of the reference: +// - the bf16 file, with the bf16 kernels of the experts +// - the Q4_0 file with a 6-bit lm_head, with the Q4_0 kernels +// - the Q4_0 file after a prompt of 2,100 tokens, so the full attention layer goes past position +// 2,048, where its blocks take 64 SIMD groups for each head in place of 32 +// +// The tiny model has the head sizes of Qwen3.6-35B-A3B (DeltaNet heads of 128, attention heads of +// 256 with RoPE on 64), so it runs the kernels of the real model. +// +// RUN: python3 %S/../scripts/make_tiny_model.py --qwen35 %t.vxw > /dev/null +// RUN: python3 %S/../scripts/reference.py %t.vxw --tokens 1,2,3,4 --steps 16 > %t.reference +// RUN: vxc %S/../src/main.vx --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx -- %t.vxw --tokens 1,2,3,4 --steps 16 > %t.vx +// RUN: python3 %S/../scripts/compare.py %t.reference %t.vx --tolerance 0.001 | FileCheck %s +// RUN: python3 %S/../scripts/make_tiny_model.py --qwen35 --q4 --q6-lm-head %t-q4.vxw > /dev/null +// RUN: python3 %S/../scripts/reference.py %t-q4.vxw --tokens 1,2,3,4 --steps 16 > %t-q4.reference +// RUN: vxc %S/../src/main.vx --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx -- %t-q4.vxw --tokens 1,2,3,4 --steps 16 > %t-q4.vx +// RUN: python3 %S/../scripts/compare.py %t-q4.reference %t-q4.vx --tolerance 0.002 | FileCheck %s --check-prefix=Q4 +// RUN: python3 -c "print(','.join(str(i * 37 % 256) for i in range(2100)))" > %t-long.ids +// RUN: python3 %S/../scripts/make_tiny_model.py --qwen35 --q4 --q6-lm-head --max-positions 2200 %t-long.vxw > /dev/null +// RUN: python3 %S/../scripts/reference.py %t-long.vxw --tokens $(cat %t-long.ids) --steps 8 > %t-long.reference +// RUN: vxc %S/../src/main.vx --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx -- %t-long.vxw --tokens $(cat %t-long.ids) --steps 8 > %t-long.vx +// RUN: python3 %S/../scripts/compare.py %t-long.reference %t-long.vx --tolerance 0.002 | FileCheck %s --check-prefix=LONG +// +// CHECK: 16 steps, same tokens, logits within 0.001 +// Q4: 16 steps, same tokens, logits within 0.002 +// LONG: 8 steps, same tokens, logits within 0.002 From 45e71dc8c0108608c8733e0593c0773e8daaaaf3 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:09:39 -0800 Subject: [PATCH 12/60] qwen app: the prompt of Qwen3.5/Qwen3.6 in chunks (#89) src/prefill35.vx runs the prompt of an arch 1 model in chunks of up to 2048 tokens, as src/prefill.vx does for arch 0. The products and the sort of the experts are those of src/prefill.vx. New here: - The DeltaNet of a chunk: the convolution and the norms of all the tokens at once, then pf_dn_recur, which runs the tokens in order and keeps S in registers for the whole chunk, 8 values of v for each SIMD group. scripts/deltanet_chunk.py prints that kernel. - The gated attention of a chunk, 64 tokens at a time, with 8 SIMD groups for each head and token. - The shared expert, as a dense SwiGLU over the chunk, times its gate. main.vx uses it in place of one token at a time. The clock of the generated tokens now starts after the tokens of step 0, which compile the kernels of a step: a token cannot run twice to warm up, because the DeltaNet would update its state twice. tests/generate_qwen35.vx: the bf16 file matches reference.py within 5.5e-5 after a short prompt and 4.8e-5 after 2,100 tokens (2 chunks). The products of a chunk round each Q4_0 weight to f16, as for arch 0, so the Q4_0 files get 0.003, as in tests/prefill.vx (1.85e-3 and 2.83e-3, the same tokens). tests/run.sh: all 89 checks pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- scripts/deltanet_chunk.py | 56 +++ src/main.vx | 17 +- src/prefill35.vx | 865 ++++++++++++++++++++++++++++++++++++++ tests/generate_qwen35.vx | 21 +- 4 files changed, 943 insertions(+), 16 deletions(-) create mode 100644 scripts/deltanet_chunk.py create mode 100644 src/prefill35.vx 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/src/main.vx b/src/main.vx index 508249c..5f2c1cf 100644 --- a/src/main.vx +++ b/src/main.vx @@ -26,6 +26,7 @@ import std::vec; import qwen::weights; import qwen::model; import qwen::qwen35; +import qwen::prefill35; import qwen::prefill; import qwen::session; import qwen::speculate; @@ -355,8 +356,8 @@ fn generate_with_drafts(w : &Weights, s : &mut State, t : &Tokenizer, text_mode return step; } -/// `main` for a Qwen3.5 or Qwen3.6 model (weight file v2, arch 1). The prompt runs one token at a -/// time; it has no chunked prefill and no drafts yet (#89). Prints the same lines as `main`. +/// `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 as `main`. fn run_qwen35(path : *const i8, t : &Tokenizer, text_mode : bool, prompt : &Vec, steps : i32) -> i32 { let w = load_qwen35_weights(path); let count = prompt.len(); @@ -390,12 +391,7 @@ fn run_qwen35(path : *const i8, t : &Tokenizer, text_mode : bool, prompt : &Vec< println!(";"); } let prompt_start = Instant::now(); - let mut ht = Tensor([1]); - for i in 0..count { - ht[0] = prompt[i]; - let token = transfer(&ht, Memory::HBM); - run_qwen35_layers(&w, &mut s, &token, i); - } + prefill_qwen35(&w, &mut s, prompt); predict_qwen35(&w, &mut s, &mut slots[0].next); let mut tokens = Vec::new(); tokens.push(read_token(&slots[0].next)); @@ -412,8 +408,9 @@ fn run_qwen35(path : *const i8, t : &Tokenizer, text_mode : bool, prompt : &Vec< } else { println!("step={} token={} logit={};", step, token, read_logit(&s.logits, token)); } - if step == 0 { - // The first token after the prompt compiles the kernels of a step, so the clock starts after it. + 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 { diff --git a/src/prefill35.vx b/src/prefill35.vx new file mode 100644 index 0000000..5cd8e4b --- /dev/null +++ b/src/prefill35.vx @@ -0,0 +1,865 @@ +//===- prefill35.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 prompt of a Qwen3.5 or Qwen3.6 model (arch 1, #89) in chunks, as src/prefill.vx does for +// arch 0. A chunk reads each weight once for all its tokens: the products are those of +// src/prefill.vx (`pf_mm`), and the experts are sorted by expert in the same way. The parts that +// are new here: +// +// - The DeltaNet of a chunk. The convolution and the norms run for all the tokens at once. The +// update of the state runs the tokens in order, in one kernel that keeps S in registers. +// - The gated attention of a chunk: the kernels of src/gated_attention.vx for ATT_TOKENS tokens +// at a time, each with ATT_GROUPS SIMD groups for each head. +// - The shared expert, as a dense SwiGLU over the chunk, times sigmoid(its gate). +import core::convert; +import core::num; +import std::nn; +import std::vec; +import qwen::deltanet; +import qwen::gated_attention; +import qwen::model; +import qwen::prefill; +import qwen::qwen35; +import qwen::simd; +import qwen::weights; + +/// The tokens of a chunk that the attention takes at a time, and the SIMD groups of each head and +/// token. The scratch space of the parts is ATT_TOKENS x q_heads x ATT_GROUPS x 260 values. +const ATT_TOKENS : i32 = 64; +const ATT_GROUPS : i32 = 8; + +/// The tensors of a chunk, made once. `rows`, `zeros` and the `e_` tensors are those of `Prefill`. +/// `proj` is the output of `qkv` or `linear_in` for each token, and `y` the input of `attn_out` or +/// `linear_out`. The `d` tensors are those of the DeltaNet, and the `s_` tensors those of the shared +/// expert. `router` has the logits of the experts, then that of the gate of the shared expert. +struct Prefill35 { + chunk : i32, + tokens : Tensor, + rows : Tensor, + zeros : Tensor, + no_bias : Tensor, + x : Tensor, + xn : Tensor, + proj : Tensor, + y : Tensor, + q : Tensor, + parts : Tensor, + dq : Tensor, + dk : Tensor, + dv : Tensor, + beta : Tensor, + decay : Tensor, + o : Tensor, + router : Tensor, + ids : Tensor, + wts : Tensor, + e_rows : Tensor, + e_ident : Tensor, + e_bases : Tensor, + slot : Tensor, + e_counts : Tensor, + e_lane_counts : Tensor, + e_gu : Tensor, + e_h : Tensor, + e_out : Tensor, + s_gu : Tensor, + s_h : Tensor, + s_out : Tensor, +} + +/// The tensors for chunks of up to `chunk` tokens. +fn new_prefill35(c : &Config, chunk : i32) -> Prefill35 { + assert(chunk > 0 && chunk % 16 == 0, "new_prefill35: the chunk must be a multiple of 16"); + let k = c.experts_per_token; + let experts = c.num_experts; + let positions = expert_positions(c, chunk); + let cap = (chunk + 31) / 32 * 32; + let mut ident = Tensor([positions]); + for p in 0..positions { + ident[p] = p; + } + let qkv_rows = (2 * c.num_q_heads + 2 * c.num_kv_heads) * 256; + let in_rows = (2 * c.linear_k_heads + 2 * c.linear_v_heads) * 128 + 2 * c.linear_v_heads; + let kh = c.linear_k_heads; + let vh = c.linear_v_heads; + return Prefill35 { + chunk: chunk, + tokens: transfer(Tensor([chunk]), Memory::HBM), + rows: transfer(Tensor([cap]), Memory::HBM), + zeros: transfer(Tensor([cap / 16]), Memory::HBM), + no_bias: transfer(Tensor([1]), Memory::HBM), + x: transfer(Tensor([cap, c.hidden_size]), Memory::HBM), + xn: transfer(Tensor([cap, c.hidden_size]), Memory::HBM), + proj: transfer(Tensor([cap, i32::max(qkv_rows, in_rows)]), Memory::HBM), + y: transfer(Tensor([cap, i32::max(c.num_q_heads * 256, vh * 128)]), Memory::HBM), + q: transfer(Tensor([chunk, c.num_q_heads, 256]), Memory::HBM), + parts: transfer(Tensor([ATT_TOKENS, c.num_q_heads, ATT_GROUPS, 260]), Memory::HBM), + dq: transfer(Tensor([chunk, kh, 128]), Memory::HBM), + dk: transfer(Tensor([chunk, kh, 128]), Memory::HBM), + dv: transfer(Tensor([chunk, vh, 128]), Memory::HBM), + beta: transfer(Tensor([chunk, vh]), Memory::HBM), + decay: transfer(Tensor([chunk, vh]), Memory::HBM), + o: transfer(Tensor([chunk, vh, 16, 8]), Memory::HBM), + router: transfer(Tensor([cap, experts + 1]), Memory::HBM), + ids: transfer(Tensor([chunk, k]), Memory::HBM), + wts: transfer(Tensor([chunk, k]), Memory::HBM), + e_rows: transfer(Tensor([positions]), Memory::HBM), + e_ident: transfer(ident, Memory::HBM), + e_bases: transfer(Tensor([positions / 16]), Memory::HBM), + slot: transfer(Tensor([chunk * k]), Memory::HBM), + e_counts: transfer(Tensor([experts]), Memory::HBM), + e_lane_counts: transfer(Tensor([experts * 32]), Memory::HBM), + e_gu: transfer(Tensor([positions, 2 * c.moe_intermediate_size]), Memory::HBM), + e_h: transfer(Tensor([positions, c.moe_intermediate_size]), Memory::HBM), + e_out: transfer(Tensor([positions, c.hidden_size]), Memory::HBM), + s_gu: transfer(Tensor([cap, 2 * c.shared_expert_inter]), Memory::HBM), + s_h: transfer(Tensor([cap, c.shared_expert_inter]), Memory::HBM), + s_out: transfer(Tensor([cap, c.hidden_size]), Memory::HBM), + }; +} + +// ------------------------------------------------------------------------------ norms --- + +/// `pf_rms_norm` with f32 weights. +fn pf35_rms_norm(y : &mut Tensor, x : &Tensor, w : &Tensor, n : i32, dim : i32, eps : f32) -> void { + spawn on(Topology::Device) { + for t in 0..n across blocks { + let mut part = unsafe { Tensor::uninit() }; + for l in 0..1024 across lanes { + let mut s : f32 = 0.0; + let mut i = l; + while i < dim { + s = s + x[t][i] * x[t][i]; + i = i + 1024; + } + part[l] = s; + } + let ss = lanes::sum(&part, 1024); + let inv = 1.0 / (ss / (dim as f32) + eps).sqrt(); + for l in 0..1024 across lanes { + for j in 0..(dim + 1023) / 1024 { + let i = j * 1024 + l; + if i < dim { + y[t][i] = x[t][i] * inv * w[i]; + } + } + } + } + } + return; +} + +/// `pf_add_rms_norm` with f32 weights: x[t] += y[t], then y[t] = the RMSNorm of x[t] times w. +fn pf35_add_rms_norm(x : &mut Tensor, y : &mut Tensor, w : &Tensor, n : i32, dim : i32, eps : f32) -> void { + spawn on(Topology::Device) { + for t in 0..n across blocks { + let mut part = unsafe { Tensor::uninit() }; + for l in 0..1024 across lanes { + let mut s : f32 = 0.0; + for j in 0..(dim + 1023) / 1024 { + let i = j * 1024 + l; + if i < dim { + let v = x[t][i] + y[t][i]; + x[t][i] = v; + s = s + v * v; + } + } + part[l] = s; + } + let ss = lanes::sum(&part, 1024); + let inv = 1.0 / (ss / (dim as f32) + eps).sqrt(); + for l in 0..1024 across lanes { + for j in 0..(dim + 1023) / 1024 { + let i = j * 1024 + l; + if i < dim { + y[t][i] = x[t][i] * inv * w[i]; + } + } + } + } + } + return; +} + +// --------------------------------------------------------------------------- DeltaNet --- + +/// The convolution, the SiLU and the L2 norms of the n tokens of the chunk, as `deltanet_conv` for +/// each. Block (t, h) is one SIMD group for head h of token t, and lane l does its channels 4 l to +/// 4 l + 3. The inputs before the chunk come from `conv_state`, which this kernel does not change. +fn pf_dn_conv(qn : &mut Tensor, kn : &mut Tensor, vv : &mut Tensor, conv_state : &Tensor, proj : &Tensor, conv : &Tensor, n : i32, k_heads : i32, v_heads : i32) -> void { + spawn on(Topology::Device) { + for t in 0..n across blocks { + for h in 0..2 * k_heads + v_heads across blocks { + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let mut y = unsafe { Tensor::uninit() }; + for j in 0..4 { + let i = 4 * l + j; + let c = h * 128 + i; + let mut x0 : f32 = 0.0; + if t >= 3 { + x0 = proj[t - 3][c]; + } else { + x0 = conv_state[h][i][t]; + } + let mut x1 : f32 = 0.0; + if t >= 2 { + x1 = proj[t - 2][c]; + } else { + x1 = conv_state[h][i][t + 1]; + } + let mut x2 : f32 = 0.0; + if t >= 1 { + x2 = proj[t - 1][c]; + } else { + x2 = conv_state[h][i][2]; + } + let a = conv[c * 4] * x0 + conv[c * 4 + 1] * x1 + conv[c * 4 + 2] * x2 + conv[c * 4 + 3] * proj[t][c]; + y[j] = a / (1.0 + (0.0 - a).fast_exp()); + } + let ss = simd_sum(y[0] * y[0] + y[1] * y[1] + y[2] * y[2] + y[3] * y[3]); + let inv = 1.0 / (ss + 0.000001).sqrt(); + for j in 0..4 { + if h < k_heads { + qn[t][h][4 * l + j] = y[j] * inv * 0.08838834764831845; + } else if h < 2 * k_heads { + kn[t][h - k_heads][4 * l + j] = y[j] * inv; + } else { + vv[t][h - 2 * k_heads][4 * l + j] = y[j]; + } + } + } + } + } + } + } + return; +} + +/// The inputs of the convolution after the chunk: the last 3 of the chunk and of the state before. +fn pf_dn_conv_state(conv_state : &mut Tensor, proj : &Tensor, n : i32, heads : i32) -> void { + spawn on(Topology::Device) { + for h in 0..heads across blocks { + for i in 0..128 across lanes { + let c = h * 128 + i; + let mut x = unsafe { Tensor::uninit() }; + for j in 0..3 { + // Input n - 3 + j of the chunk: an input of the chunk, or one of the state before it. + let at = n - 3 + j; + if at >= 0 { + x[j] = proj[at][c]; + } else { + x[j] = conv_state[h][i][3 + at]; + } + } + conv_state[h][i][0] = x[0]; + conv_state[h][i][1] = x[1]; + conv_state[h][i][2] = x[2]; + } + } + } + return; +} + +/// beta and the decay of each head of v, for each token of the chunk, as `deltanet_gates`. +fn pf_dn_gates(beta : &mut Tensor, decay : &mut Tensor, proj : &Tensor, neg_a : &Tensor, dt_bias : &Tensor, b_at : i32, a_at : i32, n : i32, v_heads : i32) -> void { + spawn on(Topology::Device) { + for t in 0..n across blocks { + for j in 0..64 across lanes { + if j < v_heads { + let b = proj[t][b_at + j]; + beta[t][j] = 1.0 / (1.0 + (0.0 - b).fast_exp()); + let x = proj[t][a_at + j] + dt_bias[j]; + let mut sp = x; + if x <= 20.0 { + sp = simd_log(1.0 + x.fast_exp()); + } + decay[t][j] = (neg_a[j] * sp).fast_exp(); + } + } + } + } + return; +} + +/// y[t] = rms_norm(o[t]) * norm * silu(z[t]) for each head of v, as `deltanet_gated_norm`. +fn pf_dn_gated_norm(y : &mut Tensor, o : &Tensor, proj : &Tensor, norm : &Tensor, z_at : i32, n : i32, v_heads : i32, eps : f32) -> void { + spawn on(Topology::Device) { + for t in 0..n across blocks { + for h in 0..v_heads across blocks { + let mut part = unsafe { Tensor::uninit() }; + for i in 0..128 across lanes { + let a = o[t][h][i / 8][i % 8]; + 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[t][z_at + h * 128 + i]; + y[t][h * 128 + i] = o[t][h][i / 8][i % 8] * inv * norm[i] * (z / (1.0 + (0.0 - z).fast_exp())); + } + } + } + } + return; +} + +/// The update of the state and the output q . S for the n tokens of the chunk, in order. Block (h, vq) +/// 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 +/// of k, and keeps its 32 values of S in registers for the whole chunk: S is read and written once. +/// For each token and value of v, the operations are those of `deltanet_recur`, in the same order. +/// o[t][h][vq][m] is the output of value vq * 8 + m. +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 { + spawn on(Topology::Device) { + for h in 0..v_heads across blocks { + for vq in 0..16 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 mut s0_0 = state[h][vq * 8 + 0][d + 0]; + let mut s0_1 = state[h][vq * 8 + 0][d + 1]; + let mut s0_2 = state[h][vq * 8 + 0][d + 2]; + let mut s0_3 = state[h][vq * 8 + 0][d + 3]; + let mut s1_0 = state[h][vq * 8 + 1][d + 0]; + let mut s1_1 = state[h][vq * 8 + 1][d + 1]; + let mut s1_2 = state[h][vq * 8 + 1][d + 2]; + let mut s1_3 = state[h][vq * 8 + 1][d + 3]; + let mut s2_0 = state[h][vq * 8 + 2][d + 0]; + let mut s2_1 = state[h][vq * 8 + 2][d + 1]; + let mut s2_2 = state[h][vq * 8 + 2][d + 2]; + let mut s2_3 = state[h][vq * 8 + 2][d + 3]; + let mut s3_0 = state[h][vq * 8 + 3][d + 0]; + let mut s3_1 = state[h][vq * 8 + 3][d + 1]; + let mut s3_2 = state[h][vq * 8 + 3][d + 2]; + let mut s3_3 = state[h][vq * 8 + 3][d + 3]; + let mut s4_0 = state[h][vq * 8 + 4][d + 0]; + let mut s4_1 = state[h][vq * 8 + 4][d + 1]; + let mut s4_2 = state[h][vq * 8 + 4][d + 2]; + let mut s4_3 = state[h][vq * 8 + 4][d + 3]; + let mut s5_0 = state[h][vq * 8 + 5][d + 0]; + let mut s5_1 = state[h][vq * 8 + 5][d + 1]; + let mut s5_2 = state[h][vq * 8 + 5][d + 2]; + let mut s5_3 = state[h][vq * 8 + 5][d + 3]; + let mut s6_0 = state[h][vq * 8 + 6][d + 0]; + let mut s6_1 = state[h][vq * 8 + 6][d + 1]; + let mut s6_2 = state[h][vq * 8 + 6][d + 2]; + let mut s6_3 = state[h][vq * 8 + 6][d + 3]; + let mut s7_0 = state[h][vq * 8 + 7][d + 0]; + let mut s7_1 = state[h][vq * 8 + 7][d + 1]; + let mut s7_2 = state[h][vq * 8 + 7][d + 2]; + let mut s7_3 = state[h][vq * 8 + 7][d + 3]; + for t in 0..n { + let q0 = qn[t][g][d + 0]; + let q1 = qn[t][g][d + 1]; + let q2 = qn[t][g][d + 2]; + let q3 = qn[t][g][d + 3]; + let k0 = kn[t][g][d + 0]; + let k1 = kn[t][g][d + 1]; + let k2 = kn[t][g][d + 2]; + let k3 = kn[t][g][d + 3]; + let b = beta[t][h]; + let dec = decay[t][h]; + let mut mine : f32 = 0.0; + let a0_0 = s0_0 * dec; + let a0_1 = s0_1 * dec; + let a0_2 = s0_2 * dec; + let a0_3 = s0_3 * dec; + let kv0 = simd_sum(a0_0 * k0 + a0_1 * k1 + a0_2 * k2 + a0_3 * k3); + let delta0 = (vv[t][h][vq * 8 + 0] - kv0) * b; + s0_0 = a0_0 + k0 * delta0; + s0_1 = a0_1 + k1 * delta0; + s0_2 = a0_2 + k2 * delta0; + s0_3 = a0_3 + k3 * delta0; + let out0 = simd_sum(s0_0 * q0 + s0_1 * q1 + s0_2 * q2 + s0_3 * q3); + if l == 0 { + mine = out0; + } + let a1_0 = s1_0 * dec; + let a1_1 = s1_1 * dec; + let a1_2 = s1_2 * dec; + let a1_3 = s1_3 * dec; + let kv1 = simd_sum(a1_0 * k0 + a1_1 * k1 + a1_2 * k2 + a1_3 * k3); + let delta1 = (vv[t][h][vq * 8 + 1] - kv1) * b; + s1_0 = a1_0 + k0 * delta1; + s1_1 = a1_1 + k1 * delta1; + s1_2 = a1_2 + k2 * delta1; + s1_3 = a1_3 + k3 * delta1; + let out1 = simd_sum(s1_0 * q0 + s1_1 * q1 + s1_2 * q2 + s1_3 * q3); + if l == 1 { + mine = out1; + } + let a2_0 = s2_0 * dec; + let a2_1 = s2_1 * dec; + let a2_2 = s2_2 * dec; + let a2_3 = s2_3 * dec; + let kv2 = simd_sum(a2_0 * k0 + a2_1 * k1 + a2_2 * k2 + a2_3 * k3); + let delta2 = (vv[t][h][vq * 8 + 2] - kv2) * b; + s2_0 = a2_0 + k0 * delta2; + s2_1 = a2_1 + k1 * delta2; + s2_2 = a2_2 + k2 * delta2; + s2_3 = a2_3 + k3 * delta2; + let out2 = simd_sum(s2_0 * q0 + s2_1 * q1 + s2_2 * q2 + s2_3 * q3); + if l == 2 { + mine = out2; + } + let a3_0 = s3_0 * dec; + let a3_1 = s3_1 * dec; + let a3_2 = s3_2 * dec; + let a3_3 = s3_3 * dec; + let kv3 = simd_sum(a3_0 * k0 + a3_1 * k1 + a3_2 * k2 + a3_3 * k3); + let delta3 = (vv[t][h][vq * 8 + 3] - kv3) * b; + s3_0 = a3_0 + k0 * delta3; + s3_1 = a3_1 + k1 * delta3; + s3_2 = a3_2 + k2 * delta3; + s3_3 = a3_3 + k3 * delta3; + let out3 = simd_sum(s3_0 * q0 + s3_1 * q1 + s3_2 * q2 + s3_3 * q3); + if l == 3 { + mine = out3; + } + let a4_0 = s4_0 * dec; + let a4_1 = s4_1 * dec; + let a4_2 = s4_2 * dec; + let a4_3 = s4_3 * dec; + let kv4 = simd_sum(a4_0 * k0 + a4_1 * k1 + a4_2 * k2 + a4_3 * k3); + let delta4 = (vv[t][h][vq * 8 + 4] - kv4) * b; + s4_0 = a4_0 + k0 * delta4; + s4_1 = a4_1 + k1 * delta4; + s4_2 = a4_2 + k2 * delta4; + s4_3 = a4_3 + k3 * delta4; + let out4 = simd_sum(s4_0 * q0 + s4_1 * q1 + s4_2 * q2 + s4_3 * q3); + if l == 4 { + mine = out4; + } + let a5_0 = s5_0 * dec; + let a5_1 = s5_1 * dec; + let a5_2 = s5_2 * dec; + let a5_3 = s5_3 * dec; + let kv5 = simd_sum(a5_0 * k0 + a5_1 * k1 + a5_2 * k2 + a5_3 * k3); + let delta5 = (vv[t][h][vq * 8 + 5] - kv5) * b; + s5_0 = a5_0 + k0 * delta5; + s5_1 = a5_1 + k1 * delta5; + s5_2 = a5_2 + k2 * delta5; + s5_3 = a5_3 + k3 * delta5; + let out5 = simd_sum(s5_0 * q0 + s5_1 * q1 + s5_2 * q2 + s5_3 * q3); + if l == 5 { + mine = out5; + } + let a6_0 = s6_0 * dec; + let a6_1 = s6_1 * dec; + let a6_2 = s6_2 * dec; + let a6_3 = s6_3 * dec; + let kv6 = simd_sum(a6_0 * k0 + a6_1 * k1 + a6_2 * k2 + a6_3 * k3); + let delta6 = (vv[t][h][vq * 8 + 6] - kv6) * b; + s6_0 = a6_0 + k0 * delta6; + s6_1 = a6_1 + k1 * delta6; + s6_2 = a6_2 + k2 * delta6; + s6_3 = a6_3 + k3 * delta6; + let out6 = simd_sum(s6_0 * q0 + s6_1 * q1 + s6_2 * q2 + s6_3 * q3); + if l == 6 { + mine = out6; + } + let a7_0 = s7_0 * dec; + let a7_1 = s7_1 * dec; + let a7_2 = s7_2 * dec; + let a7_3 = s7_3 * dec; + let kv7 = simd_sum(a7_0 * k0 + a7_1 * k1 + a7_2 * k2 + a7_3 * k3); + let delta7 = (vv[t][h][vq * 8 + 7] - kv7) * b; + s7_0 = a7_0 + k0 * delta7; + s7_1 = a7_1 + k1 * delta7; + s7_2 = a7_2 + k2 * delta7; + s7_3 = a7_3 + k3 * delta7; + let out7 = simd_sum(s7_0 * q0 + s7_1 * q1 + s7_2 * q2 + s7_3 * q3); + if l == 7 { + mine = out7; + } + if l < 8 { + o[t][h][vq][l] = mine; + } + } + state[h][vq * 8 + 0][d + 0] = s0_0; + state[h][vq * 8 + 0][d + 1] = s0_1; + state[h][vq * 8 + 0][d + 2] = s0_2; + state[h][vq * 8 + 0][d + 3] = s0_3; + state[h][vq * 8 + 1][d + 0] = s1_0; + state[h][vq * 8 + 1][d + 1] = s1_1; + state[h][vq * 8 + 1][d + 2] = s1_2; + state[h][vq * 8 + 1][d + 3] = s1_3; + state[h][vq * 8 + 2][d + 0] = s2_0; + state[h][vq * 8 + 2][d + 1] = s2_1; + state[h][vq * 8 + 2][d + 2] = s2_2; + state[h][vq * 8 + 2][d + 3] = s2_3; + state[h][vq * 8 + 3][d + 0] = s3_0; + state[h][vq * 8 + 3][d + 1] = s3_1; + state[h][vq * 8 + 3][d + 2] = s3_2; + state[h][vq * 8 + 3][d + 3] = s3_3; + state[h][vq * 8 + 4][d + 0] = s4_0; + state[h][vq * 8 + 4][d + 1] = s4_1; + state[h][vq * 8 + 4][d + 2] = s4_2; + state[h][vq * 8 + 4][d + 3] = s4_3; + state[h][vq * 8 + 5][d + 0] = s5_0; + state[h][vq * 8 + 5][d + 1] = s5_1; + state[h][vq * 8 + 5][d + 2] = s5_2; + state[h][vq * 8 + 5][d + 3] = s5_3; + state[h][vq * 8 + 6][d + 0] = s6_0; + state[h][vq * 8 + 6][d + 1] = s6_1; + state[h][vq * 8 + 6][d + 2] = s6_2; + state[h][vq * 8 + 6][d + 3] = s6_3; + state[h][vq * 8 + 7][d + 0] = s7_0; + state[h][vq * 8 + 7][d + 1] = s7_1; + state[h][vq * 8 + 7][d + 2] = s7_2; + state[h][vq * 8 + 7][d + 3] = s7_3; + } + } + } + } + } + return; +} + +// --------------------------------------------------------------------- full attention --- + +/// The norms and RoPE of q and k, and the store of k and v, for the n tokens of the chunk, as +/// `gated_norm_rope_and_store`: token t is at position start + t. Block (t, h) does head h of q, +/// then the heads of k. +fn pf_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, start : i32, n : i32, q_heads : i32, kv_heads : i32, rot : i32, eps : f32) -> void { + let half = rot / 2; + assert(k_cache.extent(0) >= start + n && v_cache.extent(0) >= start + n && cos.extent(0) >= start + n && sin.extent(0) >= start + n, "pf_gated_norm_rope_and_store: the caches and the angles need rows for the chunk"); + spawn on(Topology::Device) { + for t in 0..n across blocks { + 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[t][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 pos = start + t; + 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 { + 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[t][h][i] = r; + } else { + k_cache[pos][h - q_heads][i] = r as f16; + v_cache[pos][h - q_heads][i] = qkvg[t][(kv_heads + h) * 256 + i] as f16; + } + } + } + } + } + return; +} + +/// The attention of tokens first to first + m - 1 of the chunk, as `gated_attention_parts` for each: +/// block (tt, h, w) is a SIMD group for head h of token first + tt, at position start + first + tt. +/// It does the blocks of 32 positions w, w + ATT_GROUPS, ... up to that position. +fn pf_gated_attention_parts(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, start : i32, first : i32, m : i32, q_heads : i32, group : i32, scale : f32) -> void { + spawn on(Topology::Device) { + for tt in 0..m across blocks { + for h in 0..q_heads across blocks { + for w in 0..8 across blocks { + let mut stats = unsafe { Tensor::uninit() }; + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let t = first + tt; + let pos = start + t; + 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; + 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 + 8; + } + part[tt][h][w][d] = o0; + part[tt][h][w][d + 1] = o1; + part[tt][h][w][d + 2] = o2; + part[tt][h][w][d + 3] = o3; + part[tt][h][w][d + 4] = o4; + part[tt][h][w][d + 5] = o5; + part[tt][h][w][d + 6] = o6; + part[tt][h][w][d + 7] = o7; + 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[tt][h][w][256 + l] = stats[s][l]; + } + } + } + } + } + } + return; +} + +/// Merges the 8 parts of each head of tokens first to first + m - 1, and multiplies by sigmoid of +/// the gate, as `gated_attention_merge`. +fn pf_gated_attention_merge(y : &mut Tensor, part : &Tensor, qkvg : &Tensor, first : i32, m : i32, q_heads : i32, gate_at : i32) -> void { + spawn on(Topology::Device) { + for tt in 0..m across blocks { + for h in 0..q_heads across blocks { + for dq in 0..8 across blocks { + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let t = first + tt; + let d = dq * 32 + l; + let mut big : f32 = -3.0e38; + for c in 0..8 { + big = big.max(part[tt][h][c][256]); + } + let mut total : f32 = 0.0; + let mut acc : f32 = 0.0; + for c in 0..8 { + let w = (part[tt][h][c][256] - big).fast_exp(); + total = total + w * part[tt][h][c][257]; + acc = acc + w * part[tt][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; +} + +/// The gated attention of the n tokens of the chunk, ATT_TOKENS at a time: y[t] for each token. +fn pf_gated_attention(y : &mut Tensor, parts : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, qkvg : &Tensor, start : i32, n : i32, q_heads : i32, kv_heads : i32) -> void { + let mut first = 0; + while first < n { + let m = i32::min(ATT_TOKENS, n - first); + pf_gated_attention_parts(parts, q, k_cache, v_cache, start, first, m, q_heads, q_heads / kv_heads, 0.0625); + pf_gated_attention_merge(y, parts, qkvg, first, m, q_heads, (q_heads + 2 * kv_heads) * 256); + first = first + m; + } + return; +} + +// ------------------------------------------------------------------------------ experts --- + +/// x[t] += sigmoid(router[t][at]) * out[t], for t below n: the shared expert times its gate. +fn pf35_add_shared(x : &mut Tensor, out : &Tensor, router : &Tensor, at : i32, n : i32, dim : i32) -> void { + spawn on(Topology::Device) { + for t in 0..n across blocks { + for b in 0..(dim + 255) / 256 across blocks { + for l in 0..256 across lanes { + let i = b * 256 + l; + if i < dim { + let g = 1.0 / (1.0 + (0.0 - router[t][at]).fast_exp()); + x[t][i] = x[t][i] + g * out[t][i]; + } + } + } + } + } + return; +} + +/// The experts and the shared expert of a layer, for the n tokens of the chunk: x += the experts of +/// each token, for the norm of x in xn, as `pf_experts`, and the shared expert times its gate. +fn pf35_experts(p : &mut Prefill35, layer : &Qwen35Layer, c : &Config, n : i32, tiles : i32) -> void { + let k = c.experts_per_token; + let experts = c.num_experts; + let inter = c.moe_intermediate_size; + let shared = c.shared_expert_inter; + pf_mm_bf16(&mut p.router, &layer.router, &p.xn, &p.rows, &p.zeros, 0, &p.no_bias, false, false, experts + 1, c.hidden_size, tiles); + pf_top_k(&mut p.ids, &mut p.wts, &p.router, n, experts, k); + let e_tiles = p.e_rows.len() / 16; + pf_count_experts(&mut p.e_counts, &mut p.e_lane_counts, &p.ids, n, k, experts); + pf_place_experts(&p.e_rows, &p.slot, &p.e_counts, &p.e_lane_counts, &p.ids, n, k, experts); + pf_expert_bases(&mut p.e_bases, &p.e_counts, experts, e_tiles); + pf_mm(&mut p.e_gu, &layer.gate_up, &p.xn, &p.e_rows, &p.e_bases, 2 * inter, &p.no_bias, false, false, 2 * inter, c.hidden_size, e_tiles); + pf_silu_mul(&mut p.e_h, &p.e_gu, e_tiles * 16, inter); + pf_mm(&mut p.e_out, &layer.down, &p.e_h, &p.e_ident, &p.e_bases, c.hidden_size, &p.no_bias, false, false, c.hidden_size, inter, e_tiles); + pf_combine(&mut p.x, &p.e_out, &p.wts, &p.slot, n, k, c.hidden_size); + pf_mm(&mut p.s_gu, &layer.shared_gate_up, &p.xn, &p.rows, &p.zeros, 0, &p.no_bias, false, false, 2 * shared, c.hidden_size, tiles); + pf_silu_mul(&mut p.s_h, &p.s_gu, n, shared); + pf_mm(&mut p.s_out, &layer.shared_down, &p.s_h, &p.rows, &p.zeros, 0, &p.no_bias, false, false, c.hidden_size, shared, tiles); + pf35_add_shared(&mut p.x, &p.s_out, &p.router, experts, n, c.hidden_size); + return; +} + +// ------------------------------------------------------------------------------- chunk --- + +/// Runs tokens start to start + n - 1 of the prompt, in `p.tokens`, through every layer. The state +/// of each layer is updated, and the hidden states go to p.x. +fn pf35_chunk(w : &Qwen35Weights, s : &mut Qwen35State, p : &mut Prefill35, start : i32, n : i32) -> void { + let c = &w.config; + let eps = c.rms_norm_eps as f32; + let tiles = (n + 15) / 16; + let kh = c.linear_k_heads; + let vh = c.linear_v_heads; + let z_at = (2 * kh + vh) * 128; + let b_at = z_at + vh * 128; + let a_at = b_at + vh; + let qkv_rows = (2 * c.num_q_heads + 2 * c.num_kv_heads) * 256; + pf_embed(&mut p.x, &w.embed, &p.tokens, n, c.hidden_size); + let mut l = 0; + for ls in s.layers.iter_mut() { + let layer = &w.layers[l]; + pf35_rms_norm(&mut p.xn, &p.x, &layer.attn_norm, n, c.hidden_size, eps); + if layer.full_attention { + pf_mm(&mut p.proj, &layer.qkv, &p.xn, &p.rows, &p.zeros, 0, &p.no_bias, false, false, qkv_rows, c.hidden_size, tiles); + pf_gated_norm_rope_and_store(&mut p.q, &mut ls.k, &mut ls.v, &p.proj, &layer.q_norm, &layer.k_norm, &s.cos, &s.sin, start, n, c.num_q_heads, c.num_kv_heads, c.rotary_dim, eps); + pf_gated_attention(&mut p.y, &mut p.parts, &p.q, &ls.k, &ls.v, &p.proj, start, n, c.num_q_heads, c.num_kv_heads); + // The product goes to xn, which is free until the norm, as in `pf_chunk`. + pf_mm(&mut p.xn, &layer.attn_out, &p.y, &p.rows, &p.zeros, 0, &p.no_bias, false, false, c.hidden_size, c.num_q_heads * 256, tiles); + } else { + pf_mm(&mut p.proj, &layer.linear_in, &p.xn, &p.rows, &p.zeros, 0, &p.no_bias, false, false, a_at + vh, c.hidden_size, tiles); + pf_dn_conv(&mut p.dq, &mut p.dk, &mut p.dv, &ls.conv, &p.proj, &layer.conv, n, kh, vh); + pf_dn_conv_state(&mut ls.conv, &p.proj, n, 2 * kh + vh); + pf_dn_gates(&mut p.beta, &mut p.decay, &p.proj, &layer.neg_a, &layer.dt_bias, b_at, a_at, n, vh); + pf_dn_recur(&mut p.o, &mut ls.s, &p.dq, &p.dk, &p.dv, &p.beta, &p.decay, vh / kh, n, vh); + pf_dn_gated_norm(&mut p.y, &p.o, &p.proj, &layer.linear_norm, z_at, n, vh, eps); + pf_mm(&mut p.xn, &layer.linear_out, &p.y, &p.rows, &p.zeros, 0, &p.no_bias, false, false, c.hidden_size, vh * 128, tiles); + } + pf35_add_rms_norm(&mut p.x, &mut p.xn, &layer.mlp_norm, n, c.hidden_size, eps); + pf35_experts(p, layer, c, n, tiles); + l = l + 1; + } + return; +} + +/// Runs the prompt through every layer, in chunks of up to CHUNK tokens, from position 0. The +/// hidden state of the last token is then in `s.x`, as after `run_qwen35_layers`, so +/// `predict_qwen35` gives the next token. +fn prefill_qwen35(w : &Qwen35Weights, s : &mut Qwen35State, prompt : &Vec) -> void { + let c = &w.config; + let count = prompt.len(); + assert(count > 0 && count <= s.max_seq, "prefill_qwen35: the prompt must have tokens and fit in the state"); + let chunk = i32::min(CHUNK, (count + 15) / 16 * 16); + let mut p = new_prefill35(c, chunk); + let mut start = 0; + let mut last = 0; + while start < count { + let n = i32::min(chunk, count - start); + let mut ids = Tensor([chunk]); + let mut rows = Tensor([p.rows.len()]); + for t in 0..p.rows.len() { + rows[t] = -1; + if t < n { + rows[t] = t; + } + } + for t in 0..chunk { + if t < n { + ids[t] = prompt[start + t]; + } else { + ids[t] = 0; + } + } + p.tokens = transfer(ids, Memory::HBM); + p.rows = transfer(rows, Memory::HBM); + pf35_chunk(w, s, &mut p, start, n); + last = n; + start = start + n; + } + pf_take_row(&mut s.x, &p.x, last - 1, c.hidden_size); + return; +} diff --git a/tests/generate_qwen35.vx b/tests/generate_qwen35.vx index c6101fc..5820b31 100644 --- a/tests/generate_qwen35.vx +++ b/tests/generate_qwen35.vx @@ -3,8 +3,12 @@ // within the tolerance of the reference: // - the bf16 file, with the bf16 kernels of the experts // - the Q4_0 file with a 6-bit lm_head, with the Q4_0 kernels -// - the Q4_0 file after a prompt of 2,100 tokens, so the full attention layer goes past position -// 2,048, where its blocks take 64 SIMD groups for each head in place of 32 +// - the bf16 and the Q4_0 files after a prompt of 2,100 tokens. So the prompt runs in 2 chunks +// (the state of each layer goes from one chunk to the next), and the full attention layer goes +// past position 2,048, where its blocks take 64 SIMD groups for each head in place of 32. +// +// The products of a chunk round each Q4_0 weight, (code - 8) times its scale, to f16, as for the +// Qwen3 models. So the Q4_0 files get 0.003, as in tests/prefill.vx, and the bf16 files 0.001. // // The tiny model has the head sizes of Qwen3.6-35B-A3B (DeltaNet heads of 128, attention heads of // 256 with RoPE on 64), so it runs the kernels of the real model. @@ -16,13 +20,18 @@ // RUN: python3 %S/../scripts/make_tiny_model.py --qwen35 --q4 --q6-lm-head %t-q4.vxw > /dev/null // RUN: python3 %S/../scripts/reference.py %t-q4.vxw --tokens 1,2,3,4 --steps 16 > %t-q4.reference // RUN: vxc %S/../src/main.vx --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx -- %t-q4.vxw --tokens 1,2,3,4 --steps 16 > %t-q4.vx -// RUN: python3 %S/../scripts/compare.py %t-q4.reference %t-q4.vx --tolerance 0.002 | FileCheck %s --check-prefix=Q4 +// RUN: python3 %S/../scripts/compare.py %t-q4.reference %t-q4.vx --tolerance 0.003 | FileCheck %s --check-prefix=Q4 // RUN: python3 -c "print(','.join(str(i * 37 % 256) for i in range(2100)))" > %t-long.ids +// RUN: python3 %S/../scripts/make_tiny_model.py --qwen35 --max-positions 2200 %t-long-bf16.vxw > /dev/null +// RUN: python3 %S/../scripts/reference.py %t-long-bf16.vxw --tokens $(cat %t-long.ids) --steps 8 > %t-long-bf16.reference +// RUN: vxc %S/../src/main.vx --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx -- %t-long-bf16.vxw --tokens $(cat %t-long.ids) --steps 8 > %t-long-bf16.vx +// RUN: python3 %S/../scripts/compare.py %t-long-bf16.reference %t-long-bf16.vx --tolerance 0.001 | FileCheck %s --check-prefix=LONG-BF16 // RUN: python3 %S/../scripts/make_tiny_model.py --qwen35 --q4 --q6-lm-head --max-positions 2200 %t-long.vxw > /dev/null // RUN: python3 %S/../scripts/reference.py %t-long.vxw --tokens $(cat %t-long.ids) --steps 8 > %t-long.reference // RUN: vxc %S/../src/main.vx --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx -- %t-long.vxw --tokens $(cat %t-long.ids) --steps 8 > %t-long.vx -// RUN: python3 %S/../scripts/compare.py %t-long.reference %t-long.vx --tolerance 0.002 | FileCheck %s --check-prefix=LONG +// RUN: python3 %S/../scripts/compare.py %t-long.reference %t-long.vx --tolerance 0.003 | FileCheck %s --check-prefix=LONG // // CHECK: 16 steps, same tokens, logits within 0.001 -// Q4: 16 steps, same tokens, logits within 0.002 -// LONG: 8 steps, same tokens, logits within 0.002 +// Q4: 16 steps, same tokens, logits within 0.003 +// LONG-BF16: 8 steps, same tokens, logits within 0.001 +// LONG: 8 steps, same tokens, logits within 0.003 From be863cbaf00e5d8ce66324d1034676cf709991a0 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:46:34 -0800 Subject: [PATCH 13/60] qwen app: flash attention for the prompt of Qwen3.5/Qwen3.6 (#89) pf_gated_flash_attention is pf_flash_attention for heads of 256 values, with the output gate sigmoid(gate) in its last step. A threadgroup does 8 tokens of one query head, in steps of 64 positions, with simdgroup matrices for Q K^T and P V. scripts/mlir_kernels/gated_flash_attention.py writes it. It replaces the parts-and-merge kernels of the chunk, which read K and V again for each token. The KV caches of arch 1 now have a multiple of 64 rows, as those of arch 0. The long bf16 test (2,100 tokens, 2 chunks) matches reference.py within 4.6e-5 (4.8e-5 before). All 89 checks pass. On the real Qwen3.6-35B-A3B Q4_0 file, the 24 greedy tokens of "def fibonacci(n):" are those of reference.py. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- scripts/mlir_kernels/gated_flash_attention.py | 220 +++++++ src/prefill35.vx | 545 ++++++++++++------ src/qwen35.vx | 6 +- 3 files changed, 607 insertions(+), 164 deletions(-) create mode 100644 scripts/mlir_kernels/gated_flash_attention.py 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/src/prefill35.vx b/src/prefill35.vx index 5cd8e4b..9a57e35 100644 --- a/src/prefill35.vx +++ b/src/prefill35.vx @@ -12,26 +12,20 @@ // // - The DeltaNet of a chunk. The convolution and the norms run for all the tokens at once. The // update of the state runs the tokens in order, in one kernel that keeps S in registers. -// - The gated attention of a chunk: the kernels of src/gated_attention.vx for ATT_TOKENS tokens -// at a time, each with ATT_GROUPS SIMD groups for each head. +// - The gated attention of a chunk: a flash attention for heads of 256 values, as +// `pf_flash_attention`, with the gate in its last step. // - The shared expert, as a dense SwiGLU over the chunk, times sigmoid(its gate). import core::convert; import core::num; import std::nn; import std::vec; import qwen::deltanet; -import qwen::gated_attention; import qwen::model; import qwen::prefill; import qwen::qwen35; import qwen::simd; import qwen::weights; -/// The tokens of a chunk that the attention takes at a time, and the SIMD groups of each head and -/// token. The scratch space of the parts is ATT_TOKENS x q_heads x ATT_GROUPS x 260 values. -const ATT_TOKENS : i32 = 64; -const ATT_GROUPS : i32 = 8; - /// The tensors of a chunk, made once. `rows`, `zeros` and the `e_` tensors are those of `Prefill`. /// `proj` is the output of `qkv` or `linear_in` for each token, and `y` the input of `attn_out` or /// `linear_out`. The `d` tensors are those of the DeltaNet, and the `s_` tensors those of the shared @@ -47,7 +41,6 @@ struct Prefill35 { proj : Tensor, y : Tensor, q : Tensor, - parts : Tensor, dq : Tensor, dk : Tensor, dv : Tensor, @@ -97,7 +90,6 @@ fn new_prefill35(c : &Config, chunk : i32) -> Prefill35 { proj: transfer(Tensor([cap, i32::max(qkv_rows, in_rows)]), Memory::HBM), y: transfer(Tensor([cap, i32::max(c.num_q_heads * 256, vh * 128)]), Memory::HBM), q: transfer(Tensor([chunk, c.num_q_heads, 256]), Memory::HBM), - parts: transfer(Tensor([ATT_TOKENS, c.num_q_heads, ATT_GROUPS, 260]), Memory::HBM), dq: transfer(Tensor([chunk, kh, 128]), Memory::HBM), dk: transfer(Tensor([chunk, kh, 128]), Memory::HBM), dv: transfer(Tensor([chunk, vh, 128]), Memory::HBM), @@ -578,169 +570,398 @@ fn pf_gated_norm_rope_and_store(q_out : &mut Tensor return; } -/// The attention of tokens first to first + m - 1 of the chunk, as `gated_attention_parts` for each: -/// block (tt, h, w) is a SIMD group for head h of token first + tt, at position start + first + tt. -/// It does the blocks of 32 positions w, w + ATT_GROUPS, ... up to that position. -fn pf_gated_attention_parts(part : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, start : i32, first : i32, m : i32, q_heads : i32, group : i32, scale : f32) -> void { +/// y[t][h * 256 + d] = the attention of query head h of token t (at position start + t) over the +/// positions up to start + t, times sigmoid(qkvg[t][gate_at + h * 256 + d]), for t below n: the +/// gated attention of `gated_attention`. A threadgroup does 8 tokens of one query head, in steps of 64 +/// positions, as `pf_flash_attention` and llama.cpp's kernel_flash_attn_ext. The caches are +/// [position, kv_heads, 256] f16, with a multiple of 64 positions. K and V go from the cache straight +/// into simdgroup matrices, K transposed; Q (as f16), the scores, the weights (as f16) and the sums +/// of the 8 tokens are in shared memory. The softmax is online, in all the lanes of a subgroup. +/// +/// The design is that of llama.cpp (ggml/src/ggml-metal/kernels/fa_common.metal), MIT License, +/// Copyright (c) 2023-2026 The ggml authors. +/// +/// scripts/mlir_kernels/gated_flash_attention.py writes this function: change that script, not the +/// MLIR. +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 { + assert(q.extent(2) == 256 && k_cache.extent(2) == 256 && k_cache.extent(0) % 64 == 0 && start + n <= k_cache.extent(0), "pf_gated_flash_attention: heads of 256 values, and a KV cache of a multiple of 64 positions"); spawn on(Topology::Device) { - for tt in 0..m across blocks { + for qb in 0..(n + 7) / 8 across blocks { for h in 0..q_heads across blocks { - for w in 0..8 across blocks { - let mut stats = unsafe { Tensor::uninit() }; - for s in 0..1 across subgroups { - for l in 0..32 across lanes(32) { - let t = first + tt; - let pos = start + t; - 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; - 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 + 8; - } - part[tt][h][w][d] = o0; - part[tt][h][w][d + 1] = o1; - part[tt][h][w][d + 2] = o2; - part[tt][h][w][d + 3] = o3; - part[tt][h][w][d + 4] = o4; - part[tt][h][w][d + 5] = o5; - part[tt][h][w][d + 6] = o6; - part[tt][h][w][d + 7] = o7; - if l < 2 { - let mut x = big; - if l == 1 { - x = total; - } - stats[s][l] = x; - } + let mut sq = unsafe { Tensor::uninit() }; + let mut so = unsafe { Tensor::uninit() }; + let mut ss = unsafe { Tensor::uninit() }; + let mut sp = unsafe { Tensor::uninit() }; + let _d = mlir!( threads : 128, inputs : (%sq = &mut sq : memref<2048xf16, 3>, %so = &mut so : memref<2048xf32, 3>, %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 * 256..h * 256 + 256])]) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %c2 = arith.constant 2 : index + %c4 = arith.constant 4 : index + %c8 = arith.constant 8 : index + %c12 = arith.constant 12 : index + %c16 = arith.constant 16 : index + %c32 = arith.constant 32 : index + %c64 = arith.constant 64 : index + %c256 = arith.constant 256 : index + %tid = gpu.thread_id x + %sg = arith.divui %tid, %c32 : index + %l = arith.remui %tid, %c32 : index + %qbi = arith.index_cast %qb : i32 to index + %hi = arith.index_cast %h : i32 to index + %ni = arith.index_cast %n : i32 to index + %starti = arith.index_cast %start : i32 to index + %groupi = arith.index_cast %group : i32 to index + %gatei = arith.index_cast %gate_at : i32 to index + %g = arith.divui %hi, %groupi : index + %gD = arith.muli %g, %c256 : index + %P = memref.dim %k3, %c0 : memref + %KH = memref.dim %k3, %c1 : memref + %Wd = arith.muli %KH, %c256 : 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> + %t0 = arith.muli %qbi, %c8 : index + %qj = arith.divui %tid, %c16 : index + %qm = arith.remui %tid, %c16 : index + %qc = arith.muli %qm, %c16 : index + %qt = arith.addi %t0, %qj : index + %nm1 = arith.subi %ni, %c1 : index + %qtc = arith.minui %qt, %nm1 : index + %qlive = arith.cmpi ult, %qt, %ni : index + %vz4 = arith.constant dense<0.0> : vector<4xf32> + %sqo = arith.muli %qj, %c256 : index + %sqa = arith.addi %sqo, %qc : index + %qc0 = arith.addi %qc, %c0 : index + %sq0 = arith.addi %sqa, %c0 : index + %q0r = vector.load %q[%qtc, %hi, %qc0] : memref, vector<4xf32> + %q0 = arith.select %qlive, %q0r, %vz4 : vector<4xf32> + %q0h = arith.truncf %q0 : vector<4xf32> to vector<4xf16> + vector.store %q0h, %sq[%sq0] : memref<2048xf16, 3>, vector<4xf16> + vector.store %vz4, %so[%sq0] : memref<2048xf32, 3>, vector<4xf32> + %qc1 = arith.addi %qc, %c4 : index + %sq1 = arith.addi %sqa, %c4 : index + %q1r = vector.load %q[%qtc, %hi, %qc1] : memref, vector<4xf32> + %q1 = arith.select %qlive, %q1r, %vz4 : vector<4xf32> + %q1h = arith.truncf %q1 : vector<4xf32> to vector<4xf16> + vector.store %q1h, %sq[%sq1] : memref<2048xf16, 3>, vector<4xf16> + vector.store %vz4, %so[%sq1] : memref<2048xf32, 3>, vector<4xf32> + %qc2 = arith.addi %qc, %c8 : index + %sq2 = arith.addi %sqa, %c8 : index + %q2r = vector.load %q[%qtc, %hi, %qc2] : memref, vector<4xf32> + %q2 = arith.select %qlive, %q2r, %vz4 : vector<4xf32> + %q2h = arith.truncf %q2 : vector<4xf32> to vector<4xf16> + vector.store %q2h, %sq[%sq2] : memref<2048xf16, 3>, vector<4xf16> + vector.store %vz4, %so[%sq2] : memref<2048xf32, 3>, vector<4xf32> + %qc3 = arith.addi %qc, %c12 : index + %sq3 = arith.addi %sqa, %c12 : index + %q3r = vector.load %q[%qtc, %hi, %qc3] : memref, vector<4xf32> + %q3 = arith.select %qlive, %q3r, %vz4 : vector<4xf32> + %q3h = arith.truncf %q3 : vector<4xf32> to vector<4xf16> + vector.store %q3h, %sq[%sq3] : memref<2048xf16, 3>, vector<4xf16> + vector.store %vz4, %so[%sq3] : memref<2048xf32, 3>, vector<4xf32> + gpu.barrier + %tl = arith.addi %t0, %c8 : index + %tlc = arith.minui %tl, %ni : index + %lastq = arith.subi %tlc, %c1 : index + %lastp = arith.addi %starti, %lastq : index + %nblk0 = arith.divui %lastp, %c64 : index + %nblk = arith.addi %nblk0, %c1 : index + %j0 = arith.addi %sg, %c0 : index + %j1 = arith.addi %sg, %c4 : index + %qt0 = arith.addi %t0, %j0 : index + %qp0 = arith.addi %starti, %qt0 : index + %qt1 = arith.addi %t0, %j1 : index + %qp1 = arith.addi %starti, %qt1 : index + %neg = arith.constant -3.0e38 : f32 + %zero = arith.constant 0.0 : f32 + %l2 = arith.muli %l, %c2 : index + %l8 = arith.muli %l, %c8 : index + %zacc = gpu.subgroup_mma_constant_matrix %zero : !gpu.mma_matrix<8x8xf32, "COp"> + %st:4 = scf.for %kb = %c0 to %nblk step %c1 iter_args(%M0 = %neg, %S0 = %zero, %M1 = %neg, %S1 = %zero) -> (f32, f32, f32, f32) { + %p0 = arith.muli %kb, %c64 : index + %sg8 = arith.muli %sg, %c8 : index + %kc0 = arith.addi %sg8, %c0 : index + %kp0 = arith.addi %p0, %kc0 : index + %qk0 = scf.for %i = %c0 to %c32 step %c1 iter_args(%a = %zacc) -> (!gpu.mma_matrix<8x8xf32, "COp">) { + %d0 = arith.muli %i, %c8 : index + %mq = gpu.subgroup_mma_load_matrix %sq[%d0] {leadDimension = 256 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %kd = arith.addi %gD, %d0 : index + %mk = gpu.subgroup_mma_load_matrix %k[%kp0, %kd] {leadDimension = 0 : index, transpose} : memref> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %a2 = gpu.subgroup_mma_compute %mq, %mk, %a : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + scf.yield %a2 : !gpu.mma_matrix<8x8xf32, "COp"> } - for l in 0..2 across lanes(32) { - part[tt][h][w][256 + l] = stats[s][l]; + gpu.subgroup_mma_store_matrix %qk0, %ss[%kc0] {leadDimension = 64 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref<512xf32, 3> + %kc1 = arith.addi %sg8, %c32 : index + %kp1 = arith.addi %p0, %kc1 : index + %qk1 = scf.for %i = %c0 to %c32 step %c1 iter_args(%a = %zacc) -> (!gpu.mma_matrix<8x8xf32, "COp">) { + %d0 = arith.muli %i, %c8 : index + %mq = gpu.subgroup_mma_load_matrix %sq[%d0] {leadDimension = 256 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %kd = arith.addi %gD, %d0 : index + %mk = gpu.subgroup_mma_load_matrix %k[%kp1, %kd] {leadDimension = 0 : index, transpose} : memref> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %a2 = gpu.subgroup_mma_compute %mq, %mk, %a : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + scf.yield %a2 : !gpu.mma_matrix<8x8xf32, "COp"> } - } - } - } - } - } - return; -} - -/// Merges the 8 parts of each head of tokens first to first + m - 1, and multiplies by sigmoid of -/// the gate, as `gated_attention_merge`. -fn pf_gated_attention_merge(y : &mut Tensor, part : &Tensor, qkvg : &Tensor, first : i32, m : i32, q_heads : i32, gate_at : i32) -> void { - spawn on(Topology::Device) { - for tt in 0..m across blocks { - for h in 0..q_heads across blocks { - for dq in 0..8 across blocks { - for s in 0..1 across subgroups { - for l in 0..32 across lanes(32) { - let t = first + tt; - let d = dq * 32 + l; - let mut big : f32 = -3.0e38; - for c in 0..8 { - big = big.max(part[tt][h][c][256]); - } - let mut total : f32 = 0.0; - let mut acc : f32 = 0.0; - for c in 0..8 { - let w = (part[tt][h][c][256] - big).fast_exp(); - total = total + w * part[tt][h][c][257]; - acc = acc + w * part[tt][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()); + gpu.subgroup_mma_store_matrix %qk1, %ss[%kc1] {leadDimension = 64 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref<512xf32, 3> + gpu.barrier + %r0 = arith.muli %j0, %c64 : index + %ia0 = arith.addi %r0, %l2 : index + %ib0 = arith.addi %ia0, %c1 : index + %sa0r = memref.load %ss[%ia0] : memref<512xf32, 3> + %sb0r = memref.load %ss[%ib0] : memref<512xf32, 3> + %sa0s = arith.mulf %sa0r, %scale : f32 + %sb0s = arith.mulf %sb0r, %scale : f32 + %pa0 = arith.addi %p0, %l2 : index + %pb0 = arith.addi %pa0, %c1 : index + %oka0 = arith.cmpi ule, %pa0, %qp0 : index + %okb0 = arith.cmpi ule, %pb0, %qp0 : index + %sa0 = arith.select %oka0, %sa0s, %neg : f32 + %sb0 = arith.select %okb0, %sb0s, %neg : f32 + %mx0 = arith.maxnumf %sa0, %sb0 : f32 + %bm0 = gpu.subgroup_reduce maxnumf %mx0 : (f32) -> f32 + %Mn0 = arith.maxnumf %M0, %bm0 : f32 + %dm0 = arith.subf %M0, %Mn0 : f32 + %ms0 = math.exp %dm0 : f32 + %ea0 = arith.subf %sa0, %Mn0 : f32 + %eb0 = arith.subf %sb0, %Mn0 : f32 + %xa0 = math.exp %ea0 : f32 + %xb0 = math.exp %eb0 : f32 + %xs0 = arith.addf %xa0, %xb0 : f32 + %bs0 = gpu.subgroup_reduce add %xs0 : (f32) -> f32 + %Ss0 = arith.mulf %S0, %ms0 : f32 + %Sn0 = arith.addf %Ss0, %bs0 : f32 + %ha0 = arith.truncf %xa0 : f32 to f16 + %hb0 = arith.truncf %xb0 : f32 to f16 + memref.store %ha0, %sp[%ia0] : memref<512xf16, 3> + memref.store %hb0, %sp[%ib0] : memref<512xf16, 3> + %or0 = arith.muli %j0, %c256 : index + %oi0 = arith.addi %or0, %l8 : index + %oj0 = arith.addi %oi0, %c4 : index + %msv0 = vector.broadcast %ms0 : f32 to vector<4xf32> + %ov0a = vector.load %so[%oi0] : memref<2048xf32, 3>, vector<4xf32> + %ow0a = arith.mulf %ov0a, %msv0 : vector<4xf32> + vector.store %ow0a, %so[%oi0] : memref<2048xf32, 3>, vector<4xf32> + %ov0b = vector.load %so[%oj0] : memref<2048xf32, 3>, vector<4xf32> + %ow0b = arith.mulf %ov0b, %msv0 : vector<4xf32> + vector.store %ow0b, %so[%oj0] : memref<2048xf32, 3>, vector<4xf32> + %r1 = arith.muli %j1, %c64 : index + %ia1 = arith.addi %r1, %l2 : index + %ib1 = arith.addi %ia1, %c1 : index + %sa1r = memref.load %ss[%ia1] : memref<512xf32, 3> + %sb1r = memref.load %ss[%ib1] : memref<512xf32, 3> + %sa1s = arith.mulf %sa1r, %scale : f32 + %sb1s = arith.mulf %sb1r, %scale : f32 + %pa1 = arith.addi %p0, %l2 : index + %pb1 = arith.addi %pa1, %c1 : index + %oka1 = arith.cmpi ule, %pa1, %qp1 : index + %okb1 = arith.cmpi ule, %pb1, %qp1 : index + %sa1 = arith.select %oka1, %sa1s, %neg : f32 + %sb1 = arith.select %okb1, %sb1s, %neg : f32 + %mx1 = arith.maxnumf %sa1, %sb1 : f32 + %bm1 = gpu.subgroup_reduce maxnumf %mx1 : (f32) -> f32 + %Mn1 = arith.maxnumf %M1, %bm1 : f32 + %dm1 = arith.subf %M1, %Mn1 : f32 + %ms1 = math.exp %dm1 : f32 + %ea1 = arith.subf %sa1, %Mn1 : f32 + %eb1 = arith.subf %sb1, %Mn1 : f32 + %xa1 = math.exp %ea1 : f32 + %xb1 = math.exp %eb1 : f32 + %xs1 = arith.addf %xa1, %xb1 : f32 + %bs1 = gpu.subgroup_reduce add %xs1 : (f32) -> f32 + %Ss1 = arith.mulf %S1, %ms1 : f32 + %Sn1 = arith.addf %Ss1, %bs1 : f32 + %ha1 = arith.truncf %xa1 : f32 to f16 + %hb1 = arith.truncf %xb1 : f32 to f16 + memref.store %ha1, %sp[%ia1] : memref<512xf16, 3> + memref.store %hb1, %sp[%ib1] : memref<512xf16, 3> + %or1 = arith.muli %j1, %c256 : index + %oi1 = arith.addi %or1, %l8 : index + %oj1 = arith.addi %oi1, %c4 : index + %msv1 = vector.broadcast %ms1 : f32 to vector<4xf32> + %ov1a = vector.load %so[%oi1] : memref<2048xf32, 3>, vector<4xf32> + %ow1a = arith.mulf %ov1a, %msv1 : vector<4xf32> + vector.store %ow1a, %so[%oi1] : memref<2048xf32, 3>, vector<4xf32> + %ov1b = vector.load %so[%oj1] : memref<2048xf32, 3>, vector<4xf32> + %ow1b = arith.mulf %ov1b, %msv1 : vector<4xf32> + vector.store %ow1b, %so[%oj1] : memref<2048xf32, 3>, vector<4xf32> + gpu.barrier + %dv0c = arith.constant 0 : index + %dv0 = arith.addi %sg8, %dv0c : index + %o0i = gpu.subgroup_mma_load_matrix %so[%dv0] {leadDimension = 256 : index} : memref<2048xf32, 3> -> !gpu.mma_matrix<8x8xf32, "COp"> + %vd0 = arith.addi %gD, %dv0 : index + %o0 = scf.for %kk = %c0 to %c8 step %c1 iter_args(%o = %o0i) -> (!gpu.mma_matrix<8x8xf32, "COp">) { + %k8 = arith.muli %kk, %c8 : index + %mp = gpu.subgroup_mma_load_matrix %sp[%k8] {leadDimension = 64 : index} : memref<512xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %vp = arith.addi %p0, %k8 : index + %mv = gpu.subgroup_mma_load_matrix %v[%vp, %vd0] {leadDimension = 0 : index} : memref> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %onx = gpu.subgroup_mma_compute %mp, %mv, %o : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + scf.yield %onx : !gpu.mma_matrix<8x8xf32, "COp"> } + gpu.subgroup_mma_store_matrix %o0, %so[%dv0] {leadDimension = 256 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref<2048xf32, 3> + %dv1c = arith.constant 32 : index + %dv1 = arith.addi %sg8, %dv1c : index + %o1i = gpu.subgroup_mma_load_matrix %so[%dv1] {leadDimension = 256 : index} : memref<2048xf32, 3> -> !gpu.mma_matrix<8x8xf32, "COp"> + %vd1 = arith.addi %gD, %dv1 : index + %o1 = scf.for %kk = %c0 to %c8 step %c1 iter_args(%o = %o1i) -> (!gpu.mma_matrix<8x8xf32, "COp">) { + %k8 = arith.muli %kk, %c8 : index + %mp = gpu.subgroup_mma_load_matrix %sp[%k8] {leadDimension = 64 : index} : memref<512xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %vp = arith.addi %p0, %k8 : index + %mv = gpu.subgroup_mma_load_matrix %v[%vp, %vd1] {leadDimension = 0 : index} : memref> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %onx = gpu.subgroup_mma_compute %mp, %mv, %o : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + scf.yield %onx : !gpu.mma_matrix<8x8xf32, "COp"> + } + gpu.subgroup_mma_store_matrix %o1, %so[%dv1] {leadDimension = 256 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref<2048xf32, 3> + %dv2c = arith.constant 64 : index + %dv2 = arith.addi %sg8, %dv2c : index + %o2i = gpu.subgroup_mma_load_matrix %so[%dv2] {leadDimension = 256 : index} : memref<2048xf32, 3> -> !gpu.mma_matrix<8x8xf32, "COp"> + %vd2 = arith.addi %gD, %dv2 : index + %o2 = scf.for %kk = %c0 to %c8 step %c1 iter_args(%o = %o2i) -> (!gpu.mma_matrix<8x8xf32, "COp">) { + %k8 = arith.muli %kk, %c8 : index + %mp = gpu.subgroup_mma_load_matrix %sp[%k8] {leadDimension = 64 : index} : memref<512xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %vp = arith.addi %p0, %k8 : index + %mv = gpu.subgroup_mma_load_matrix %v[%vp, %vd2] {leadDimension = 0 : index} : memref> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %onx = gpu.subgroup_mma_compute %mp, %mv, %o : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + scf.yield %onx : !gpu.mma_matrix<8x8xf32, "COp"> + } + gpu.subgroup_mma_store_matrix %o2, %so[%dv2] {leadDimension = 256 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref<2048xf32, 3> + %dv3c = arith.constant 96 : index + %dv3 = arith.addi %sg8, %dv3c : index + %o3i = gpu.subgroup_mma_load_matrix %so[%dv3] {leadDimension = 256 : index} : memref<2048xf32, 3> -> !gpu.mma_matrix<8x8xf32, "COp"> + %vd3 = arith.addi %gD, %dv3 : index + %o3 = scf.for %kk = %c0 to %c8 step %c1 iter_args(%o = %o3i) -> (!gpu.mma_matrix<8x8xf32, "COp">) { + %k8 = arith.muli %kk, %c8 : index + %mp = gpu.subgroup_mma_load_matrix %sp[%k8] {leadDimension = 64 : index} : memref<512xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %vp = arith.addi %p0, %k8 : index + %mv = gpu.subgroup_mma_load_matrix %v[%vp, %vd3] {leadDimension = 0 : index} : memref> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %onx = gpu.subgroup_mma_compute %mp, %mv, %o : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + scf.yield %onx : !gpu.mma_matrix<8x8xf32, "COp"> + } + gpu.subgroup_mma_store_matrix %o3, %so[%dv3] {leadDimension = 256 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref<2048xf32, 3> + %dv4c = arith.constant 128 : index + %dv4 = arith.addi %sg8, %dv4c : index + %o4i = gpu.subgroup_mma_load_matrix %so[%dv4] {leadDimension = 256 : index} : memref<2048xf32, 3> -> !gpu.mma_matrix<8x8xf32, "COp"> + %vd4 = arith.addi %gD, %dv4 : index + %o4 = scf.for %kk = %c0 to %c8 step %c1 iter_args(%o = %o4i) -> (!gpu.mma_matrix<8x8xf32, "COp">) { + %k8 = arith.muli %kk, %c8 : index + %mp = gpu.subgroup_mma_load_matrix %sp[%k8] {leadDimension = 64 : index} : memref<512xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %vp = arith.addi %p0, %k8 : index + %mv = gpu.subgroup_mma_load_matrix %v[%vp, %vd4] {leadDimension = 0 : index} : memref> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %onx = gpu.subgroup_mma_compute %mp, %mv, %o : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + scf.yield %onx : !gpu.mma_matrix<8x8xf32, "COp"> + } + gpu.subgroup_mma_store_matrix %o4, %so[%dv4] {leadDimension = 256 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref<2048xf32, 3> + %dv5c = arith.constant 160 : index + %dv5 = arith.addi %sg8, %dv5c : index + %o5i = gpu.subgroup_mma_load_matrix %so[%dv5] {leadDimension = 256 : index} : memref<2048xf32, 3> -> !gpu.mma_matrix<8x8xf32, "COp"> + %vd5 = arith.addi %gD, %dv5 : index + %o5 = scf.for %kk = %c0 to %c8 step %c1 iter_args(%o = %o5i) -> (!gpu.mma_matrix<8x8xf32, "COp">) { + %k8 = arith.muli %kk, %c8 : index + %mp = gpu.subgroup_mma_load_matrix %sp[%k8] {leadDimension = 64 : index} : memref<512xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %vp = arith.addi %p0, %k8 : index + %mv = gpu.subgroup_mma_load_matrix %v[%vp, %vd5] {leadDimension = 0 : index} : memref> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %onx = gpu.subgroup_mma_compute %mp, %mv, %o : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + scf.yield %onx : !gpu.mma_matrix<8x8xf32, "COp"> + } + gpu.subgroup_mma_store_matrix %o5, %so[%dv5] {leadDimension = 256 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref<2048xf32, 3> + %dv6c = arith.constant 192 : index + %dv6 = arith.addi %sg8, %dv6c : index + %o6i = gpu.subgroup_mma_load_matrix %so[%dv6] {leadDimension = 256 : index} : memref<2048xf32, 3> -> !gpu.mma_matrix<8x8xf32, "COp"> + %vd6 = arith.addi %gD, %dv6 : index + %o6 = scf.for %kk = %c0 to %c8 step %c1 iter_args(%o = %o6i) -> (!gpu.mma_matrix<8x8xf32, "COp">) { + %k8 = arith.muli %kk, %c8 : index + %mp = gpu.subgroup_mma_load_matrix %sp[%k8] {leadDimension = 64 : index} : memref<512xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %vp = arith.addi %p0, %k8 : index + %mv = gpu.subgroup_mma_load_matrix %v[%vp, %vd6] {leadDimension = 0 : index} : memref> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %onx = gpu.subgroup_mma_compute %mp, %mv, %o : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + scf.yield %onx : !gpu.mma_matrix<8x8xf32, "COp"> + } + gpu.subgroup_mma_store_matrix %o6, %so[%dv6] {leadDimension = 256 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref<2048xf32, 3> + %dv7c = arith.constant 224 : index + %dv7 = arith.addi %sg8, %dv7c : index + %o7i = gpu.subgroup_mma_load_matrix %so[%dv7] {leadDimension = 256 : index} : memref<2048xf32, 3> -> !gpu.mma_matrix<8x8xf32, "COp"> + %vd7 = arith.addi %gD, %dv7 : index + %o7 = scf.for %kk = %c0 to %c8 step %c1 iter_args(%o = %o7i) -> (!gpu.mma_matrix<8x8xf32, "COp">) { + %k8 = arith.muli %kk, %c8 : index + %mp = gpu.subgroup_mma_load_matrix %sp[%k8] {leadDimension = 64 : index} : memref<512xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %vp = arith.addi %p0, %k8 : index + %mv = gpu.subgroup_mma_load_matrix %v[%vp, %vd7] {leadDimension = 0 : index} : memref> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %onx = gpu.subgroup_mma_compute %mp, %mv, %o : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + scf.yield %onx : !gpu.mma_matrix<8x8xf32, "COp"> + } + gpu.subgroup_mma_store_matrix %o7, %so[%dv7] {leadDimension = 256 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref<2048xf32, 3> + gpu.barrier + scf.yield %Mn0, %Sn0, %Mn1, %Sn1 : f32, f32, f32, f32 } - } + %hD = arith.muli %hi, %c256 : index + %gh = arith.addi %gatei, %hD : index + %one = arith.constant 1.0 : f32 + %one4 = arith.constant dense<1.0> : vector<4xf32> + %inv0 = arith.divf %one, %st#1 : f32 + %iv0 = vector.broadcast %inv0 : f32 to vector<4xf32> + %fr0 = arith.muli %j0, %c256 : index + %live0 = arith.cmpi ult, %qt0, %ni : index + scf.if %live0 { + %fl0a = arith.addi %l8, %c0 : index + %fi0a = arith.addi %fr0, %fl0a : index + %fv0a = vector.load %so[%fi0a] : memref<2048xf32, 3>, vector<4xf32> + %fw0a = arith.mulf %fv0a, %iv0 : vector<4xf32> + %gi0a = arith.addi %gh, %fl0a : index + %gv0a = vector.load %qkvg[%qt0, %gi0a] : memref, vector<4xf32> + %gn0a = arith.negf %gv0a : vector<4xf32> + %ge0a = math.exp %gn0a : vector<4xf32> + %gd0a = arith.addf %ge0a, %one4 : vector<4xf32> + %fg0a = arith.divf %fw0a, %gd0a : vector<4xf32> + %yc0a = arith.addi %hD, %fl0a : index + vector.store %fg0a, %y[%qt0, %yc0a] : memref, vector<4xf32> + %fl0b = arith.addi %l8, %c4 : index + %fi0b = arith.addi %fr0, %fl0b : index + %fv0b = vector.load %so[%fi0b] : memref<2048xf32, 3>, vector<4xf32> + %fw0b = arith.mulf %fv0b, %iv0 : vector<4xf32> + %gi0b = arith.addi %gh, %fl0b : index + %gv0b = vector.load %qkvg[%qt0, %gi0b] : memref, vector<4xf32> + %gn0b = arith.negf %gv0b : vector<4xf32> + %ge0b = math.exp %gn0b : vector<4xf32> + %gd0b = arith.addf %ge0b, %one4 : vector<4xf32> + %fg0b = arith.divf %fw0b, %gd0b : vector<4xf32> + %yc0b = arith.addi %hD, %fl0b : index + vector.store %fg0b, %y[%qt0, %yc0b] : memref, vector<4xf32> + } + %inv1 = arith.divf %one, %st#3 : f32 + %iv1 = vector.broadcast %inv1 : f32 to vector<4xf32> + %fr1 = arith.muli %j1, %c256 : index + %live1 = arith.cmpi ult, %qt1, %ni : index + scf.if %live1 { + %fl1a = arith.addi %l8, %c0 : index + %fi1a = arith.addi %fr1, %fl1a : index + %fv1a = vector.load %so[%fi1a] : memref<2048xf32, 3>, vector<4xf32> + %fw1a = arith.mulf %fv1a, %iv1 : vector<4xf32> + %gi1a = arith.addi %gh, %fl1a : index + %gv1a = vector.load %qkvg[%qt1, %gi1a] : memref, vector<4xf32> + %gn1a = arith.negf %gv1a : vector<4xf32> + %ge1a = math.exp %gn1a : vector<4xf32> + %gd1a = arith.addf %ge1a, %one4 : vector<4xf32> + %fg1a = arith.divf %fw1a, %gd1a : vector<4xf32> + %yc1a = arith.addi %hD, %fl1a : index + vector.store %fg1a, %y[%qt1, %yc1a] : memref, vector<4xf32> + %fl1b = arith.addi %l8, %c4 : index + %fi1b = arith.addi %fr1, %fl1b : index + %fv1b = vector.load %so[%fi1b] : memref<2048xf32, 3>, vector<4xf32> + %fw1b = arith.mulf %fv1b, %iv1 : vector<4xf32> + %gi1b = arith.addi %gh, %fl1b : index + %gv1b = vector.load %qkvg[%qt1, %gi1b] : memref, vector<4xf32> + %gn1b = arith.negf %gv1b : vector<4xf32> + %ge1b = math.exp %gn1b : vector<4xf32> + %gd1b = arith.addf %ge1b, %one4 : vector<4xf32> + %fg1b = arith.divf %fw1b, %gd1b : vector<4xf32> + %yc1b = arith.addi %hD, %fl1b : index + vector.store %fg1b, %y[%qt1, %yc1b] : memref, vector<4xf32> + } + macro.yield %qb : i32 + }; } } } return; } -/// The gated attention of the n tokens of the chunk, ATT_TOKENS at a time: y[t] for each token. -fn pf_gated_attention(y : &mut Tensor, parts : &mut Tensor, q : &Tensor, k_cache : &Tensor, v_cache : &Tensor, qkvg : &Tensor, start : i32, n : i32, q_heads : i32, kv_heads : i32) -> void { - let mut first = 0; - while first < n { - let m = i32::min(ATT_TOKENS, n - first); - pf_gated_attention_parts(parts, q, k_cache, v_cache, start, first, m, q_heads, q_heads / kv_heads, 0.0625); - pf_gated_attention_merge(y, parts, qkvg, first, m, q_heads, (q_heads + 2 * kv_heads) * 256); - first = first + m; - } - return; -} - // ------------------------------------------------------------------------------ experts --- /// x[t] += sigmoid(router[t][at]) * out[t], for t below n: the shared expert times its gate. @@ -807,7 +1028,7 @@ fn pf35_chunk(w : &Qwen35Weights, s : &mut Qwen35State, p : &mut Prefill35, star if layer.full_attention { pf_mm(&mut p.proj, &layer.qkv, &p.xn, &p.rows, &p.zeros, 0, &p.no_bias, false, false, qkv_rows, c.hidden_size, tiles); pf_gated_norm_rope_and_store(&mut p.q, &mut ls.k, &mut ls.v, &p.proj, &layer.q_norm, &layer.k_norm, &s.cos, &s.sin, start, n, c.num_q_heads, c.num_kv_heads, c.rotary_dim, eps); - pf_gated_attention(&mut p.y, &mut p.parts, &p.q, &ls.k, &ls.v, &p.proj, start, n, c.num_q_heads, c.num_kv_heads); + pf_gated_flash_attention(&mut p.y, &p.q, &ls.k, &ls.v, &p.proj, start, n, c.num_q_heads, c.num_q_heads / c.num_kv_heads, qkv_rows - c.num_q_heads * 256, 0.0625); // The product goes to xn, which is free until the norm, as in `pf_chunk`. pf_mm(&mut p.xn, &layer.attn_out, &p.y, &p.rows, &p.zeros, 0, &p.no_bias, false, false, c.hidden_size, c.num_q_heads * 256, tiles); } else { diff --git a/src/qwen35.vx b/src/qwen35.vx index 8283763..5e49016 100644 --- a/src/qwen35.vx +++ b/src/qwen35.vx @@ -78,14 +78,16 @@ fn new_qwen35_state(c : &Config, max_seq : i32) -> Qwen35State { hsin[p][i] = f64::sin(angle) as f32; } } + // The caches have a multiple of 64 rows, for `pf_gated_flash_attention`. + let rows = (max_seq + 63) / 64 * 64; let mut layers = Vec::new(); for l in 0..c.num_layers { if (l + 1) % c.full_attention_interval == 0 { layers.push(Qwen35LayerState { conv: transfer(Tensor([1, 1, 1]), Memory::HBM), s: transfer(Tensor([1, 1, 1]), Memory::HBM), - k: transfer(Tensor([max_seq, c.num_kv_heads, 256]), Memory::HBM), - v: transfer(Tensor([max_seq, c.num_kv_heads, 256]), Memory::HBM), + k: transfer(Tensor([rows, c.num_kv_heads, 256]), Memory::HBM), + v: transfer(Tensor([rows, c.num_kv_heads, 256]), Memory::HBM), }); } else { layers.push(Qwen35LayerState { From 6888edbcc52879d20c8cd9da5bb2dd1c935f9c7d Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:47:21 -0800 Subject: [PATCH 14/60] tokenizer: read the tokenizer of Qwen3.5 and Qwen3.6 The pre-tokenizer regex of Qwen3.5 and Qwen3.6 adds the Unicode marks (\p{M}) to the class of letters. convert_tokenizer.py now accepts this regex and writes the marks in the table of letters. tokenizer.vx then splits the text as the new regex does, with no change to its code. Only its comments change. Files of the older tokenizers are byte-identical to those of main. Tests: - test_tokenizer.py also compares the Qwen3.6 tokenizer with the tokenizers package, when the model folder is present. - The class test checks each regex of the model folders against the regex engine of tokenizers, for every code point. - A new test, which CI runs, checks the table of letters of each regex and that the script refuses another regex. Part of #89. --- scripts/convert_tokenizer.py | 39 ++++++++++++++-------- scripts/make_tiny_tokenizer.py | 2 +- scripts/test_tokenizer.py | 61 +++++++++++++++++++++++++++++++--- src/tokenizer.vx | 9 +++-- 4 files changed, 89 insertions(+), 22 deletions(-) diff --git a/scripts/convert_tokenizer.py b/scripts/convert_tokenizer.py index 8736d74..0ec01b8 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,7 +9,7 @@ 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. @@ -27,7 +27,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 +77,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), @@ -122,12 +130,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 +145,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 +159,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 +170,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) @@ -181,7 +192,7 @@ def unicode_tables(): def build(t): """The bytes of the tokenizer file for the parsed tokenizer.json `t`.""" - check_structure(t) + 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 +215,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)) 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/test_tokenizer.py b/scripts/test_tokenizer.py index 42312e2..1a4658b 100644 --- a/scripts/test_tokenizer.py +++ b/scripts/test_tokenizer.py @@ -23,6 +23,7 @@ import os import random import shutil +import struct import subprocess import sys import sysconfig @@ -32,6 +33,7 @@ from pathlib import Path import convert_tokenizer +import make_tiny_tokenizer try: from tokenizers import Tokenizer @@ -40,7 +42,8 @@ ROOT = Path(__file__).resolve().parent.parent MODELS = [Path("~/models/Qwen2.5-Coder-0.5B-Instruct").expanduser(), - Path("~/models/Qwen3-Coder-30B-A3B-Instruct").expanduser()] + Path("~/models/Qwen3-Coder-30B-A3B-Instruct").expanduser(), + Path("~/models/Qwen3.6-35B-A3B").expanduser()] SPECIALS = ["<|endoftext|>", "<|im_start|>", "<|im_end|>", "<|fim_prefix|>", "", ""] @@ -178,17 +181,65 @@ 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(" i32 { return -1; } -/// Whether `c` is a letter, \p{L}. +/// Whether `c` is in the class of letters of the regex: \p{L}, and also \p{M} for Qwen3.5. The +/// tokenizer file has the class. fn is_letter(t : &Tokenizer, c : i32) -> bool { if c < 128 { return (c >= 65 && c <= 90) || (c >= 97 && c <= 122); @@ -228,7 +229,8 @@ fn is_newline(c : i32) -> bool { return c == 10 || c == 13; } -/// Whether `c` is none of white space, a letter and a number, as [^\s\p{L}\p{N}]. +/// Whether `c` is none of white space, a letter and a number, as [^\s\p{L}\p{N}]. The letters +/// are those of `is_letter`. fn is_other(t : &Tokenizer, c : i32) -> bool { return !is_space(t, c) && !is_letter(t, c) && !is_number(t, c); } @@ -418,6 +420,9 @@ fn fold(c : i32) -> i32 { /// 5. \s*[\r\n]+ /// 6. \s+(?!\S) /// 7. \s+ +/// The regex of Qwen3.5 has [\p{L}\p{M}] where this one has \p{L}, and the tokenizer file then puts +/// the marks (\p{M}) in the class of letters. A mark as the optional first character of 2 gives +/// the same piece as a mark among the letters, so the code is the same. fn piece_end(t : &Tokenizer, c : &Vec, i : i32, n : i32) -> i32 { let first = c.get(i); // 1. A contraction. From 3dcbe09d2ce84c5e2816e766b71d80f8e0fa4cc6 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:50:06 -0800 Subject: [PATCH 15/60] tokenizer: refuse a Python with another Unicode version convert_tokenizer.py takes the classes of the regex and the NFC tables from the unicodedata module of Python. They give the ids of the tokenizers package only when Python has its Unicode version, 16.0. The venv here has Python 3.13 with Unicode 15.1. Its tables put new characters such as U+140B5 in another class, so test_tokenizer.py failed 4 of its tests. The script now refuses another Unicode version. Python 3.14 has 16.0. --any-unicode turns the check off for the tiny tokenizers of the RUN lines, because CI runs them with Python 3.15. test_tokenizer.py makes the tokenizer files and the Unicode tables with a Python of Unicode 16.0: itself, or python3.14 on PATH. In the venv, all 7 of its tests now pass. A new test checks the refusal. Part of #89. --- README.md | 6 ++- scripts/convert_tokenizer.py | 19 ++++++-- scripts/test_tokenizer.py | 93 ++++++++++++++++++++++++++++-------- tests/session.vx | 2 +- tests/tokenize.vx | 2 +- 5 files changed, 94 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 21094d4..2ddb329 100644 --- a/README.md +++ b/README.md @@ -436,7 +436,7 @@ 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 +`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 @@ -451,7 +451,9 @@ 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. +`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 diff --git a/scripts/convert_tokenizer.py b/scripts/convert_tokenizer.py index 0ec01b8..a4cb674 100644 --- a/scripts/convert_tokenizer.py +++ b/scripts/convert_tokenizer.py @@ -16,7 +16,8 @@ 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. @@ -96,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`. @@ -190,8 +195,12 @@ class of letters has the marks (\\p{M}).""" 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`.""" +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()} @@ -273,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/test_tokenizer.py b/scripts/test_tokenizer.py index 1a4658b..8596c64 100644 --- a/scripts/test_tokenizer.py +++ b/scripts/test_tokenizer.py @@ -9,7 +9,9 @@ of this repository, Python, Rust and C++ sources, and texts made from random Unicode characters. QWEN_TOKENIZER_CORPUS_MB sets the size of the source files (default 4 MB). -The tests skip when `tokenizers`, `vxc` or the model folders are missing, as in CI. +The tests make the tokenizer files and the Unicode tables with a Python that has the Unicode +version of `tokenizers` (convert_tokenizer.UNICODE_VERSION): this Python, or python3.14 on PATH. +They skip when `tokenizers`, `vxc`, that Python or the model folders are missing, as in CI. `tests/tokenize.vx` checks a tiny tokenizer without them. Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. @@ -30,6 +32,7 @@ import tempfile import unicodedata import unittest +import unittest.mock from pathlib import Path import convert_tokenizer @@ -117,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)], @@ -126,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 @@ -143,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]")] @@ -208,8 +258,8 @@ def code_points(ranges): def category(c): return unicodedata.category(chr(c))[0] - qwen2 = code_points(letter_ranges(convert_tokenizer.build(self.tiny_tokenizer(convert_tokenizer.QWEN2_PATTERN)))) - qwen35 = code_points(letter_ranges(convert_tokenizer.build(self.tiny_tokenizer(convert_tokenizer.QWEN35_PATTERN)))) + qwen2 = code_points(letter_ranges(convert_tokenizer.build(self.tiny_tokenizer(convert_tokenizer.QWEN2_PATTERN), True))) + qwen35 = code_points(letter_ranges(convert_tokenizer.build(self.tiny_tokenizer(convert_tokenizer.QWEN35_PATTERN), True))) self.assertEqual({category(c) for c in qwen2}, {"L"}) self.assertEqual({category(c) for c in qwen35 - qwen2}, {"M"}) self.assertLessEqual(qwen2, qwen35) @@ -217,10 +267,21 @@ def category(c): def test_another_regex_is_refused(self): with self.assertRaisesRegex(AssertionError, "the pre-tokenizer has another regex"): - convert_tokenizer.build(self.tiny_tokenizer(convert_tokenizer.QWEN2_PATTERN.replace(r"\p{N}", r"\d"))) + convert_tokenizer.build(self.tiny_tokenizer(convert_tokenizer.QWEN2_PATTERN.replace(r"\p{N}", r"\d")), True) + + +class UnicodeVersion(unittest.TestCase): + + def test_another_unicode_version_is_refused(self): + t = make_tiny_tokenizer.tokenizer_json() + with unittest.mock.patch.object(convert_tokenizer, "UNICODE_VERSION", "1.1.0"): + with self.assertRaisesRegex(AssertionError, "the tables must have Unicode 1.1.0"): + convert_tokenizer.build(t) + self.assertEqual(convert_tokenizer.build(t, True)[:8], convert_tokenizer.MAGIC) @unittest.skipIf(Tokenizer is None, "needs the tokenizers package") +@unittest.skipIf(UNICODE_PYTHON is None, NEEDS_UNICODE_PYTHON) class UnicodeTablesAgainstHuggingFace(unittest.TestCase): def test_classes_equal_those_of_the_regex_engine(self): @@ -239,7 +300,8 @@ def test_classes_equal_those_of_the_regex_engine(self): def check_classes(self, path, marks_are_letters): pre = Tokenizer.from_file(str(path)).pre_tokenizer - letters, numbers, spaces, *_ = convert_tokenizer.unicode_tables(marks_are_letters) + tables = with_unicode_python(f"print(json.dumps(t.convert_tokenizer.unicode_tables({marks_are_letters})[:3]))") + letters, numbers, spaces = [[tuple(r) for r in table] for table in tables] def inside(ranges, c): i = bisect.bisect_right(ranges, (c, 0x110000)) - 1 @@ -268,21 +330,12 @@ def test_old_nfc_data_lists_what_tokenizers_lacks(self): self.skipTest("needs a Qwen tokenizer.json") norm = Tokenizer.from_file(str(path)).normalizer - def differs(text): - return norm.normalize_str(text) != unicodedata.normalize("NFC", text) + def differs(texts): + return any(norm.normalize_str(text) != nfc for text, nfc in texts) - # 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 = [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/tests/session.vx b/tests/session.vx index 9d3a9e1..1fefe77 100644 --- a/tests/session.vx +++ b/tests/session.vx @@ -13,7 +13,7 @@ // // RUN: python3 %S/../scripts/make_tiny_model.py --vocab-size 404 --max-positions 1024 %t.vxw > /dev/null // RUN: python3 %S/../scripts/make_tiny_tokenizer.py %t.json > /dev/null -// RUN: python3 %S/../scripts/convert_tokenizer.py %t.json %t.vxt > /dev/null +// RUN: python3 %S/../scripts/convert_tokenizer.py --any-unicode %t.json %t.vxt > /dev/null // RUN: python3 %S/../scripts/chat.py %t.vxw %t.vxt --context 512 --check | FileCheck %s // // CHECK: {{^}}turn 1: prompt {{[0-9]+}} tokens, reused False, same text as a fresh run: True{{$}} diff --git a/tests/tokenize.vx b/tests/tokenize.vx index 30689ac..406d9c2 100644 --- a/tests/tokenize.vx +++ b/tests/tokenize.vx @@ -11,7 +11,7 @@ // so `grep -a` reads them as text: GNU grep prints no line of an input that it takes as binary. // // RUN: python3 %S/../scripts/make_tiny_tokenizer.py %t.json > /dev/null -// RUN: python3 %S/../scripts/convert_tokenizer.py %t.json %t.vxt > /dev/null +// RUN: python3 %S/../scripts/convert_tokenizer.py --any-unicode %t.json %t.vxt > /dev/null // RUN: python3 %S/../scripts/make_tiny_tokenizer.py --texts %t.texts // RUN: vxc %s --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx -- %t.vxt %t.texts | FileCheck %s // RUN: vxc %s --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx -- %t.vxt %t.texts | grep -v '^\[JIT\]' | sed '/^texts=/,$d' > %t.ids From 0f7c7ed20352c8598be60d35ab0dd0efc7c0c87a Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:01:30 -0800 Subject: [PATCH 16/60] qwen app: the chat format of Qwen3.5/Qwen3.6, with --think (#89) The chat template of Qwen3.5 and Qwen3.6 opens the reply with a block, and the models think by default. With --chat on an arch 1 file, the prompt now ends with "\n\n\n\n", as the template does with enable_thinking=false, so the reply comes at once. --think ends it with "\n", and the model thinks first. and are not special tokens, so they do not stop the run. With --chat, run_qwen35 now prints only the reply, as `main` does for arch 0. On the real Qwen3.6-35B-A3B Q4_0 file, "Write a short Python function that checks whether a number is prime." gives a correct is_prime in a code block and stops at <|im_end|>. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- src/main.vx | 47 ++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 40 insertions(+), 7 deletions(-) diff --git a/src/main.vx b/src/main.vx index 5f2c1cf..6f5e064 100644 --- a/src/main.vx +++ b/src/main.vx @@ -19,7 +19,9 @@ // --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. import core::convert; import std::time; import std::vec; @@ -57,6 +59,7 @@ struct Options { lines : bool, draft : *const i8, has_draft : bool, + think : bool, } /// The options of `argv`. Asserts that they are complete and that they fit together. @@ -66,7 +69,7 @@ fn parse_options(argc : i32, argv : *mut *mut i8) -> Options { 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, + 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, think: false, }; let mut i = 2; while i < argc { @@ -74,6 +77,9 @@ fn parse_options(argc : i32, argv : *mut *mut i8) -> Options { 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, "--session") { o.session = true; i = i + 1; @@ -124,6 +130,7 @@ 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; } @@ -185,6 +192,17 @@ fn same(a : *const i8, b : *const i8) -> bool { return unsafe { strcmp(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 { if o.has_tokens { @@ -195,7 +213,20 @@ fn prompt_ids(o : &Options, t : &Tokenizer) -> Vec { } else { read_text_file(o.prompt_file) }; - let full = if o.chat { + let full = if o.chat && weight_file_arch(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 @@ -358,7 +389,7 @@ fn generate_with_drafts(w : &Weights, s : &mut State, t : &Tokenizer, text_mode /// `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 as `main`. -fn run_qwen35(path : *const i8, t : &Tokenizer, text_mode : bool, prompt : &Vec, steps : i32) -> i32 { +fn run_qwen35(path : *const i8, t : &Tokenizer, text_mode : bool, chat : bool, prompt : &Vec, steps : i32) -> i32 { let w = load_qwen35_weights(path); let count = prompt.len(); let mut s = new_qwen35_state(&w.config, count + steps); @@ -377,8 +408,10 @@ fn run_qwen35(path : *const i8, t : &Tokenizer, text_mode : bool, prompt : &Vec< }); } if text_mode { - for i in 0..count { - write_token(t, prompt[i]); + if !chat { + for i in 0..count { + write_token(t, prompt[i]); + } } } else { print!("prompt="); @@ -463,7 +496,7 @@ fn main(argc : i32, argv : *mut *mut i8) -> i32 { assert(steps > 0, "--steps must be at least 1"); if weight_file_arch(o.weights) == 1 { - return run_qwen35(o.weights, &t, text_mode, &prompt, steps); + return run_qwen35(o.weights, &t, text_mode, o.chat, &prompt, steps); } let w = load_weights(o.weights); let mut s = new_state(&w.config, count + steps); From 8390803ab6cb9c0296e647f9fd9049d715462909 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:31:39 -0800 Subject: [PATCH 17/60] qwen app: --draft for Qwen3.5/Qwen3.6 (#89) A round of arch 1 (src/round35.vx) runs the last token and up to 15 draft tokens through the model with one read of the weights, as `run_round` does for arch 0. Each position gets the result of the kernels of one token bit for bit, so the tokens are those of plain greedy decoding. A DeltaNet layer changes its state with each token, and a round does not know which positions it keeps until the CPU reads the tokens. So the round reads S and the convolution inputs and writes neither. It keeps q, k, v, beta, decay and the outputs of linear_in of each position. Then commit_round35 runs the update of S again for the kept positions and writes S and the last 3 convolution inputs. That costs one more read of S per layer for each round. The full attention layers run the kernels of one token for each position, in order. The products use nn_matvec_q4_rows and a residual add, which give the bits of nn_matvec_q4_add. The experts use row versions of moe_swiglu_q4_blocks and moe_down_q4_add_blocks. generate_with_drafts35 is generate_with_drafts with a commit after each round. Its first step is a plain step, which compiles the kernels of a token, so the clock starts after it. tests/round35.vx checks rounds of 6, 4, 2 and 5 tokens that keep 3, 1, 2 and 5 of them: every logit, and the DeltaNet states after each commit, equal those of plain decoding bit for bit. tests/ generate_qwen35.vx checks that --draft 7 gives the lines of plain decoding on a prompt that makes a round. All 98 checks pass. On the real Qwen3.6-35B-A3B Q4_0 file, 96 lines of "def fibonacci(n):" with --draft 7 equal those without it, and a chat prompt that asks for type hints on a function gives the same text with and without drafts, with 79 of 81 draft tokens accepted. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- src/main.vx | 175 +++++++++- src/round35.vx | 727 +++++++++++++++++++++++++++++++++++++++ tests/generate_qwen35.vx | 12 + tests/round35.vx | 176 ++++++++++ 4 files changed, 1079 insertions(+), 11 deletions(-) create mode 100644 src/round35.vx create mode 100644 tests/round35.vx diff --git a/src/main.vx b/src/main.vx index 6f5e064..2c870ee 100644 --- a/src/main.vx +++ b/src/main.vx @@ -33,6 +33,7 @@ import qwen::prefill; import qwen::session; import qwen::speculate; import qwen::round; +import qwen::round35; import qwen::tokenizer; /// The options of the command line. @@ -238,9 +239,9 @@ 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 { +fn show(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 is_special(t, token) || token == eos { return false; } write_token(t, token); @@ -251,8 +252,8 @@ fn show(t : &Tokenizer, w : &Weights, text_mode : bool, step : i32, token : i32, } /// 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]; } @@ -303,7 +304,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(t, w.config.eos_token_id, text_mode, 0, token, read_logit(&s.logits, token)); while going && step + 1 < steps { let room = steps - step - 1; let m = longest_match(&context); @@ -341,7 +342,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(t, w.config.eos_token_id, text_mode, step, token, logit); j = j + 1; } run = i32::min(run * 2, AHEAD); @@ -365,9 +366,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(t, w.config.eos_token_id, text_mode, step, token, logit); more = j < k && draft[j] == token; if more { accepted = accepted + 1; @@ -387,9 +388,150 @@ fn generate_with_drafts(w : &Weights, s : &mut State, t : &Tokenizer, text_mode return step; } +/// `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(w : &Qwen35Weights, s : &mut Qwen35State, t : &Tokenizer, 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 eos = w.config.eos_token_id; + 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(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(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; + let mut misses = 0; + let mut missed_length = 0; + 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 { + 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(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(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; + if j == 0 { + misses = misses + 1; + missed_length = m.length; + } else { + misses = 0; + } + } + } + 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). There are no drafts yet (#89). Prints the same lines as `main`. -fn run_qwen35(path : *const i8, t : &Tokenizer, text_mode : bool, chat : bool, prompt : &Vec, steps : i32) -> i32 { +/// (src/prefill35.vx). With --draft, the tokens come from `generate_with_drafts35`. Prints the +/// same lines as `main`. +fn run_qwen35(path : *const i8, t : &Tokenizer, text_mode : bool, chat : bool, prompt : &Vec, steps : i32, draft : i32) -> i32 { let w = load_qwen35_weights(path); let count = prompt.len(); let mut s = new_qwen35_state(&w.config, count + steps); @@ -431,7 +573,13 @@ fn run_qwen35(path : *const i8, t : &Tokenizer, text_mode : bool, chat : bool, p let prompt_ms = f64::from(prompt_start.elapsed().as_secs_f32()) * 1000.0; let mut start = Instant::now(); let mut decoded = 0; + if draft > 0 { + decoded = generate_with_drafts35(&w, &mut s, t, text_mode, prompt, tokens[0], steps, draft, &mut start); + } for step in 0..steps { + if draft > 0 { + break; + } let token = tokens[step]; if text_mode { if is_special(t, token) || token == w.config.eos_token_id { @@ -496,7 +644,12 @@ fn main(argc : i32, argv : *mut *mut i8) -> i32 { assert(steps > 0, "--steps must be at least 1"); if weight_file_arch(o.weights) == 1 { - return run_qwen35(o.weights, &t, text_mode, o.chat, &prompt, steps); + let draft = if o.has_draft { + parse_numbers(o.draft)[0] + } else { + 0 + }; + return run_qwen35(o.weights, &t, text_mode, o.chat, &prompt, steps, draft); } let w = load_weights(o.weights); let mut s = new_state(&w.config, count + steps); diff --git a/src/round35.vx b/src/round35.vx new file mode 100644 index 0000000..c4dd934 --- /dev/null +++ b/src/round35.vx @@ -0,0 +1,727 @@ +//===- round35.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 +// +//===----------------------------------------------------------------------===// +// A round of a Qwen3.5 or Qwen3.6 model (arch 1, #89): n positions in a row, start to +// start + n - 1, with one read of the weights, as `run_round` (src/speculate.vx) for arch 0. Each +// position gets the result of the kernels of a generated token (src/qwen35.vx) bit for bit, so a +// round gives the tokens that plain decoding gives. +// +// The state of a DeltaNet layer is the problem: a token changes S and the last 3 inputs of the +// convolution, and a round does not know which of its positions it keeps until the CPU reads the +// tokens. So a round reads S and the convolution inputs and writes neither. It keeps the q, k, v, +// beta and decay of each position, and the outputs of `linear_in`. Then `commit_round35` runs the +// update of the state again for the positions that the CPU keeps, and writes it. That costs one +// more read of S for each round, about 2 MB for each layer. +// +// The full attention layers run the kernels of one token for each position, in order, so each +// position sees the rows of the KV cache that the positions before it wrote. The KV cache keeps +// the rows of all n positions; the next round or step writes over the rows that the CPU does not +// keep, before any token reads them. +import core::num; +import std::nn; +import std::vec; +import qwen::deltanet; +import qwen::gated_attention; +import qwen::model; +import qwen::products; +import qwen::q6; +import qwen::qwen35; +import qwen::round; +import qwen::simd; +import qwen::weights; + +/// The tensors of a round of up to ROUND_MAX positions, in GPU memory. Row t of each is position +/// t. `proj` and `y` are as in `Qwen35State`, and `add` is the output of a product before its +/// residual add. The `d` tensors, `beta`, `decay` and `o` are those of the DeltaNet, for the layer +/// that runs; `proj` and those tensors of a DeltaNet layer are what `commit_round35` reads, so a +/// round keeps them for each DeltaNet layer: `kept` has one `RoundLayer35` for each layer. +struct Round35 { + tokens : Tensor, + x : Tensor, + xn : Tensor, + y : Tensor, + add : Tensor, + o : Tensor, + router : Tensor, + ids : Tensor, + weights : Tensor, + mlp : Tensor, + shared_ids : Tensor, + shared_weight : Tensor, + shared_mlp : Tensor, + logits : Tensor, + next : Tensor, + kept : Vec, +} + +/// What a round keeps of one layer for `commit_round35`. A full attention layer keeps only `proj`, +/// which it uses while it runs; the others have one value each. +struct RoundLayer35 { + proj : Tensor, + dq : Tensor, + dk : Tensor, + dv : Tensor, + beta : Tensor, + decay : Tensor, +} + +fn round35_zeros(a : i32, b : i32) -> Tensor { + let mut x = Tensor([a, b]); + for i in 0..a { + for j in 0..b { + x[i][j] = 0.0; + } + } + return transfer(x, Memory::HBM); +} + +/// Whether the round kernels can run model `w`: Q4_0 layers and experts, and a 6-bit lm_head. +fn can_round35(w : &Qwen35Weights) -> bool { + let mut ok = w.lm_head.dtype == U6; + for l in 0..w.config.num_layers { + ok = ok && w.layers[l].gate_up.dtype == U4 && w.layers[l].down.dtype == U4 && w.layers[l].shared_gate_up.dtype == U4 && w.layers[l].shared_down.dtype == U4; + if w.layers[l].full_attention { + ok = ok && w.layers[l].qkv.dtype == U4 && w.layers[l].attn_out.dtype == U4; + } else { + ok = ok && w.layers[l].linear_in.dtype == U4 && w.layers[l].linear_out.dtype == U4; + } + } + return ok; +} + +fn new_round35(c : &Config) -> Round35 { + let n = ROUND_MAX; + let kh = c.linear_k_heads; + let vh = c.linear_v_heads; + let qkv_rows = (2 * c.num_q_heads + 2 * c.num_kv_heads) * 256; + let in_rows = (2 * kh + 2 * vh) * 128 + 2 * vh; + let k = c.experts_per_token; + let mut kept = Vec::new(); + for l in 0..c.num_layers { + if (l + 1) % c.full_attention_interval == 0 { + kept.push(RoundLayer35 { + proj: transfer(Tensor([n, qkv_rows]), Memory::HBM), + dq: transfer(Tensor([1, 1, 1]), Memory::HBM), + dk: transfer(Tensor([1, 1, 1]), Memory::HBM), + dv: transfer(Tensor([1, 1, 1]), Memory::HBM), + beta: transfer(Tensor([1, 1]), Memory::HBM), + decay: transfer(Tensor([1, 1]), Memory::HBM), + }); + } else { + kept.push(RoundLayer35 { + proj: transfer(Tensor([n, in_rows]), Memory::HBM), + dq: transfer(Tensor([n, kh, 128]), Memory::HBM), + dk: transfer(Tensor([n, kh, 128]), Memory::HBM), + dv: transfer(Tensor([n, vh, 128]), Memory::HBM), + beta: transfer(Tensor([n, vh]), Memory::HBM), + decay: transfer(Tensor([n, vh]), Memory::HBM), + }); + } + } + let mut shared_ids = Tensor([n, 1]); + for t in 0..n { + shared_ids[t][0] = 0; + } + return Round35 { + tokens: transfer(Tensor([n]), Memory::HBM), + x: transfer(Tensor([n, c.hidden_size]), Memory::HBM), + xn: transfer(Tensor([n, c.hidden_size]), Memory::HBM), + y: transfer(Tensor([n, i32::max(c.num_q_heads * 256, vh * 128)]), Memory::HBM), + add: transfer(Tensor([n, c.hidden_size]), Memory::HBM), + o: transfer(Tensor([n, vh, 128]), Memory::HBM), + router: transfer(Tensor([n, c.num_experts + 1]), Memory::HBM), + ids: transfer(Tensor([n, k]), Memory::HBM), + weights: transfer(Tensor([n, k]), Memory::HBM), + mlp: transfer(Tensor([n * k, c.moe_intermediate_size]), Memory::HBM), + shared_ids: transfer(shared_ids, Memory::HBM), + shared_weight: round35_zeros(n, 1), + shared_mlp: transfer(Tensor([n, c.shared_expert_inter]), Memory::HBM), + logits: transfer(Tensor([n, c.vocab_size]), Memory::HBM), + next: transfer(Tensor([n]), Memory::HBM), + kept: kept, + }; +} + +// ---------------------------------------------------------------------------- small kernels --- + +/// `rms_norm_f32` for each of n rows. +fn rms_norm_f32_rows(y : &mut Tensor, x : &Tensor, w : &Tensor, n : i32, dim : i32, eps : f32) -> void { + assert(n > 0 && y.extent(0) >= n && x.extent(0) >= n && y.extent(1) >= dim && x.extent(1) >= dim && w.len() >= dim, "rms_norm_f32_rows: a tensor is too small"); + spawn on(Topology::Device) { + for t in 0..n across blocks { + let mut part = unsafe { Tensor::uninit() }; + for l in 0..1024 across lanes { + let mut s : f32 = 0.0; + let mut i = l; + while i < dim { + s = s + x[t][i] * x[t][i]; + i = i + 1024; + } + part[l] = s; + } + let ss = lanes::sum(&part, 1024); + let inv = 1.0 / (ss / (dim as f32) + eps).sqrt(); + for l in 0..1024 across lanes { + for j in 0..(dim + 1023) / 1024 { + let i = j * 1024 + l; + if i < dim { + y[t][i] = x[t][i] * inv * w[i]; + } + } + } + } + } + return; +} + +/// x[t][i] += a[t][i], for t below n: the residual add of `nn_matvec_q4_add`, after +/// `nn_matvec_q4_rows` wrote the products to `a`. +fn add_rows(x : &mut Tensor, a : &Tensor, n : i32, dim : i32) -> void { + spawn on(Topology::Device) { + for t in 0..n across blocks { + for b in 0..(dim + 255) / 256 across blocks { + for l in 0..256 across lanes { + let i = b * 256 + l; + if i < dim { + x[t][i] = x[t][i] + a[t][i]; + } + } + } + } + } + return; +} + +/// x[t][i] = y[i], for i below dim. +fn put_row(x : &mut Tensor, y : &Tensor, t : i32, dim : i32) -> void { + spawn on(Topology::Device) { + for b in 0..(dim + 255) / 256 across blocks { + for l in 0..256 across lanes { + let i = b * 256 + l; + if i < dim { + x[t][i] = y[i]; + } + } + } + } + return; +} + +/// y[i] = x[t][i], for i below dim. +fn take_row(y : &mut Tensor, x : &Tensor, t : i32, dim : i32) -> void { + spawn on(Topology::Device) { + for b in 0..(dim + 255) / 256 across blocks { + for l in 0..256 across lanes { + let i = b * 256 + l; + if i < dim { + y[i] = x[t][i]; + } + } + } + } + return; +} + +/// out[t][0] = sigmoid(logits[t][at]), for t below n: `shared_gate` for each row. +fn shared_gate_rows(out : &mut Tensor, logits : &Tensor, n : i32, at : i32) -> void { + spawn on(Topology::Device) { + for b in 0..1 across blocks { + for t in 0..ROUND_MAX across lanes { + if t < n { + out[t][0] = 1.0 / (1.0 + (0.0 - logits[t][at]).fast_exp()); + } + } + } + } + return; +} + +// -------------------------------------------------------------------------------- DeltaNet --- + +/// `deltanet_conv` for positions 0 to n - 1 of the round, without the write of the convolution +/// state. The input of position p is proj[p] when p >= 0, and conv_state[.][.][3 + p] before the +/// round. +fn round_dn_conv(qn : &mut Tensor, kn : &mut Tensor, vv : &mut Tensor, conv_state : &Tensor, proj : &Tensor, conv : &Tensor, n : i32, k_heads : i32, v_heads : i32) -> void { + spawn on(Topology::Device) { + for t in 0..n across blocks { + 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 mut x0 : f32 = 0.0; + if t >= 3 { + x0 = proj[t - 3][c]; + } else { + x0 = conv_state[h][i][t]; + } + let mut x1 : f32 = 0.0; + if t >= 2 { + x1 = proj[t - 2][c]; + } else { + x1 = conv_state[h][i][t + 1]; + } + let mut x2 : f32 = 0.0; + if t >= 1 { + x2 = proj[t - 1][c]; + } else { + x2 = conv_state[h][i][2]; + } + let x3 = proj[t][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()); + 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[t][h][i] = y[i] * inv * 0.08838834764831845; + } else if h < 2 * k_heads { + kn[t][h - k_heads][i] = y[i] * inv; + } else { + vv[t][h - 2 * k_heads][i] = y[i]; + } + } + } + } + } + return; +} + +/// The convolution state after the first `count` positions of the round: the inputs of positions +/// count - 3 to count - 1. +fn round_dn_commit_conv(conv_state : &mut Tensor, proj : &Tensor, count : i32, heads : i32) -> void { + spawn on(Topology::Device) { + for h in 0..heads across blocks { + for i in 0..128 across lanes { + let c = h * 128 + i; + let o0 = conv_state[h][i][0]; + let o1 = conv_state[h][i][1]; + let o2 = conv_state[h][i][2]; + // Input count - 3 + j, for j = 0, 1, 2; before the round, input p is o(3 + p). + let mut n0 = o0; + let mut n1 = o1; + let mut n2 = o2; + if count == 1 { + n0 = o1; + n1 = o2; + n2 = proj[0][c]; + } else if count == 2 { + n0 = o2; + n1 = proj[0][c]; + n2 = proj[1][c]; + } else { + n0 = proj[count - 3][c]; + n1 = proj[count - 2][c]; + n2 = proj[count - 1][c]; + } + conv_state[h][i][0] = n0; + conv_state[h][i][1] = n1; + conv_state[h][i][2] = n2; + } + } + } + return; +} + +/// `deltanet_gates` for each of n rows. +fn round_dn_gates(beta : &mut Tensor, decay : &mut Tensor, proj : &Tensor, neg_a : &Tensor, dt_bias : &Tensor, b_at : i32, a_at : i32, n : i32, v_heads : i32) -> void { + spawn on(Topology::Device) { + for t in 0..n across blocks { + for j in 0..64 across lanes { + if j < v_heads { + let b = proj[t][b_at + j]; + beta[t][j] = 1.0 / (1.0 + (0.0 - b).fast_exp()); + let x = proj[t][a_at + j] + dt_bias[j]; + let mut sp = x; + if x <= 20.0 { + sp = simd_log(1.0 + x.fast_exp()); + } + decay[t][j] = (neg_a[j] * sp).fast_exp(); + } + } + } + } + return; +} + +/// `deltanet_recur` for positions 0 to n - 1 of the round, in order, without the write of S: each +/// lane keeps its 4 values of a row of S in registers over the positions. o[t] gets the output of +/// position t. +fn round_dn_recur(o : &mut Tensor, state : &Tensor, qn : &Tensor, kn : &Tensor, vv : &Tensor, beta : &Tensor, decay : &Tensor, group : i32, n : i32, v_heads : i32) -> void { + assert(n >= 1 && n <= ROUND_MAX, "round_dn_recur: n must be 1 to ROUND_MAX"); + 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 mut mine = unsafe { Tensor::uninit() }; + for t in 0..16 { + mine[t] = 0.0; + } + for m in 0..32 { + let v = vq * 32 + m; + let mut s0 = state[h][v][d]; + let mut s1 = state[h][v][d + 1]; + let mut s2 = state[h][v][d + 2]; + let mut s3 = state[h][v][d + 3]; + for t in 0..n { + let dec = decay[t][h]; + let k0 = kn[t][g][d]; + let k1 = kn[t][g][d + 1]; + let k2 = kn[t][g][d + 2]; + let k3 = kn[t][g][d + 3]; + let a0 = s0 * dec; + let a1 = s1 * dec; + let a2 = s2 * dec; + let a3 = s3 * dec; + let kv = simd_sum(a0 * k0 + a1 * k1 + a2 * k2 + a3 * k3); + let delta = (vv[t][h][v] - kv) * beta[t][h]; + s0 = a0 + k0 * delta; + s1 = a1 + k1 * delta; + s2 = a2 + k2 * delta; + s3 = a3 + k3 * delta; + let out = simd_sum(s0 * qn[t][g][d] + s1 * qn[t][g][d + 1] + s2 * qn[t][g][d + 2] + s3 * qn[t][g][d + 3]); + if m == l { + mine[t] = out; + } + } + } + for t in 0..n { + o[t][h][vq * 32 + l] = mine[t]; + } + } + } + } + } + } + return; +} + +/// The update of S of `deltanet_recur` for the first `count` positions of the round, in order, +/// written back to `state`. It needs no q and gives no output. +fn round_dn_commit_state(state : &mut Tensor, kn : &Tensor, vv : &Tensor, beta : &Tensor, decay : &Tensor, group : i32, count : 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; + for m in 0..32 { + let v = vq * 32 + m; + let mut s0 = state[h][v][d]; + let mut s1 = state[h][v][d + 1]; + let mut s2 = state[h][v][d + 2]; + let mut s3 = state[h][v][d + 3]; + for t in 0..count { + let dec = decay[t][h]; + let k0 = kn[t][g][d]; + let k1 = kn[t][g][d + 1]; + let k2 = kn[t][g][d + 2]; + let k3 = kn[t][g][d + 3]; + let a0 = s0 * dec; + let a1 = s1 * dec; + let a2 = s2 * dec; + let a3 = s3 * dec; + let kv = simd_sum(a0 * k0 + a1 * k1 + a2 * k2 + a3 * k3); + let delta = (vv[t][h][v] - kv) * beta[t][h]; + s0 = a0 + k0 * delta; + s1 = a1 + k1 * delta; + s2 = a2 + k2 * delta; + s3 = a3 + k3 * delta; + } + state[h][v][d] = s0; + state[h][v][d + 1] = s1; + state[h][v][d + 2] = s2; + state[h][v][d + 3] = s3; + } + } + } + } + } + } + return; +} + +/// `deltanet_gated_norm` for each of n rows. +fn round_dn_gated_norm(y : &mut Tensor, o : &Tensor, proj : &Tensor, norm : &Tensor, z_at : i32, n : i32, v_heads : i32, eps : f32) -> void { + spawn on(Topology::Device) { + for t in 0..n across blocks { + for h in 0..v_heads across blocks { + let mut part = unsafe { Tensor::uninit() }; + for i in 0..128 across lanes { + let a = o[t][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[t][z_at + h * 128 + i]; + y[t][h * 128 + i] = o[t][h][i] * inv * norm[i] * (z / (1.0 + (0.0 - z).fast_exp())); + } + } + } + } + return; +} + +// --------------------------------------------------------------------------------- experts --- + +/// `moe_swiglu_q4_blocks` for n positions: out[t * k + e] gets the output of expert ids[t][e] for +/// x[t]. A block runs the body of `moe_swiglu_q4_blocks` for one position and expert. +fn moe_swiglu_q4_blocks_rows(out : &mut Tensor, w : &Tensor, scales : &Tensor, ids : &Tensor, x : &Tensor, n : i32, k : i32, rows : i32, cols : i32, experts : i32) -> void { + assert(k > 0 && n > 0 && ids.extent(0) >= n && ids.extent(1) >= k && x.extent(0) >= n && out.extent(0) >= n * k && out.extent(1) >= rows, "moe_swiglu_q4_blocks_rows: `ids` needs n rows of k values, `x` n rows, and `out` a row of rows values for each of the n * k"); + assert(rows % 8 == 0, "moe_swiglu_q4_blocks_rows: rows must be a multiple of 8"); + nn_check_q4(w.len(), scales.len(), x.extent(1), experts * 2 * rows, cols); + let words = cols / 8; + let groups = cols / 32; + spawn on(Topology::Device) { + for rb in 0..rows / 8 across blocks { + for te in 0..n * k across blocks { + let mut part = unsafe { + Tensor::uninit() + }; + for s in 0..2 across subgroups { + for l in 0..32 across lanes(32) { + let t = te / k; + let e = te - t * k; + let mut acc = unsafe { Tensor::uninit() }; + for j in 0..8 { + acc[j] = 0.0; + } + let id = ids[t][e]; + assert(id >= 0 && id < experts, "moe_swiglu_q4_blocks_rows: an id is not the number of an expert"); + let first = id * 2 * rows + rb * 8 + s * 4; + let mut i = l * 2; + while i < words { + let c = i * 8; + let mut xp = unsafe { Tensor::uninit() }; + for u in 0..16 { + xp[u] = x[t][c + u]; + } + let sum8 = 8.0 * (xp[0] + xp[1] + xp[2] + xp[3] + xp[4] + xp[5] + xp[6] + xp[7] + xp[8] + xp[9] + xp[10] + xp[11] + xp[12] + xp[13] + xp[14] + xp[15]); + xp[1] = xp[1] * 0.0625; + xp[2] = xp[2] * 0.00390625; + xp[3] = xp[3] * 0.000244140625; + xp[4] = xp[4] * 0.0000152587890625; + xp[5] = xp[5] * 0.00000095367431640625; + xp[6] = xp[6] * 0.000000059604644775390625; + xp[7] = xp[7] * 0.0000000037252902984619140625; + xp[9] = xp[9] * 0.0625; + xp[10] = xp[10] * 0.00390625; + xp[11] = xp[11] * 0.000244140625; + xp[12] = xp[12] * 0.0000152587890625; + xp[13] = xp[13] * 0.00000095367431640625; + xp[14] = xp[14] * 0.000000059604644775390625; + xp[15] = xp[15] * 0.0000000037252902984619140625; + for j in 0..8 { + let row = first + j % 4 + (j / 4) * rows; + let at = row * words + i; + let w0 = w[at]; + let w1 = w[at + 1]; + let dot = ((w0 & 15u32) as f32) * xp[0] + ((w0 & 240u32) as f32) * xp[1] + ((w0 & 3840u32) as f32) * xp[2] + ((w0 & 61440u32) as f32) * xp[3] + ((w0 & 983040u32) as f32) * xp[4] + ((w0 & 15728640u32) as f32) * xp[5] + ((w0 & 251658240u32) as f32) * xp[6] + ((w0 & 4026531840u32) as f32) * xp[7] + ((w1 & 15u32) as f32) * xp[8] + ((w1 & 240u32) as f32) * xp[9] + ((w1 & 3840u32) as f32) * xp[10] + ((w1 & 61440u32) as f32) * xp[11] + ((w1 & 983040u32) as f32) * xp[12] + ((w1 & 15728640u32) as f32) * xp[13] + ((w1 & 251658240u32) as f32) * xp[14] + ((w1 & 4026531840u32) as f32) * xp[15]; + acc[j] = acc[j] + (dot - sum8) * (scales[row * groups + i / 4] as f32); + } + i = i + 64; + } + part[s][0][l] = acc[0]; + part[s][1][l] = acc[1]; + part[s][2][l] = acc[2]; + part[s][3][l] = acc[3]; + part[s][4][l] = acc[4]; + part[s][5][l] = acc[5]; + part[s][6][l] = acc[6]; + part[s][7][l] = acc[7]; + } + let g0 = lanes::sum(&part[s][0], 32); + let u0 = lanes::sum(&part[s][4], 32); + out[te][rb * 8 + s * 4 + 0] = g0 / (1.0 + (0.0 - g0).fast_exp()) * u0; + let g1 = lanes::sum(&part[s][1], 32); + let u1 = lanes::sum(&part[s][5], 32); + out[te][rb * 8 + s * 4 + 1] = g1 / (1.0 + (0.0 - g1).fast_exp()) * u1; + let g2 = lanes::sum(&part[s][2], 32); + let u2 = lanes::sum(&part[s][6], 32); + out[te][rb * 8 + s * 4 + 2] = g2 / (1.0 + (0.0 - g2).fast_exp()) * u2; + let g3 = lanes::sum(&part[s][3], 32); + let u3 = lanes::sum(&part[s][7], 32); + out[te][rb * 8 + s * 4 + 3] = g3 / (1.0 + (0.0 - g3).fast_exp()) * u3; + } + } + } + } + return; +} + +/// `moe_down_q4_add_blocks` for n positions: y[t] += the experts ids[t] of h[t * k] to +/// h[t * k + k - 1], times weights[t]. A block runs the body of `moe_down_q4_add_blocks` for one +/// position. +fn moe_down_q4_add_blocks_rows(y : &mut Tensor, w : &Tensor, scales : &Tensor, ids : &Tensor, weights : &Tensor, h : &Tensor, n : i32, k : i32, rows : i32, cols : i32, experts : i32) -> void { + assert(k > 0 && n > 0 && ids.extent(0) >= n && ids.extent(1) >= k && weights.extent(0) >= n && weights.extent(1) >= k && h.extent(0) >= n * k && h.extent(1) >= cols && y.extent(0) >= n, "moe_down_q4_add_blocks_rows: `ids` and `weights` need n rows of k values, `h` a row of cols values for each of the n * k, and `y` n rows"); + nn_check_q4(w.len(), scales.len(), cols, experts * rows, cols); + assert(rows % 8 == 0 && y.extent(1) >= rows, "moe_down_q4_add_blocks_rows: rows must be a multiple of 8, and the output needs rows values"); + let words = cols / 8; + let groups = cols / 32; + spawn on(Topology::Device) { + for rb in 0..rows / 8 across blocks { + for t in 0..n across blocks { + let mut part = unsafe { + Tensor::uninit() + }; + for s in 0..2 across subgroups { + for l in 0..32 across lanes(32) { + let mut acc = unsafe { Tensor::uninit() }; + for j in 0..4 { + acc[j] = 0.0; + } + let pairs = words / 2; + let mut p = l; + while p < k * pairs { + let e = p / pairs; + let i = (p - e * pairs) * 2; + let id = ids[t][e]; + assert(id >= 0 && id < experts, "moe_down_q4_add_blocks_rows: an id is not the number of an expert"); + let first = id * rows + rb * 8 + s * 4; + let we = weights[t][e]; + let c = i * 8; + let mut xp = unsafe { Tensor::uninit() }; + for u in 0..16 { + xp[u] = h[t * k + e][c + u]; + } + let sum8 = 8.0 * (xp[0] + xp[1] + xp[2] + xp[3] + xp[4] + xp[5] + xp[6] + xp[7] + xp[8] + xp[9] + xp[10] + xp[11] + xp[12] + xp[13] + xp[14] + xp[15]); + xp[1] = xp[1] * 0.0625; + xp[2] = xp[2] * 0.00390625; + xp[3] = xp[3] * 0.000244140625; + xp[4] = xp[4] * 0.0000152587890625; + xp[5] = xp[5] * 0.00000095367431640625; + xp[6] = xp[6] * 0.000000059604644775390625; + xp[7] = xp[7] * 0.0000000037252902984619140625; + xp[9] = xp[9] * 0.0625; + xp[10] = xp[10] * 0.00390625; + xp[11] = xp[11] * 0.000244140625; + xp[12] = xp[12] * 0.0000152587890625; + xp[13] = xp[13] * 0.00000095367431640625; + xp[14] = xp[14] * 0.000000059604644775390625; + xp[15] = xp[15] * 0.0000000037252902984619140625; + for j in 0..4 { + let row = first + j; + let at = row * words + i; + let w0 = w[at]; + let w1 = w[at + 1]; + let dot = ((w0 & 15u32) as f32) * xp[0] + ((w0 & 240u32) as f32) * xp[1] + ((w0 & 3840u32) as f32) * xp[2] + ((w0 & 61440u32) as f32) * xp[3] + ((w0 & 983040u32) as f32) * xp[4] + ((w0 & 15728640u32) as f32) * xp[5] + ((w0 & 251658240u32) as f32) * xp[6] + ((w0 & 4026531840u32) as f32) * xp[7] + ((w1 & 15u32) as f32) * xp[8] + ((w1 & 240u32) as f32) * xp[9] + ((w1 & 3840u32) as f32) * xp[10] + ((w1 & 61440u32) as f32) * xp[11] + ((w1 & 983040u32) as f32) * xp[12] + ((w1 & 15728640u32) as f32) * xp[13] + ((w1 & 251658240u32) as f32) * xp[14] + ((w1 & 4026531840u32) as f32) * xp[15]; + acc[j] = acc[j] + we * (dot - sum8) * (scales[row * groups + i / 4] as f32); + } + p = p + 32; + } + part[s][0][l] = acc[0]; + part[s][1][l] = acc[1]; + part[s][2][l] = acc[2]; + part[s][3][l] = acc[3]; + } + let s0 = lanes::sum(&part[s][0], 32); + let s1 = lanes::sum(&part[s][1], 32); + let s2 = lanes::sum(&part[s][2], 32); + let s3 = lanes::sum(&part[s][3], 32); + y[t][rb * 8 + s * 4 + 0] = y[t][rb * 8 + s * 4 + 0] + s0; + y[t][rb * 8 + s * 4 + 1] = y[t][rb * 8 + s * 4 + 1] + s1; + y[t][rb * 8 + s * 4 + 2] = y[t][rb * 8 + s * 4 + 2] + s2; + y[t][rb * 8 + s * 4 + 3] = y[t][rb * 8 + s * 4 + 3] + s3; + } + } + } + } + return; +} + +// ------------------------------------------------------------------------------- the round --- + +/// Runs the n tokens of `tokens` at positions start to start + n - 1 through the model, as +/// `run_qwen35_layers` and then `predict_qwen35` for each token in turn: r.next[t] gets the greedy +/// token after token t. The KV caches get the rows of all n tokens. The DeltaNet states do not +/// change: `commit_round35` writes them for the tokens that the caller keeps. +fn run_round35(w : &Qwen35Weights, s : &mut Qwen35State, r : &mut Round35, tokens : &Vec, start : i32, n : i32) -> void { + let c = &w.config; + let eps = c.rms_norm_eps as f32; + let kh = c.linear_k_heads; + let vh = c.linear_v_heads; + let z_at = (2 * kh + vh) * 128; + let b_at = z_at + vh * 128; + let a_at = b_at + vh; + let qkv_rows = (2 * c.num_q_heads + 2 * c.num_kv_heads) * 256; + let k = c.experts_per_token; + assert(n >= 1 && n <= ROUND_MAX && start + n <= s.max_seq, "run_round35: n must be 1 to ROUND_MAX, and the positions must fit in the KV cache"); + let mut h = Tensor([ROUND_MAX]); + for t in 0..ROUND_MAX { + h[t] = 0; + if t < n { + h[t] = tokens[t]; + } + } + r.tokens = transfer(h, Memory::HBM); + nn_embed_rows(&mut r.x, &w.embed, &r.tokens, n, c.hidden_size); + let mut kit = r.kept.iter_mut(); + let mut l = 0; + for ls in s.layers.iter_mut() { + let layer = &w.layers[l]; + let kept = kit.next().unwrap(); + rms_norm_f32_rows(&mut r.xn, &r.x, &layer.attn_norm, n, c.hidden_size, eps); + if layer.full_attention { + nn_matvec_q4_rows(&mut kept.proj, &layer.qkv.codes, &layer.qkv.group_scales, &r.xn, n, qkv_rows, c.hidden_size); + for t in 0..n { + take_row(&mut s.proj, &kept.proj, t, qkv_rows); + gated_norm_rope_and_store(&mut s.q, &mut ls.k, &mut ls.v, &s.proj, &layer.q_norm, &layer.k_norm, &s.cos, &s.sin, start + t, c.num_q_heads, c.num_kv_heads, c.rotary_dim, eps); + gated_attention(&mut s.y, &mut s.parts, &s.q, &ls.k, &ls.v, &s.proj, start + t, c.num_q_heads, c.num_kv_heads); + put_row(&mut r.y, &s.y, t, c.num_q_heads * 256); + } + nn_matvec_q4_rows(&mut r.add, &layer.attn_out.codes, &layer.attn_out.group_scales, &r.y, n, c.hidden_size, c.num_q_heads * 256); + } else { + nn_matvec_q4_rows(&mut kept.proj, &layer.linear_in.codes, &layer.linear_in.group_scales, &r.xn, n, a_at + vh, c.hidden_size); + round_dn_conv(&mut kept.dq, &mut kept.dk, &mut kept.dv, &ls.conv, &kept.proj, &layer.conv, n, kh, vh); + round_dn_gates(&mut kept.beta, &mut kept.decay, &kept.proj, &layer.neg_a, &layer.dt_bias, b_at, a_at, n, vh); + round_dn_recur(&mut r.o, &ls.s, &kept.dq, &kept.dk, &kept.dv, &kept.beta, &kept.decay, vh / kh, n, vh); + round_dn_gated_norm(&mut r.y, &r.o, &kept.proj, &layer.linear_norm, z_at, n, vh, eps); + nn_matvec_q4_rows(&mut r.add, &layer.linear_out.codes, &layer.linear_out.group_scales, &r.y, n, c.hidden_size, vh * 128); + } + add_rows(&mut r.x, &r.add, n, c.hidden_size); + rms_norm_f32_rows(&mut r.xn, &r.x, &layer.mlp_norm, n, c.hidden_size, eps); + nn_matvec_rows(&mut r.router, &layer.router, &r.xn, n, c.num_experts + 1, c.hidden_size); + nn_top_k_rows(&mut r.ids, &mut r.weights, &r.router, n, c.num_experts, k); + shared_gate_rows(&mut r.shared_weight, &r.router, n, c.num_experts); + moe_swiglu_q4_blocks_rows(&mut r.mlp, &layer.gate_up.codes, &layer.gate_up.group_scales, &r.ids, &r.xn, n, k, c.moe_intermediate_size, c.hidden_size, c.num_experts); + moe_down_q4_add_blocks_rows(&mut r.x, &layer.down.codes, &layer.down.group_scales, &r.ids, &r.weights, &r.mlp, n, k, c.hidden_size, c.moe_intermediate_size, c.num_experts); + moe_swiglu_q4_blocks_rows(&mut r.shared_mlp, &layer.shared_gate_up.codes, &layer.shared_gate_up.group_scales, &r.shared_ids, &r.xn, n, 1, c.shared_expert_inter, c.hidden_size, 1); + moe_down_q4_add_blocks_rows(&mut r.x, &layer.shared_down.codes, &layer.shared_down.group_scales, &r.shared_ids, &r.shared_weight, &r.shared_mlp, n, 1, c.hidden_size, c.shared_expert_inter, 1); + l = l + 1; + } + rms_norm_f32_rows(&mut r.xn, &r.x, &w.final_norm, n, c.hidden_size, eps); + matvec_q6_rows(&mut r.logits, &w.lm_head.codes, &w.lm_head.high, &w.lm_head.group_scales, &r.xn, n, c.vocab_size, c.hidden_size); + nn_argmax_rows(&mut r.next, &r.logits, n, c.vocab_size); + return; +} + +/// Keeps the first `count` tokens of the last round: writes the DeltaNet states as `run_qwen35_layers` +/// leaves them after those tokens, bit for bit. The KV caches already have their rows. +fn commit_round35(w : &Qwen35Weights, s : &mut Qwen35State, r : &Round35, count : i32) -> void { + let c = &w.config; + let kh = c.linear_k_heads; + let vh = c.linear_v_heads; + assert(count >= 1 && count <= ROUND_MAX, "commit_round35: count must be 1 to ROUND_MAX"); + let mut l = 0; + for ls in s.layers.iter_mut() { + if !w.layers[l].full_attention { + let kept = &r.kept[l]; + round_dn_commit_state(&mut ls.s, &kept.dk, &kept.dv, &kept.beta, &kept.decay, vh / kh, count, vh); + round_dn_commit_conv(&mut ls.conv, &kept.proj, count, 2 * kh + vh); + } + l = l + 1; + } + return; +} diff --git a/tests/generate_qwen35.vx b/tests/generate_qwen35.vx index 5820b31..65a610f 100644 --- a/tests/generate_qwen35.vx +++ b/tests/generate_qwen35.vx @@ -6,6 +6,9 @@ // - the bf16 and the Q4_0 files after a prompt of 2,100 tokens. So the prompt runs in 2 chunks // (the state of each layer goes from one chunk to the next), and the full attention layer goes // past position 2,048, where its blocks take 64 SIMD groups for each head in place of 32. +// - the Q4_0 file with --draft 7, against the same file without it: the lines of the steps must be +// the same, logits too. The prompt repeats its first 10 tokens at its end, and the model gives +// 109 and 99 after it, as it did after their first copy, so a round of 7 draft tokens runs. // // The products of a chunk round each Q4_0 weight, (code - 8) times its scale, to f16, as for the // Qwen3 models. So the Q4_0 files get 0.003, as in tests/prefill.vx, and the bf16 files 0.001. @@ -30,8 +33,17 @@ // RUN: python3 %S/../scripts/reference.py %t-long.vxw --tokens $(cat %t-long.ids) --steps 8 > %t-long.reference // RUN: vxc %S/../src/main.vx --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx -- %t-long.vxw --tokens $(cat %t-long.ids) --steps 8 > %t-long.vx // RUN: python3 %S/../scripts/compare.py %t-long.reference %t-long.vx --tolerance 0.003 | FileCheck %s --check-prefix=LONG +// RUN: vxc %S/../src/main.vx --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx -- %t-q4.vxw --tokens 31,41,59,26,53,58,97,93,23,84,109,99,62,64,33,83,27,31,41,59,26,53,58,97,93,23,84 --steps 32 > %t-plain.vx +// RUN: vxc %S/../src/main.vx --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx -- %t-q4.vxw --tokens 31,41,59,26,53,58,97,93,23,84,109,99,62,64,33,83,27,31,41,59,26,53,58,97,93,23,84 --steps 32 --draft 7 > %t-draft.vx +// RUN: grep step= %t-plain.vx > %t-plain.steps +// RUN: grep step= %t-draft.vx > %t-draft.steps +// RUN: diff %t-plain.steps %t-draft.steps +// RUN: grep -c step= %t-draft.steps | FileCheck %s --check-prefix=STEPS +// RUN: grep rounds= %t-draft.vx | FileCheck %s --check-prefix=DRAFT // // CHECK: 16 steps, same tokens, logits within 0.001 // Q4: 16 steps, same tokens, logits within 0.003 // LONG-BF16: 8 steps, same tokens, logits within 0.001 // LONG: 8 steps, same tokens, logits within 0.003 +// STEPS: {{^}}32{{$}} +// DRAFT: rounds=1 drafted=7 accepted=0; diff --git a/tests/round35.vx b/tests/round35.vx new file mode 100644 index 0000000..c402472 --- /dev/null +++ b/tests/round35.vx @@ -0,0 +1,176 @@ +//===- round35.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 +// +//===----------------------------------------------------------------------===// +// A round of a Qwen3.5/Qwen3.6 model (src/round35.vx) against plain decoding (src/qwen35.vx), on +// the tiny model of Q4_0 layers and a 6-bit lm_head. Each value must be equal bit for bit. State +// `r` runs rounds of 6, 4, 2 and 5 tokens after a prompt, and keeps 3, 1, 2 and 5 of them with +// `commit_round35`. State `b` decodes the kept tokens one at a time, and state `a`, a copy of `b` +// before each round, decodes all the tokens of the round. The logits of each position of a round +// must be those of `a`, and the DeltaNet states after the commit those of `b`. +// +// RUN: python3 %S/../scripts/make_tiny_model.py --qwen35 --q4 --q6-lm-head %t.vxw > /dev/null +// RUN: vxc %s --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx -- %t.vxw | FileCheck %s +// +// CHECK: {{^}}round of 6: logits 0 differ, tokens 0 differ{{$}} +// CHECK: {{^}}keep 3: states 0 differ{{$}} +// CHECK: {{^}}round of 4: logits 0 differ, tokens 0 differ{{$}} +// CHECK: {{^}}keep 1: states 0 differ{{$}} +// CHECK: {{^}}round of 2: logits 0 differ, tokens 0 differ{{$}} +// CHECK: {{^}}keep 2: states 0 differ{{$}} +// CHECK: {{^}}round of 5: logits 0 differ, tokens 0 differ{{$}} +// CHECK: {{^}}keep 5: states 0 differ{{$}} +import core::convert; +import core::num; +import std::nn; +import std::vec; +import qwen::model; +import qwen::prefill35; +import qwen::qwen35; +import qwen::round; +import qwen::round35; +import qwen::weights; + +/// Decodes `tokens` one at a time from position `pos`, and gives the logits of each, one after +/// another. +fn decode(w : &Qwen35Weights, s : &mut Qwen35State, tokens : &Vec, pos : i32) -> Vec { + let mut out = Vec::new(); + let mut next = transfer(Tensor([1]), Memory::HBM); + for t in 0..tokens.len() { + let mut h = Tensor([1]); + h[0] = tokens[t]; + let input = transfer(h, Memory::HBM); + run_qwen35_layers(w, s, &input, pos + t); + predict_qwen35(w, s, &mut next); + let logits = transfer(&s.logits, Memory::CPU_DRAM); + for i in 0..w.config.vocab_size { + out.push(logits[i]); + } + } + return out; +} + +/// The number of values of the DeltaNet states (S and the convolution inputs) of a and b that are +/// not equal bit for bit. +fn states_differ(w : &Qwen35Weights, a : &Qwen35State, b : &Qwen35State) -> i32 { + let mut differ = 0; + for l in 0..w.config.num_layers { + if !w.layers[l].full_attention { + let sa = transfer(&a.layers[l].s, Memory::CPU_DRAM); + let sb = transfer(&b.layers[l].s, Memory::CPU_DRAM); + for h in 0..sa.extent(0) { + for i in 0..128 { + for j in 0..128 { + if sa[h][i][j].to_bits() != sb[h][i][j].to_bits() { + differ = differ + 1; + } + } + } + } + let ca = transfer(&a.layers[l].conv, Memory::CPU_DRAM); + let cb = transfer(&b.layers[l].conv, Memory::CPU_DRAM); + for h in 0..ca.extent(0) { + for i in 0..128 { + for j in 0..3 { + if ca[h][i][j].to_bits() != cb[h][i][j].to_bits() { + differ = differ + 1; + } + } + } + } + } + } + return differ; +} + +/// Runs `tokens` as a round on `r` and decodes them one at a time on `a`, both from `pos`, and +/// prints how many logits and tokens differ. +fn check_round(w : &Qwen35Weights, rs : &mut Qwen35State, round : &mut Round35, a : &mut Qwen35State, tokens : &Vec, pos : i32) -> void { + let n = tokens.len(); + let want = decode(w, a, tokens, pos); + run_round35(w, rs, round, tokens, pos, n); + let got = transfer(&round.logits, Memory::CPU_DRAM); + let next = transfer(&round.next, Memory::CPU_DRAM); + let vocab = w.config.vocab_size; + let mut differ = 0; + let mut tokens_differ = 0; + for t in 0..n { + let mut best = 0; + for i in 0..vocab { + if got[t][i].to_bits() != want[t * vocab + i].to_bits() { + differ = differ + 1; + } + if want[t * vocab + i] > want[t * vocab + best] { + best = i; + } + } + if next[t] != best { + tokens_differ = tokens_differ + 1; + } + } + println!("round of {}: logits {} differ, tokens {} differ", n, differ, tokens_differ); + return; +} + +fn some_tokens(first : i32, n : i32, vocab : i32) -> Vec { + let mut v = Vec::new(); + for i in 0..n { + v.push((first + i * 37) % vocab); + } + return v; +} + +/// Copies the state of each layer of `src` to `dst`. +fn copy_states(dst : &mut Qwen35State, src : &Qwen35State) -> void { + let mut l = 0; + for ls in dst.layers.iter_mut() { + ls.s = transfer(transfer(&src.layers[l].s, Memory::CPU_DRAM), Memory::HBM); + ls.conv = transfer(transfer(&src.layers[l].conv, Memory::CPU_DRAM), Memory::HBM); + ls.k = transfer(transfer(&src.layers[l].k, Memory::CPU_DRAM), Memory::HBM); + ls.v = transfer(transfer(&src.layers[l].v, Memory::CPU_DRAM), Memory::HBM); + l = l + 1; + } + return; +} + +fn main(argc : i32, argv : *mut *mut i8) -> i32 { + let w = load_qwen35_weights(unsafe { argv[1] }); + let vocab = w.config.vocab_size; + let max_seq = 64; + let mut a = new_qwen35_state(&w.config, max_seq); + let mut b = new_qwen35_state(&w.config, max_seq); + let mut r = new_qwen35_state(&w.config, max_seq); + let mut round = new_round35(&w.config); + let prompt = some_tokens(5, 7, vocab); + prefill_qwen35(&w, &mut b, &prompt); + prefill_qwen35(&w, &mut r, &prompt); + let mut pos = prompt.len(); + let mut sizes = Vec::new(); + let mut keeps = Vec::new(); + sizes.push(6); + keeps.push(3); + sizes.push(4); + keeps.push(1); + sizes.push(2); + keeps.push(2); + sizes.push(5); + keeps.push(5); + for i in 0..sizes.len() { + // `a` decodes all the tokens of the round, from a copy of `b`; `b` decodes the kept ones. + copy_states(&mut a, &b); + let tokens = some_tokens(11 + 13 * i, sizes[i], vocab); + check_round(&w, &mut r, &mut round, &mut a, &tokens, pos); + let mut kept = Vec::new(); + for j in 0..keeps[i] { + kept.push(tokens[j]); + } + let _logits = decode(&w, &mut b, &kept, pos); + commit_round35(&w, &mut r, &round, keeps[i]); + println!("keep {}: states {} differ", keeps[i], states_differ(&w, &r, &b)); + pos = pos + keeps[i]; + } + return 0; +} From 0ba9521abf8612f37078145721f654358c858e58 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:50:29 -0800 Subject: [PATCH 18/60] qwen app: run the app with vxc -O2 vxc compiles the code that runs on the CPU at -O0 by default, and no command here passed -O. At -O0, a zeroed CPU tensor of 98 MB takes about 52 ms; at -O2 it takes about 1 ms. The tensors of a chunk of the prompt are about 220 MB at 512 tokens, so the prompt of the real Qwen3.6 file is about 8% faster with -O2 (informal reading, not under the policy). The time of a generated token does not change, and neither do the tokens. The README, the header of src/main.vx, scripts/chat.py, examples/run.sh and decode/profile_decode.vx now run vxc -O2. The README says to use -O2 for every run that is timed. The tests keep the default, so they compile faster. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- README.md | 14 +++++++++----- decode/README.md | 2 +- decode/profile_decode.vx | 2 +- examples/run.sh | 2 +- scripts/chat.py | 2 +- src/main.vx | 2 +- 6 files changed, 14 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 21094d4..b8728ae 100644 --- a/README.md +++ b/README.md @@ -81,11 +81,15 @@ pip install -r requirements.txt 1. Generate text with the Vx program, on the GPU: ```sh - 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 -- 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. @@ -94,7 +98,7 @@ pip install -r requirements.txt 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 \ + 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 ``` @@ -117,9 +121,9 @@ pip install -r requirements.txt 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 \ + 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 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 -- qwen-0.5b.vxw \ --tokenizer qwen.vxt --prompt "def fibonacci(n):" --lines --steps 8 ``` @@ -212,7 +216,7 @@ 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 \ +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 ``` 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..683a158 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; 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/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/src/main.vx b/src/main.vx index 5f2c1cf..685d93e 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 From 98d32b6a9408c7d13bd0a57f6344509a2e1c5815 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:21:14 -0800 Subject: [PATCH 19/60] qwen app: --prompt-runs and --ignore-eos for the benchmark runner (#89) --prompt-runs K (Qwen3.5 and Qwen3.6) runs the prompt K times, each on a fresh state made before its clock starts, and prints `time prompt_ms=` for each run. The first run includes the first launch of each kernel. The runs use the same chunk tensors (new prefill_qwen35_with), made before the first clock starts, as llama.cpp makes its buffers when it loads the model. The tokens and the decode come from the last run. --ignore-eos does not stop the text at a special token or EOS, as llama.cpp's --ignore-eos, so a run gives --steps tokens. It works for both architectures, with and without --draft. tests/generate_qwen35.vx: --prompt-runs 3 gives 3 prompt times and the step lines of the file without it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- src/main.vx | 90 ++++++++++++++++++++++++++++++---------- src/prefill35.vx | 19 +++++++-- tests/generate_qwen35.vx | 8 ++++ 3 files changed, 93 insertions(+), 24 deletions(-) diff --git a/src/main.vx b/src/main.vx index 2c870ee..53d7378 100644 --- a/src/main.vx +++ b/src/main.vx @@ -21,7 +21,10 @@ // format of the Instruct models and prints only the reply. --lines prints the lines of --tokens // 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. +// --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::time; import std::vec; @@ -61,6 +64,9 @@ struct Options { draft : *const i8, has_draft : bool, think : bool, + ignore_eos : bool, + prompt_runs : *const i8, + has_prompt_runs : bool, } /// The options of `argv`. Asserts that they are complete and that they fit together. @@ -70,7 +76,7 @@ fn parse_options(argc : i32, argv : *mut *mut i8) -> Options { 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, think: 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, think: false, ignore_eos: false, prompt_runs: empty, has_prompt_runs: false, }; let mut i = 2; while i < argc { @@ -81,6 +87,9 @@ fn parse_options(argc : i32, argv : *mut *mut i8) -> Options { } 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; @@ -114,6 +123,9 @@ fn parse_options(argc : i32, argv : *mut *mut i8) -> Options { } else if same(name, "--draft") { o.draft = value; o.has_draft = true; + } else if same(name, "--prompt-runs") { + o.prompt_runs = 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; @@ -238,10 +250,11 @@ 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. +/// Gives false at the end of the text, where the loop stops. With `eos` -1 (--ignore-eos), the text +/// has no end. fn show(t : &Tokenizer, eos : i32, text_mode : bool, step : i32, token : i32, logit : f32) -> bool { if text_mode { - if is_special(t, token) || token == eos { + if ends_text(t, eos, token) { return false; } write_token(t, token); @@ -251,6 +264,11 @@ fn show(t : &Tokenizer, eos : i32, text_mode : bool, step : i32, token : i32, lo 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(logits : &Tensor, j : i32, token : i32) -> f32 { let h = transfer(logits, Memory::CPU_DRAM); @@ -263,7 +281,7 @@ fn round_logit(logits : &Tensor, j : i32, token : i32) /// 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(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"); @@ -304,7 +322,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.config.eos_token_id, text_mode, 0, token, read_logit(&s.logits, token)); + let mut going = show(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); @@ -342,7 +360,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.config.eos_token_id, text_mode, step, token, logit); + going = show(t, eos, text_mode, step, token, logit); j = j + 1; } run = i32::min(run * 2, AHEAD); @@ -368,7 +386,7 @@ fn generate_with_drafts(w : &Weights, s : &mut State, t : &Tokenizer, text_mode if !text_mode { logit = round_logit(&r.logits, j, token); } - going = show(t, w.config.eos_token_id, text_mode, step, token, logit); + going = show(t, eos, text_mode, step, token, logit); more = j < k && draft[j] == token; if more { accepted = accepted + 1; @@ -392,11 +410,10 @@ fn generate_with_drafts(w : &Weights, s : &mut State, t : &Tokenizer, text_mode /// `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(w : &Qwen35Weights, s : &mut Qwen35State, t : &Tokenizer, text_mode : bool, prompt : &Vec, first : i32, steps : i32, max : i32, start : &mut Instant) -> i32 { +fn generate_with_drafts35(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 eos = w.config.eos_token_id; let mut r = new_round35(&w.config); let mut ring = Vec::new(); for j in 0..AHEAD { @@ -531,8 +548,13 @@ fn generate_with_drafts35(w : &Qwen35Weights, s : &mut Qwen35State, t : &Tokeniz /// `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(path : *const i8, t : &Tokenizer, text_mode : bool, chat : bool, prompt : &Vec, steps : i32, draft : i32) -> i32 { +fn run_qwen35(path : *const i8, t : &Tokenizer, text_mode : bool, chat : bool, ignore_eos : bool, prompt : &Vec, steps : i32, draft : i32, runs : i32) -> i32 { let w = load_qwen35_weights(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 { @@ -565,16 +587,30 @@ fn run_qwen35(path : *const i8, t : &Tokenizer, text_mode : bool, chat : bool, p } println!(";"); } - let prompt_start = Instant::now(); - prefill_qwen35(&w, &mut s, prompt); - predict_qwen35(&w, &mut s, &mut slots[0].next); + // 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)); let mut tokens = Vec::new(); - tokens.push(read_token(&slots[0].next)); - let prompt_ms = f64::from(prompt_start.elapsed().as_secs_f32()) * 1000.0; + 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(); + 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; if draft > 0 { - decoded = generate_with_drafts35(&w, &mut s, t, text_mode, prompt, tokens[0], steps, draft, &mut start); + decoded = generate_with_drafts35(&w, &mut s, t, eos, text_mode, prompt, tokens[0], steps, draft, &mut start); } for step in 0..steps { if draft > 0 { @@ -582,7 +618,7 @@ fn run_qwen35(path : *const i8, t : &Tokenizer, text_mode : bool, chat : bool, p } 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); @@ -649,9 +685,21 @@ fn main(argc : i32, argv : *mut *mut i8) -> i32 { } else { 0 }; - return run_qwen35(o.weights, &t, text_mode, o.chat, &prompt, steps, draft); + 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"); + return run_qwen35(o.weights, &t, text_mode, o.chat, o.ignore_eos, &prompt, steps, draft, runs); } + assert(!o.has_prompt_runs, "--prompt-runs needs a Qwen3.5 or Qwen3.6 file"); let w = load_weights(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"); @@ -703,7 +751,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(&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 { @@ -711,7 +759,7 @@ 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); diff --git a/src/prefill35.vx b/src/prefill35.vx index 9a57e35..cca92b7 100644 --- a/src/prefill35.vx +++ b/src/prefill35.vx @@ -1047,15 +1047,28 @@ fn pf35_chunk(w : &Qwen35Weights, s : &mut Qwen35State, p : &mut Prefill35, star return; } +/// The chunk of `prefill_qwen35` for a prompt of `count` tokens: CHUNK, or fewer for a shorter +/// prompt. +fn prefill35_chunk(count : i32) -> i32 { + return i32::min(CHUNK, (count + 15) / 16 * 16); +} + /// Runs the prompt through every layer, in chunks of up to CHUNK tokens, from position 0. The /// hidden state of the last token is then in `s.x`, as after `run_qwen35_layers`, so /// `predict_qwen35` gives the next token. fn prefill_qwen35(w : &Qwen35Weights, s : &mut Qwen35State, prompt : &Vec) -> void { + let mut p = new_prefill35(&w.config, prefill35_chunk(prompt.len())); + prefill_qwen35_with(w, s, &mut p, prompt); + return; +} + +/// `prefill_qwen35` with the tensors of `p`, from `new_prefill35`, so that more prompts can use the +/// same tensors. Each chunk writes the parts of them that it reads. +fn prefill_qwen35_with(w : &Qwen35Weights, s : &mut Qwen35State, p : &mut Prefill35, prompt : &Vec) -> void { let c = &w.config; let count = prompt.len(); assert(count > 0 && count <= s.max_seq, "prefill_qwen35: the prompt must have tokens and fit in the state"); - let chunk = i32::min(CHUNK, (count + 15) / 16 * 16); - let mut p = new_prefill35(c, chunk); + let chunk = p.tokens.len(); let mut start = 0; let mut last = 0; while start < count { @@ -1077,7 +1090,7 @@ fn prefill_qwen35(w : &Qwen35Weights, s : &mut Qwen35State, prompt : &Vec) } p.tokens = transfer(ids, Memory::HBM); p.rows = transfer(rows, Memory::HBM); - pf35_chunk(w, s, &mut p, start, n); + pf35_chunk(w, s, p, start, n); last = n; start = start + n; } diff --git a/tests/generate_qwen35.vx b/tests/generate_qwen35.vx index 65a610f..334a6b2 100644 --- a/tests/generate_qwen35.vx +++ b/tests/generate_qwen35.vx @@ -9,6 +9,8 @@ // - the Q4_0 file with --draft 7, against the same file without it: the lines of the steps must be // the same, logits too. The prompt repeats its first 10 tokens at its end, and the model gives // 109 and 99 after it, as it did after their first copy, so a round of 7 draft tokens runs. +// - the Q4_0 file with --prompt-runs 3: a time for each run of the prompt, and the lines of the +// steps of the file without it. // // The products of a chunk round each Q4_0 weight, (code - 8) times its scale, to f16, as for the // Qwen3 models. So the Q4_0 files get 0.003, as in tests/prefill.vx, and the bf16 files 0.001. @@ -40,6 +42,11 @@ // RUN: diff %t-plain.steps %t-draft.steps // RUN: grep -c step= %t-draft.steps | FileCheck %s --check-prefix=STEPS // RUN: grep rounds= %t-draft.vx | FileCheck %s --check-prefix=DRAFT +// RUN: vxc %S/../src/main.vx --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx -- %t-q4.vxw --tokens 1,2,3,4 --steps 16 --prompt-runs 3 > %t-runs.vx +// RUN: grep step= %t-q4.vx > %t-q4.steps +// RUN: grep step= %t-runs.vx > %t-runs.steps +// RUN: diff %t-q4.steps %t-runs.steps +// RUN: grep -c "time prompt_ms=" %t-runs.vx | FileCheck %s --check-prefix=RUNS // // CHECK: 16 steps, same tokens, logits within 0.001 // Q4: 16 steps, same tokens, logits within 0.003 @@ -47,3 +54,4 @@ // LONG: 8 steps, same tokens, logits within 0.003 // STEPS: {{^}}32{{$}} // DRAFT: rounds=1 drafted=7 accepted=0; +// RUNS: {{^}}3{{$}} From 3945b0ad6425d9374cc47fa886008484152c0a16 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:47:22 -0800 Subject: [PATCH 20/60] Prefill products: skip the multiplies of a half tile of padding (#89) An expert of Qwen3.6-35B-A3B gets about 16 of the 4,096 choices of a 512-token chunk, and its tokens are padded to blocks of 32, so about half of the positions of the expert products were padding. The tokens of a block come before its padding, so when token 16 of a block is padding, the two SIMD groups of tokens 16 to 31 now skip their multiplies (an scf.if around them in scripts/mlir_kernels/expert_product.py). The down product reads the positions themselves (e_ident), so the new pf_live_positions gives -1 to the positions of padding after each sort. Informal, -O2, the real model, one chunk of 512 tokens, interleaved: the experts take 622 ms in place of 777 (gate_up 352 in place of 452, down 196 in place of 250). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- scripts/mlir_kernels/expert_product.py | 15 ++ src/prefill.vx | 225 ++++++++++++++----------- src/prefill35.vx | 1 + 3 files changed, 147 insertions(+), 94 deletions(-) diff --git a/scripts/mlir_kernels/expert_product.py b/scripts/mlir_kernels/expert_product.py index 285d2f7..626c708 100755 --- a/scripts/mlir_kernels/expert_product.py +++ b/scripts/mlir_kernels/expert_product.py @@ -95,6 +95,13 @@ def c(n): # 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('%rh32 = arith.muli %rh, %k32 : index') # sw[rh * 32] +# The tokens of an expert come first in its tiles, so when token 16 of the block is padding, so are +# tokens 16 to 31, and the subgroups of those tokens (th = 1) skip their multiplies. +b('%tb16 = arith.addi %tb32, %k16 : index') +b('%from16 = memref.load %list[%tb16] : memref') +b('%live16 = arith.cmpi sge, %from16, %zi : i32') +b('%th0 = arith.cmpi eq, %th, %k0 : index') +b('%busy = arith.ori %th0, %live16 : i1') 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}) {{') @@ -138,6 +145,9 @@ def c(n): 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>') d('gpu.barrier') +d(f'%mm:8 = scf.if %busy -> ({accty}) {{') +d0 = d +d = lambda s: d0(' ' + s) prev = [f'%a{i}' for i in range(8)] for k8 in (0, 8, 16, 24): if hint: @@ -160,6 +170,11 @@ def c(n): cur.append(f'%r{n}_{k8}') prev = cur d('scf.yield ' + ', '.join(prev) + ' : ' + accty) +d = d0 +d('} else {') +d(' scf.yield ' + ', '.join(f'%a{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') diff --git a/src/prefill.vx b/src/prefill.vx index 36f969a..3f281ae 100644 --- a/src/prefill.vx +++ b/src/prefill.vx @@ -47,6 +47,8 @@ const ATTENTION_TOKENS : i32 = 128; /// (`pf_sort_by_expert`): position p of `e_rows` is a token, or -1 for padding, and /// `slot[t * k + j]` is the position of expert j of token t. `e_counts[e]` is the number of choices /// of expert e, and `e_lane_counts[e * 32 + l]` those in the tokens of lane l of the sort. +/// `e_ident[p]` is p for a position with a token and -1 for padding (`pf_live_positions`): the list +/// of the down product of the experts. struct Prefill { chunk : i32, tokens : Tensor, @@ -403,7 +405,9 @@ fn pf_mm_q4_set(y : &mut Tensor, w : &Tensor, w : &Tensor %th512 = arith.muli %th, %k512 : index %rh32 = arith.muli %rh, %k32 : index + %tb16 = arith.addi %tb32, %k16 : index + %from16 = memref.load %list[%tb16] : memref + %live16 = arith.cmpi sge, %from16, %zi : i32 + %th0 = arith.cmpi eq, %th, %k0 : index + %busy = arith.ori %th0, %live16 : i1 %res:8 = scf.for %g = %k0 to %Gl step %k1 iter_args(%a0 = %z, %a1 = %z, %a2 = %z, %a3 = %z, %a4 = %z, %a5 = %z, %a6 = %z, %a7 = %z) -> (!gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">) { %g4 = arith.muli %g, %k4 : index %wa = arith.addi %wbase, %g4 : index @@ -597,99 +606,104 @@ fn pf_mm_q4_mlir(y : &mut Tensor, w : &Tensor, vector<4xf16> vector.store %h1, %sx[%sxd4] {alignment = 8} : memref<1024xf16, 3>, vector<4xf16> gpu.barrier - vx.subgroup_schedule_barrier - %bo0_0 = arith.addi %rh32, %k0 : index - %mb0_0 = gpu.subgroup_mma_load_matrix %sw[%bo0_0] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - %bo1_0 = arith.addi %rh32, %k8 : index - %mb1_0 = gpu.subgroup_mma_load_matrix %sw[%bo1_0] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - %bo2_0 = arith.addi %rh32, %k16 : index - %mb2_0 = gpu.subgroup_mma_load_matrix %sw[%bo2_0] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - %bo3_0 = arith.addi %rh32, %k24 : index - %mb3_0 = gpu.subgroup_mma_load_matrix %sw[%bo3_0] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - vx.subgroup_schedule_barrier - %ao0_0 = arith.addi %th512, %k0 : index - %ma0_0 = gpu.subgroup_mma_load_matrix %sx[%ao0_0] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> - %ao1_0 = arith.addi %th512, %k256 : index - %ma1_0 = gpu.subgroup_mma_load_matrix %sx[%ao1_0] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> - vx.subgroup_schedule_barrier - %r0_0 = gpu.subgroup_mma_compute %ma0_0, %mb0_0, %a0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r1_0 = gpu.subgroup_mma_compute %ma0_0, %mb1_0, %a1 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r2_0 = gpu.subgroup_mma_compute %ma0_0, %mb2_0, %a2 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r3_0 = gpu.subgroup_mma_compute %ma0_0, %mb3_0, %a3 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r4_0 = gpu.subgroup_mma_compute %ma1_0, %mb0_0, %a4 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r5_0 = gpu.subgroup_mma_compute %ma1_0, %mb1_0, %a5 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r6_0 = gpu.subgroup_mma_compute %ma1_0, %mb2_0, %a6 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r7_0 = gpu.subgroup_mma_compute %ma1_0, %mb3_0, %a7 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - vx.subgroup_schedule_barrier - %bo0_8 = arith.addi %rh32, %k512 : index - %mb0_8 = gpu.subgroup_mma_load_matrix %sw[%bo0_8] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - %bo1_8 = arith.addi %rh32, %k520 : index - %mb1_8 = gpu.subgroup_mma_load_matrix %sw[%bo1_8] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - %bo2_8 = arith.addi %rh32, %k528 : index - %mb2_8 = gpu.subgroup_mma_load_matrix %sw[%bo2_8] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - %bo3_8 = arith.addi %rh32, %k536 : index - %mb3_8 = gpu.subgroup_mma_load_matrix %sw[%bo3_8] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - vx.subgroup_schedule_barrier - %ao0_8 = arith.addi %th512, %k8 : index - %ma0_8 = gpu.subgroup_mma_load_matrix %sx[%ao0_8] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> - %ao1_8 = arith.addi %th512, %k264 : index - %ma1_8 = gpu.subgroup_mma_load_matrix %sx[%ao1_8] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> - vx.subgroup_schedule_barrier - %r0_8 = gpu.subgroup_mma_compute %ma0_8, %mb0_8, %r0_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r1_8 = gpu.subgroup_mma_compute %ma0_8, %mb1_8, %r1_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r2_8 = gpu.subgroup_mma_compute %ma0_8, %mb2_8, %r2_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r3_8 = gpu.subgroup_mma_compute %ma0_8, %mb3_8, %r3_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r4_8 = gpu.subgroup_mma_compute %ma1_8, %mb0_8, %r4_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r5_8 = gpu.subgroup_mma_compute %ma1_8, %mb1_8, %r5_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r6_8 = gpu.subgroup_mma_compute %ma1_8, %mb2_8, %r6_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r7_8 = gpu.subgroup_mma_compute %ma1_8, %mb3_8, %r7_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - vx.subgroup_schedule_barrier - %bo0_16 = arith.addi %rh32, %k1024 : index - %mb0_16 = gpu.subgroup_mma_load_matrix %sw[%bo0_16] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - %bo1_16 = arith.addi %rh32, %k1032 : index - %mb1_16 = gpu.subgroup_mma_load_matrix %sw[%bo1_16] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - %bo2_16 = arith.addi %rh32, %k1040 : index - %mb2_16 = gpu.subgroup_mma_load_matrix %sw[%bo2_16] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - %bo3_16 = arith.addi %rh32, %k1048 : index - %mb3_16 = gpu.subgroup_mma_load_matrix %sw[%bo3_16] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - vx.subgroup_schedule_barrier - %ao0_16 = arith.addi %th512, %k16 : index - %ma0_16 = gpu.subgroup_mma_load_matrix %sx[%ao0_16] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> - %ao1_16 = arith.addi %th512, %k272 : index - %ma1_16 = gpu.subgroup_mma_load_matrix %sx[%ao1_16] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> - vx.subgroup_schedule_barrier - %r0_16 = gpu.subgroup_mma_compute %ma0_16, %mb0_16, %r0_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r1_16 = gpu.subgroup_mma_compute %ma0_16, %mb1_16, %r1_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r2_16 = gpu.subgroup_mma_compute %ma0_16, %mb2_16, %r2_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r3_16 = gpu.subgroup_mma_compute %ma0_16, %mb3_16, %r3_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r4_16 = gpu.subgroup_mma_compute %ma1_16, %mb0_16, %r4_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r5_16 = gpu.subgroup_mma_compute %ma1_16, %mb1_16, %r5_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r6_16 = gpu.subgroup_mma_compute %ma1_16, %mb2_16, %r6_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r7_16 = gpu.subgroup_mma_compute %ma1_16, %mb3_16, %r7_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - vx.subgroup_schedule_barrier - %bo0_24 = arith.addi %rh32, %k1536 : index - %mb0_24 = gpu.subgroup_mma_load_matrix %sw[%bo0_24] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - %bo1_24 = arith.addi %rh32, %k1544 : index - %mb1_24 = gpu.subgroup_mma_load_matrix %sw[%bo1_24] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - %bo2_24 = arith.addi %rh32, %k1552 : index - %mb2_24 = gpu.subgroup_mma_load_matrix %sw[%bo2_24] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - %bo3_24 = arith.addi %rh32, %k1560 : index - %mb3_24 = gpu.subgroup_mma_load_matrix %sw[%bo3_24] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - vx.subgroup_schedule_barrier - %ao0_24 = arith.addi %th512, %k24 : index - %ma0_24 = gpu.subgroup_mma_load_matrix %sx[%ao0_24] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> - %ao1_24 = arith.addi %th512, %k280 : index - %ma1_24 = gpu.subgroup_mma_load_matrix %sx[%ao1_24] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> - vx.subgroup_schedule_barrier - %r0_24 = gpu.subgroup_mma_compute %ma0_24, %mb0_24, %r0_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r1_24 = gpu.subgroup_mma_compute %ma0_24, %mb1_24, %r1_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r2_24 = gpu.subgroup_mma_compute %ma0_24, %mb2_24, %r2_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r3_24 = gpu.subgroup_mma_compute %ma0_24, %mb3_24, %r3_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r4_24 = gpu.subgroup_mma_compute %ma1_24, %mb0_24, %r4_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r5_24 = gpu.subgroup_mma_compute %ma1_24, %mb1_24, %r5_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r6_24 = gpu.subgroup_mma_compute %ma1_24, %mb2_24, %r6_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r7_24 = gpu.subgroup_mma_compute %ma1_24, %mb3_24, %r7_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - scf.yield %r0_24, %r1_24, %r2_24, %r3_24, %r4_24, %r5_24, %r6_24, %r7_24 : !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp"> + %mm:8 = scf.if %busy -> (!gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">) { + vx.subgroup_schedule_barrier + %bo0_0 = arith.addi %rh32, %k0 : index + %mb0_0 = gpu.subgroup_mma_load_matrix %sw[%bo0_0] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo1_0 = arith.addi %rh32, %k8 : index + %mb1_0 = gpu.subgroup_mma_load_matrix %sw[%bo1_0] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo2_0 = arith.addi %rh32, %k16 : index + %mb2_0 = gpu.subgroup_mma_load_matrix %sw[%bo2_0] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo3_0 = arith.addi %rh32, %k24 : index + %mb3_0 = gpu.subgroup_mma_load_matrix %sw[%bo3_0] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + vx.subgroup_schedule_barrier + %ao0_0 = arith.addi %th512, %k0 : index + %ma0_0 = gpu.subgroup_mma_load_matrix %sx[%ao0_0] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao1_0 = arith.addi %th512, %k256 : index + %ma1_0 = gpu.subgroup_mma_load_matrix %sx[%ao1_0] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + vx.subgroup_schedule_barrier + %r0_0 = gpu.subgroup_mma_compute %ma0_0, %mb0_0, %a0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r1_0 = gpu.subgroup_mma_compute %ma0_0, %mb1_0, %a1 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r2_0 = gpu.subgroup_mma_compute %ma0_0, %mb2_0, %a2 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r3_0 = gpu.subgroup_mma_compute %ma0_0, %mb3_0, %a3 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r4_0 = gpu.subgroup_mma_compute %ma1_0, %mb0_0, %a4 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r5_0 = gpu.subgroup_mma_compute %ma1_0, %mb1_0, %a5 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r6_0 = gpu.subgroup_mma_compute %ma1_0, %mb2_0, %a6 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r7_0 = gpu.subgroup_mma_compute %ma1_0, %mb3_0, %a7 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + vx.subgroup_schedule_barrier + %bo0_8 = arith.addi %rh32, %k512 : index + %mb0_8 = gpu.subgroup_mma_load_matrix %sw[%bo0_8] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo1_8 = arith.addi %rh32, %k520 : index + %mb1_8 = gpu.subgroup_mma_load_matrix %sw[%bo1_8] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo2_8 = arith.addi %rh32, %k528 : index + %mb2_8 = gpu.subgroup_mma_load_matrix %sw[%bo2_8] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo3_8 = arith.addi %rh32, %k536 : index + %mb3_8 = gpu.subgroup_mma_load_matrix %sw[%bo3_8] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + vx.subgroup_schedule_barrier + %ao0_8 = arith.addi %th512, %k8 : index + %ma0_8 = gpu.subgroup_mma_load_matrix %sx[%ao0_8] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao1_8 = arith.addi %th512, %k264 : index + %ma1_8 = gpu.subgroup_mma_load_matrix %sx[%ao1_8] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + vx.subgroup_schedule_barrier + %r0_8 = gpu.subgroup_mma_compute %ma0_8, %mb0_8, %r0_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r1_8 = gpu.subgroup_mma_compute %ma0_8, %mb1_8, %r1_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r2_8 = gpu.subgroup_mma_compute %ma0_8, %mb2_8, %r2_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r3_8 = gpu.subgroup_mma_compute %ma0_8, %mb3_8, %r3_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r4_8 = gpu.subgroup_mma_compute %ma1_8, %mb0_8, %r4_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r5_8 = gpu.subgroup_mma_compute %ma1_8, %mb1_8, %r5_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r6_8 = gpu.subgroup_mma_compute %ma1_8, %mb2_8, %r6_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r7_8 = gpu.subgroup_mma_compute %ma1_8, %mb3_8, %r7_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + vx.subgroup_schedule_barrier + %bo0_16 = arith.addi %rh32, %k1024 : index + %mb0_16 = gpu.subgroup_mma_load_matrix %sw[%bo0_16] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo1_16 = arith.addi %rh32, %k1032 : index + %mb1_16 = gpu.subgroup_mma_load_matrix %sw[%bo1_16] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo2_16 = arith.addi %rh32, %k1040 : index + %mb2_16 = gpu.subgroup_mma_load_matrix %sw[%bo2_16] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo3_16 = arith.addi %rh32, %k1048 : index + %mb3_16 = gpu.subgroup_mma_load_matrix %sw[%bo3_16] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + vx.subgroup_schedule_barrier + %ao0_16 = arith.addi %th512, %k16 : index + %ma0_16 = gpu.subgroup_mma_load_matrix %sx[%ao0_16] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao1_16 = arith.addi %th512, %k272 : index + %ma1_16 = gpu.subgroup_mma_load_matrix %sx[%ao1_16] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + vx.subgroup_schedule_barrier + %r0_16 = gpu.subgroup_mma_compute %ma0_16, %mb0_16, %r0_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r1_16 = gpu.subgroup_mma_compute %ma0_16, %mb1_16, %r1_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r2_16 = gpu.subgroup_mma_compute %ma0_16, %mb2_16, %r2_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r3_16 = gpu.subgroup_mma_compute %ma0_16, %mb3_16, %r3_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r4_16 = gpu.subgroup_mma_compute %ma1_16, %mb0_16, %r4_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r5_16 = gpu.subgroup_mma_compute %ma1_16, %mb1_16, %r5_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r6_16 = gpu.subgroup_mma_compute %ma1_16, %mb2_16, %r6_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r7_16 = gpu.subgroup_mma_compute %ma1_16, %mb3_16, %r7_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + vx.subgroup_schedule_barrier + %bo0_24 = arith.addi %rh32, %k1536 : index + %mb0_24 = gpu.subgroup_mma_load_matrix %sw[%bo0_24] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo1_24 = arith.addi %rh32, %k1544 : index + %mb1_24 = gpu.subgroup_mma_load_matrix %sw[%bo1_24] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo2_24 = arith.addi %rh32, %k1552 : index + %mb2_24 = gpu.subgroup_mma_load_matrix %sw[%bo2_24] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo3_24 = arith.addi %rh32, %k1560 : index + %mb3_24 = gpu.subgroup_mma_load_matrix %sw[%bo3_24] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + vx.subgroup_schedule_barrier + %ao0_24 = arith.addi %th512, %k24 : index + %ma0_24 = gpu.subgroup_mma_load_matrix %sx[%ao0_24] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao1_24 = arith.addi %th512, %k280 : index + %ma1_24 = gpu.subgroup_mma_load_matrix %sx[%ao1_24] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + vx.subgroup_schedule_barrier + %r0_24 = gpu.subgroup_mma_compute %ma0_24, %mb0_24, %r0_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r1_24 = gpu.subgroup_mma_compute %ma0_24, %mb1_24, %r1_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r2_24 = gpu.subgroup_mma_compute %ma0_24, %mb2_24, %r2_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r3_24 = gpu.subgroup_mma_compute %ma0_24, %mb3_24, %r3_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r4_24 = gpu.subgroup_mma_compute %ma1_24, %mb0_24, %r4_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r5_24 = gpu.subgroup_mma_compute %ma1_24, %mb1_24, %r5_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r6_24 = gpu.subgroup_mma_compute %ma1_24, %mb2_24, %r6_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r7_24 = gpu.subgroup_mma_compute %ma1_24, %mb3_24, %r7_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + scf.yield %r0_24, %r1_24, %r2_24, %r3_24, %r4_24, %r5_24, %r6_24, %r7_24 : !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp"> + } else { + scf.yield %a0, %a1, %a2, %a3, %a4, %a5, %a6, %a7 : !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp"> + } + scf.yield %mm#0, %mm#1, %mm#2, %mm#3, %mm#4, %mm#5, %mm#6, %mm#7 : !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp"> } %th16 = arith.muli %th, %k16 : index %yr0 = arith.addi %tb32, %th16 : index @@ -1700,9 +1714,32 @@ fn pf_sort_by_expert(p : &mut Prefill, n : i32, k : i32, experts : i32) -> i32 { pf_count_experts(&mut p.e_counts, &mut p.e_lane_counts, &p.ids, n, k, experts); pf_place_experts(&p.e_rows, &p.slot, &p.e_counts, &p.e_lane_counts, &p.ids, n, k, experts); pf_expert_bases(&mut p.e_bases, &p.e_counts, experts, tiles); + pf_live_positions(&mut p.e_ident, &p.e_rows); return tiles; } +/// ident[p] = p where rows[p] has a token, and -1 for padding. The products of a chunk skip the +/// multiplies of the half of a tile of 32 that has only padding, so the list of the down product of +/// the experts, whose input rows are the positions, must have -1 for padding too. +fn pf_live_positions(ident : &mut Tensor, rows : &Tensor) -> void { + let positions = rows.len(); + spawn on(Topology::Device) { + for b in 0..(positions + 255) / 256 across blocks { + for l in 0..256 across lanes { + let p = b * 256 + l; + if p < positions { + if rows[p] >= 0 { + ident[p] = p; + } else { + ident[p] = -1; + } + } + } + } + } + return; +} + /// The mixture of experts of a layer, for the n tokens of the chunk: x += the experts of each /// token, for the norm of x in xn. fn pf_experts(p : &mut Prefill, layer : &Layer, c : &Config, n : i32, tiles : i32) -> void { diff --git a/src/prefill35.vx b/src/prefill35.vx index cca92b7..d1fd979 100644 --- a/src/prefill35.vx +++ b/src/prefill35.vx @@ -995,6 +995,7 @@ fn pf35_experts(p : &mut Prefill35, layer : &Qwen35Layer, c : &Config, n : i32, pf_count_experts(&mut p.e_counts, &mut p.e_lane_counts, &p.ids, n, k, experts); pf_place_experts(&p.e_rows, &p.slot, &p.e_counts, &p.e_lane_counts, &p.ids, n, k, experts); pf_expert_bases(&mut p.e_bases, &p.e_counts, experts, e_tiles); + pf_live_positions(&mut p.e_ident, &p.e_rows); pf_mm(&mut p.e_gu, &layer.gate_up, &p.xn, &p.e_rows, &p.e_bases, 2 * inter, &p.no_bias, false, false, 2 * inter, c.hidden_size, e_tiles); pf_silu_mul(&mut p.e_h, &p.e_gu, e_tiles * 16, inter); pf_mm(&mut p.e_out, &layer.down, &p.e_h, &p.e_ident, &p.e_bases, c.hidden_size, &p.no_bias, false, false, c.hidden_size, inter, e_tiles); From 413e932c79d4a592fab75205c5a7a1a025605045 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:03:03 -0800 Subject: [PATCH 21/60] Prefill products: skip the multiplies of padding by 8 tokens (#89) A SIMD group of the Q4_0 product of a chunk makes 2 rows of 8 tokens. It now skips the multiplies of each row whose first token is padding, in place of only the 16 tokens of a half block, so the multiplies of an expert go by 8 tokens and not 32. Informal, -O2, the real model, one chunk of 512 tokens, interleaved: the experts take 595 ms in place of 623 (gate_up 331 in place of 353, down 190 in place of 196). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- scripts/mlir_kernels/expert_product.py | 78 ++++---- src/prefill.vx | 258 ++++++++++++++++--------- 2 files changed, 210 insertions(+), 126 deletions(-) diff --git a/scripts/mlir_kernels/expert_product.py b/scripts/mlir_kernels/expert_product.py index 626c708..155fb2e 100755 --- a/scripts/mlir_kernels/expert_product.py +++ b/scripts/mlir_kernels/expert_product.py @@ -94,14 +94,16 @@ def c(n): 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('%th16 = arith.muli %th, %k16 : index') b('%rh32 = arith.muli %rh, %k32 : index') # sw[rh * 32] -# The tokens of an expert come first in its tiles, so when token 16 of the block is padding, so are -# tokens 16 to 31, and the subgroups of those tokens (th = 1) skip their multiplies. -b('%tb16 = arith.addi %tb32, %k16 : index') -b('%from16 = memref.load %list[%tb16] : memref') -b('%live16 = arith.cmpi sge, %from16, %zi : i32') -b('%th0 = arith.cmpi eq, %th, %k0 : index') -b('%busy = arith.ori %th0, %live16 : i1') +# 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. +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(8)) accty = ', '.join([ACC] * 8) b(f'%res:8 = scf.for %g = %k0 to %Gl step %k1 iter_args({accs}) -> ({accty}) {{') @@ -145,38 +147,46 @@ def c(n): 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>') d('gpu.barrier') -d(f'%mm:8 = scf.if %busy -> ({accty}) {{') -d0 = d -d = lambda s: d0(' ' + s) -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 8 sums; those of the other rows go through as they are.""" + 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): - 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 = d0 + 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}} : memref<1024xf16, 3> -> {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) +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 {') -d(' scf.yield ' + ', '.join(f'%a{i}' for i in range(8)) + ' : ' + accty) +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') b('%yc0 = arith.addi %rb64, %rh32 : index') diff --git a/src/prefill.vx b/src/prefill.vx index 3f281ae..f28bfea 100644 --- a/src/prefill.vx +++ b/src/prefill.vx @@ -405,9 +405,9 @@ fn pf_mm_q4_set(y : &mut Tensor, w : &Tensor, w : &Tensor %th512 = arith.muli %th, %k512 : index + %th16 = arith.muli %th, %k16 : index %rh32 = arith.muli %rh, %k32 : index - %tb16 = arith.addi %tb32, %k16 : index - %from16 = memref.load %list[%tb16] : memref - %live16 = arith.cmpi sge, %from16, %zi : i32 - %th0 = arith.cmpi eq, %th, %k0 : index - %busy = arith.ori %th0, %live16 : i1 + %tf0 = arith.addi %tb32, %th16 : index + %tf1 = arith.addi %tf0, %k8 : index + %from_t0 = memref.load %list[%tf0] : memref + %busy0 = arith.cmpi sge, %from_t0, %zi : i32 + %from_t1 = memref.load %list[%tf1] : memref + %busy1 = arith.cmpi sge, %from_t1, %zi : i32 %res:8 = scf.for %g = %k0 to %Gl step %k1 iter_args(%a0 = %z, %a1 = %z, %a2 = %z, %a3 = %z, %a4 = %z, %a5 = %z, %a6 = %z, %a7 = %z) -> (!gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">) { %g4 = arith.muli %g, %k4 : index %wa = arith.addi %wbase, %g4 : index @@ -606,106 +608,178 @@ fn pf_mm_q4_mlir(y : &mut Tensor, w : &Tensor, vector<4xf16> vector.store %h1, %sx[%sxd4] {alignment = 8} : memref<1024xf16, 3>, vector<4xf16> gpu.barrier - %mm:8 = scf.if %busy -> (!gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">) { + %mm:8 = scf.if %busy1 -> (!gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">) { vx.subgroup_schedule_barrier - %bo0_0 = arith.addi %rh32, %k0 : index - %mb0_0 = gpu.subgroup_mma_load_matrix %sw[%bo0_0] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - %bo1_0 = arith.addi %rh32, %k8 : index - %mb1_0 = gpu.subgroup_mma_load_matrix %sw[%bo1_0] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - %bo2_0 = arith.addi %rh32, %k16 : index - %mb2_0 = gpu.subgroup_mma_load_matrix %sw[%bo2_0] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - %bo3_0 = arith.addi %rh32, %k24 : index - %mb3_0 = gpu.subgroup_mma_load_matrix %sw[%bo3_0] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo0_0f = arith.addi %rh32, %k0 : index + %mb0_0f = gpu.subgroup_mma_load_matrix %sw[%bo0_0f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo1_0f = arith.addi %rh32, %k8 : index + %mb1_0f = gpu.subgroup_mma_load_matrix %sw[%bo1_0f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo2_0f = arith.addi %rh32, %k16 : index + %mb2_0f = gpu.subgroup_mma_load_matrix %sw[%bo2_0f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo3_0f = arith.addi %rh32, %k24 : index + %mb3_0f = gpu.subgroup_mma_load_matrix %sw[%bo3_0f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> vx.subgroup_schedule_barrier - %ao0_0 = arith.addi %th512, %k0 : index - %ma0_0 = gpu.subgroup_mma_load_matrix %sx[%ao0_0] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> - %ao1_0 = arith.addi %th512, %k256 : index - %ma1_0 = gpu.subgroup_mma_load_matrix %sx[%ao1_0] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao0_0f = arith.addi %th512, %k0 : index + %ma0_0f = gpu.subgroup_mma_load_matrix %sx[%ao0_0f] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao1_0f = arith.addi %th512, %k256 : index + %ma1_0f = gpu.subgroup_mma_load_matrix %sx[%ao1_0f] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> vx.subgroup_schedule_barrier - %r0_0 = gpu.subgroup_mma_compute %ma0_0, %mb0_0, %a0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r1_0 = gpu.subgroup_mma_compute %ma0_0, %mb1_0, %a1 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r2_0 = gpu.subgroup_mma_compute %ma0_0, %mb2_0, %a2 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r3_0 = gpu.subgroup_mma_compute %ma0_0, %mb3_0, %a3 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r4_0 = gpu.subgroup_mma_compute %ma1_0, %mb0_0, %a4 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r5_0 = gpu.subgroup_mma_compute %ma1_0, %mb1_0, %a5 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r6_0 = gpu.subgroup_mma_compute %ma1_0, %mb2_0, %a6 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r7_0 = gpu.subgroup_mma_compute %ma1_0, %mb3_0, %a7 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r0_0f = gpu.subgroup_mma_compute %ma0_0f, %mb0_0f, %a0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r1_0f = gpu.subgroup_mma_compute %ma0_0f, %mb1_0f, %a1 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r2_0f = gpu.subgroup_mma_compute %ma0_0f, %mb2_0f, %a2 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r3_0f = gpu.subgroup_mma_compute %ma0_0f, %mb3_0f, %a3 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r4_0f = gpu.subgroup_mma_compute %ma1_0f, %mb0_0f, %a4 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r5_0f = gpu.subgroup_mma_compute %ma1_0f, %mb1_0f, %a5 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r6_0f = gpu.subgroup_mma_compute %ma1_0f, %mb2_0f, %a6 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r7_0f = gpu.subgroup_mma_compute %ma1_0f, %mb3_0f, %a7 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> vx.subgroup_schedule_barrier - %bo0_8 = arith.addi %rh32, %k512 : index - %mb0_8 = gpu.subgroup_mma_load_matrix %sw[%bo0_8] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - %bo1_8 = arith.addi %rh32, %k520 : index - %mb1_8 = gpu.subgroup_mma_load_matrix %sw[%bo1_8] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - %bo2_8 = arith.addi %rh32, %k528 : index - %mb2_8 = gpu.subgroup_mma_load_matrix %sw[%bo2_8] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - %bo3_8 = arith.addi %rh32, %k536 : index - %mb3_8 = gpu.subgroup_mma_load_matrix %sw[%bo3_8] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo0_8f = arith.addi %rh32, %k512 : index + %mb0_8f = gpu.subgroup_mma_load_matrix %sw[%bo0_8f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo1_8f = arith.addi %rh32, %k520 : index + %mb1_8f = gpu.subgroup_mma_load_matrix %sw[%bo1_8f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo2_8f = arith.addi %rh32, %k528 : index + %mb2_8f = gpu.subgroup_mma_load_matrix %sw[%bo2_8f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo3_8f = arith.addi %rh32, %k536 : index + %mb3_8f = gpu.subgroup_mma_load_matrix %sw[%bo3_8f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> vx.subgroup_schedule_barrier - %ao0_8 = arith.addi %th512, %k8 : index - %ma0_8 = gpu.subgroup_mma_load_matrix %sx[%ao0_8] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> - %ao1_8 = arith.addi %th512, %k264 : index - %ma1_8 = gpu.subgroup_mma_load_matrix %sx[%ao1_8] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao0_8f = arith.addi %th512, %k8 : index + %ma0_8f = gpu.subgroup_mma_load_matrix %sx[%ao0_8f] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao1_8f = arith.addi %th512, %k264 : index + %ma1_8f = gpu.subgroup_mma_load_matrix %sx[%ao1_8f] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> vx.subgroup_schedule_barrier - %r0_8 = gpu.subgroup_mma_compute %ma0_8, %mb0_8, %r0_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r1_8 = gpu.subgroup_mma_compute %ma0_8, %mb1_8, %r1_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r2_8 = gpu.subgroup_mma_compute %ma0_8, %mb2_8, %r2_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r3_8 = gpu.subgroup_mma_compute %ma0_8, %mb3_8, %r3_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r4_8 = gpu.subgroup_mma_compute %ma1_8, %mb0_8, %r4_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r5_8 = gpu.subgroup_mma_compute %ma1_8, %mb1_8, %r5_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r6_8 = gpu.subgroup_mma_compute %ma1_8, %mb2_8, %r6_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r7_8 = gpu.subgroup_mma_compute %ma1_8, %mb3_8, %r7_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r0_8f = gpu.subgroup_mma_compute %ma0_8f, %mb0_8f, %r0_0f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r1_8f = gpu.subgroup_mma_compute %ma0_8f, %mb1_8f, %r1_0f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r2_8f = gpu.subgroup_mma_compute %ma0_8f, %mb2_8f, %r2_0f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r3_8f = gpu.subgroup_mma_compute %ma0_8f, %mb3_8f, %r3_0f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r4_8f = gpu.subgroup_mma_compute %ma1_8f, %mb0_8f, %r4_0f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r5_8f = gpu.subgroup_mma_compute %ma1_8f, %mb1_8f, %r5_0f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r6_8f = gpu.subgroup_mma_compute %ma1_8f, %mb2_8f, %r6_0f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r7_8f = gpu.subgroup_mma_compute %ma1_8f, %mb3_8f, %r7_0f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> vx.subgroup_schedule_barrier - %bo0_16 = arith.addi %rh32, %k1024 : index - %mb0_16 = gpu.subgroup_mma_load_matrix %sw[%bo0_16] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - %bo1_16 = arith.addi %rh32, %k1032 : index - %mb1_16 = gpu.subgroup_mma_load_matrix %sw[%bo1_16] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - %bo2_16 = arith.addi %rh32, %k1040 : index - %mb2_16 = gpu.subgroup_mma_load_matrix %sw[%bo2_16] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - %bo3_16 = arith.addi %rh32, %k1048 : index - %mb3_16 = gpu.subgroup_mma_load_matrix %sw[%bo3_16] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo0_16f = arith.addi %rh32, %k1024 : index + %mb0_16f = gpu.subgroup_mma_load_matrix %sw[%bo0_16f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo1_16f = arith.addi %rh32, %k1032 : index + %mb1_16f = gpu.subgroup_mma_load_matrix %sw[%bo1_16f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo2_16f = arith.addi %rh32, %k1040 : index + %mb2_16f = gpu.subgroup_mma_load_matrix %sw[%bo2_16f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo3_16f = arith.addi %rh32, %k1048 : index + %mb3_16f = gpu.subgroup_mma_load_matrix %sw[%bo3_16f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> vx.subgroup_schedule_barrier - %ao0_16 = arith.addi %th512, %k16 : index - %ma0_16 = gpu.subgroup_mma_load_matrix %sx[%ao0_16] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> - %ao1_16 = arith.addi %th512, %k272 : index - %ma1_16 = gpu.subgroup_mma_load_matrix %sx[%ao1_16] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao0_16f = arith.addi %th512, %k16 : index + %ma0_16f = gpu.subgroup_mma_load_matrix %sx[%ao0_16f] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao1_16f = arith.addi %th512, %k272 : index + %ma1_16f = gpu.subgroup_mma_load_matrix %sx[%ao1_16f] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> vx.subgroup_schedule_barrier - %r0_16 = gpu.subgroup_mma_compute %ma0_16, %mb0_16, %r0_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r1_16 = gpu.subgroup_mma_compute %ma0_16, %mb1_16, %r1_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r2_16 = gpu.subgroup_mma_compute %ma0_16, %mb2_16, %r2_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r3_16 = gpu.subgroup_mma_compute %ma0_16, %mb3_16, %r3_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r4_16 = gpu.subgroup_mma_compute %ma1_16, %mb0_16, %r4_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r5_16 = gpu.subgroup_mma_compute %ma1_16, %mb1_16, %r5_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r6_16 = gpu.subgroup_mma_compute %ma1_16, %mb2_16, %r6_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r7_16 = gpu.subgroup_mma_compute %ma1_16, %mb3_16, %r7_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r0_16f = gpu.subgroup_mma_compute %ma0_16f, %mb0_16f, %r0_8f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r1_16f = gpu.subgroup_mma_compute %ma0_16f, %mb1_16f, %r1_8f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r2_16f = gpu.subgroup_mma_compute %ma0_16f, %mb2_16f, %r2_8f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r3_16f = gpu.subgroup_mma_compute %ma0_16f, %mb3_16f, %r3_8f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r4_16f = gpu.subgroup_mma_compute %ma1_16f, %mb0_16f, %r4_8f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r5_16f = gpu.subgroup_mma_compute %ma1_16f, %mb1_16f, %r5_8f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r6_16f = gpu.subgroup_mma_compute %ma1_16f, %mb2_16f, %r6_8f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r7_16f = gpu.subgroup_mma_compute %ma1_16f, %mb3_16f, %r7_8f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> vx.subgroup_schedule_barrier - %bo0_24 = arith.addi %rh32, %k1536 : index - %mb0_24 = gpu.subgroup_mma_load_matrix %sw[%bo0_24] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - %bo1_24 = arith.addi %rh32, %k1544 : index - %mb1_24 = gpu.subgroup_mma_load_matrix %sw[%bo1_24] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - %bo2_24 = arith.addi %rh32, %k1552 : index - %mb2_24 = gpu.subgroup_mma_load_matrix %sw[%bo2_24] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> - %bo3_24 = arith.addi %rh32, %k1560 : index - %mb3_24 = gpu.subgroup_mma_load_matrix %sw[%bo3_24] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo0_24f = arith.addi %rh32, %k1536 : index + %mb0_24f = gpu.subgroup_mma_load_matrix %sw[%bo0_24f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo1_24f = arith.addi %rh32, %k1544 : index + %mb1_24f = gpu.subgroup_mma_load_matrix %sw[%bo1_24f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo2_24f = arith.addi %rh32, %k1552 : index + %mb2_24f = gpu.subgroup_mma_load_matrix %sw[%bo2_24f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo3_24f = arith.addi %rh32, %k1560 : index + %mb3_24f = gpu.subgroup_mma_load_matrix %sw[%bo3_24f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> vx.subgroup_schedule_barrier - %ao0_24 = arith.addi %th512, %k24 : index - %ma0_24 = gpu.subgroup_mma_load_matrix %sx[%ao0_24] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> - %ao1_24 = arith.addi %th512, %k280 : index - %ma1_24 = gpu.subgroup_mma_load_matrix %sx[%ao1_24] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao0_24f = arith.addi %th512, %k24 : index + %ma0_24f = gpu.subgroup_mma_load_matrix %sx[%ao0_24f] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao1_24f = arith.addi %th512, %k280 : index + %ma1_24f = gpu.subgroup_mma_load_matrix %sx[%ao1_24f] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> vx.subgroup_schedule_barrier - %r0_24 = gpu.subgroup_mma_compute %ma0_24, %mb0_24, %r0_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r1_24 = gpu.subgroup_mma_compute %ma0_24, %mb1_24, %r1_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r2_24 = gpu.subgroup_mma_compute %ma0_24, %mb2_24, %r2_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r3_24 = gpu.subgroup_mma_compute %ma0_24, %mb3_24, %r3_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r4_24 = gpu.subgroup_mma_compute %ma1_24, %mb0_24, %r4_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r5_24 = gpu.subgroup_mma_compute %ma1_24, %mb1_24, %r5_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r6_24 = gpu.subgroup_mma_compute %ma1_24, %mb2_24, %r6_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - %r7_24 = gpu.subgroup_mma_compute %ma1_24, %mb3_24, %r7_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> - scf.yield %r0_24, %r1_24, %r2_24, %r3_24, %r4_24, %r5_24, %r6_24, %r7_24 : !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp"> + %r0_24f = gpu.subgroup_mma_compute %ma0_24f, %mb0_24f, %r0_16f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r1_24f = gpu.subgroup_mma_compute %ma0_24f, %mb1_24f, %r1_16f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r2_24f = gpu.subgroup_mma_compute %ma0_24f, %mb2_24f, %r2_16f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r3_24f = gpu.subgroup_mma_compute %ma0_24f, %mb3_24f, %r3_16f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r4_24f = gpu.subgroup_mma_compute %ma1_24f, %mb0_24f, %r4_16f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r5_24f = gpu.subgroup_mma_compute %ma1_24f, %mb1_24f, %r5_16f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r6_24f = gpu.subgroup_mma_compute %ma1_24f, %mb2_24f, %r6_16f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r7_24f = gpu.subgroup_mma_compute %ma1_24f, %mb3_24f, %r7_16f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + scf.yield %r0_24f, %r1_24f, %r2_24f, %r3_24f, %r4_24f, %r5_24f, %r6_24f, %r7_24f : !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp"> } else { - scf.yield %a0, %a1, %a2, %a3, %a4, %a5, %a6, %a7 : !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp"> + %mh:8 = scf.if %busy0 -> (!gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">) { + vx.subgroup_schedule_barrier + %bo0_0h = arith.addi %rh32, %k0 : index + %mb0_0h = gpu.subgroup_mma_load_matrix %sw[%bo0_0h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo1_0h = arith.addi %rh32, %k8 : index + %mb1_0h = gpu.subgroup_mma_load_matrix %sw[%bo1_0h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo2_0h = arith.addi %rh32, %k16 : index + %mb2_0h = gpu.subgroup_mma_load_matrix %sw[%bo2_0h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo3_0h = arith.addi %rh32, %k24 : index + %mb3_0h = gpu.subgroup_mma_load_matrix %sw[%bo3_0h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + vx.subgroup_schedule_barrier + %ao0_0h = arith.addi %th512, %k0 : index + %ma0_0h = gpu.subgroup_mma_load_matrix %sx[%ao0_0h] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + vx.subgroup_schedule_barrier + %r0_0h = gpu.subgroup_mma_compute %ma0_0h, %mb0_0h, %a0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r1_0h = gpu.subgroup_mma_compute %ma0_0h, %mb1_0h, %a1 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r2_0h = gpu.subgroup_mma_compute %ma0_0h, %mb2_0h, %a2 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r3_0h = gpu.subgroup_mma_compute %ma0_0h, %mb3_0h, %a3 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + vx.subgroup_schedule_barrier + %bo0_8h = arith.addi %rh32, %k512 : index + %mb0_8h = gpu.subgroup_mma_load_matrix %sw[%bo0_8h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo1_8h = arith.addi %rh32, %k520 : index + %mb1_8h = gpu.subgroup_mma_load_matrix %sw[%bo1_8h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo2_8h = arith.addi %rh32, %k528 : index + %mb2_8h = gpu.subgroup_mma_load_matrix %sw[%bo2_8h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo3_8h = arith.addi %rh32, %k536 : index + %mb3_8h = gpu.subgroup_mma_load_matrix %sw[%bo3_8h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + vx.subgroup_schedule_barrier + %ao0_8h = arith.addi %th512, %k8 : index + %ma0_8h = gpu.subgroup_mma_load_matrix %sx[%ao0_8h] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + vx.subgroup_schedule_barrier + %r0_8h = gpu.subgroup_mma_compute %ma0_8h, %mb0_8h, %r0_0h : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r1_8h = gpu.subgroup_mma_compute %ma0_8h, %mb1_8h, %r1_0h : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r2_8h = gpu.subgroup_mma_compute %ma0_8h, %mb2_8h, %r2_0h : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r3_8h = gpu.subgroup_mma_compute %ma0_8h, %mb3_8h, %r3_0h : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + vx.subgroup_schedule_barrier + %bo0_16h = arith.addi %rh32, %k1024 : index + %mb0_16h = gpu.subgroup_mma_load_matrix %sw[%bo0_16h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo1_16h = arith.addi %rh32, %k1032 : index + %mb1_16h = gpu.subgroup_mma_load_matrix %sw[%bo1_16h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo2_16h = arith.addi %rh32, %k1040 : index + %mb2_16h = gpu.subgroup_mma_load_matrix %sw[%bo2_16h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo3_16h = arith.addi %rh32, %k1048 : index + %mb3_16h = gpu.subgroup_mma_load_matrix %sw[%bo3_16h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + vx.subgroup_schedule_barrier + %ao0_16h = arith.addi %th512, %k16 : index + %ma0_16h = gpu.subgroup_mma_load_matrix %sx[%ao0_16h] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + vx.subgroup_schedule_barrier + %r0_16h = gpu.subgroup_mma_compute %ma0_16h, %mb0_16h, %r0_8h : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r1_16h = gpu.subgroup_mma_compute %ma0_16h, %mb1_16h, %r1_8h : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r2_16h = gpu.subgroup_mma_compute %ma0_16h, %mb2_16h, %r2_8h : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r3_16h = gpu.subgroup_mma_compute %ma0_16h, %mb3_16h, %r3_8h : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + vx.subgroup_schedule_barrier + %bo0_24h = arith.addi %rh32, %k1536 : index + %mb0_24h = gpu.subgroup_mma_load_matrix %sw[%bo0_24h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo1_24h = arith.addi %rh32, %k1544 : index + %mb1_24h = gpu.subgroup_mma_load_matrix %sw[%bo1_24h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo2_24h = arith.addi %rh32, %k1552 : index + %mb2_24h = gpu.subgroup_mma_load_matrix %sw[%bo2_24h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo3_24h = arith.addi %rh32, %k1560 : index + %mb3_24h = gpu.subgroup_mma_load_matrix %sw[%bo3_24h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + vx.subgroup_schedule_barrier + %ao0_24h = arith.addi %th512, %k24 : index + %ma0_24h = gpu.subgroup_mma_load_matrix %sx[%ao0_24h] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + vx.subgroup_schedule_barrier + %r0_24h = gpu.subgroup_mma_compute %ma0_24h, %mb0_24h, %r0_16h : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r1_24h = gpu.subgroup_mma_compute %ma0_24h, %mb1_24h, %r1_16h : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r2_24h = gpu.subgroup_mma_compute %ma0_24h, %mb2_24h, %r2_16h : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r3_24h = gpu.subgroup_mma_compute %ma0_24h, %mb3_24h, %r3_16h : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + scf.yield %r0_24h, %r1_24h, %r2_24h, %r3_24h, %a4, %a5, %a6, %a7 : !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp"> + } else { + scf.yield %a0, %a1, %a2, %a3, %a4, %a5, %a6, %a7 : !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp"> + } + scf.yield %mh#0, %mh#1, %mh#2, %mh#3, %mh#4, %mh#5, %mh#6, %mh#7 : !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp"> } scf.yield %mm#0, %mm#1, %mm#2, %mm#3, %mm#4, %mm#5, %mm#6, %mm#7 : !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp"> } - %th16 = arith.muli %th, %k16 : index %yr0 = arith.addi %tb32, %th16 : index %yr1 = arith.addi %yr0, %k8 : index %yc0 = arith.addi %rb64, %rh32 : index From 3ee766ddb55cfc4d1386a0ce7fcdaabde3947c36 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:41:58 -0800 Subject: [PATCH 22/60] Prefill of Qwen3.6: the router in the fast kernel, SiLU of live rows (#89) The router of a chunk (257 rows of bf16) took 47 ms of a 512-token prompt of Qwen3.6-35B-A3B in pf_mm_bf16. expert_product.py --bf16 now prints pf_mm_bf16_mlir: the product of pf_mm_q4_mlir, with bf16 weights that go to f16 in shared memory. Rows need not be a multiple of 64; `router` gets the columns of whole blocks of 64. The router weights of the model are below 0.4, and the f16 of a weight below 6.1e-5 is off by 3e-8 at most. pf35_experts uses it when the experts are Q4_0, whose products round to f16 already. A bf16 file keeps the f32 router (the long bf16 test of tests/generate_qwen35.vx found 0.004 with the f16 router). pf_silu_mul_live skips the positions of padding (e_ident -1): the SwiGLU of the experts ran on all 12,032 positions of the chunk for 4,096 choices. Informal, -O2, the real model, interleaved: router 21 ms in place of 47, SiLU 32 in place of 42; a prompt of 512 tokens 1,180 ms in place of 1,212. The tokens of the reference prompt and of a 48-step code-edit prompt stay the same. The logits of the code-edit prompt move by 0.02 to 0.2 (0.46 at most), as the f16 of the router moves near ties. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- scripts/mlir_kernels/expert_product.py | 62 +++- src/prefill.vx | 416 ++++++++++++++++++++++++- src/prefill35.vx | 14 +- 3 files changed, 470 insertions(+), 22 deletions(-) diff --git a/scripts/mlir_kernels/expert_product.py b/scripts/mlir_kernels/expert_product.py index 155fb2e..f21a5a1 100755 --- a/scripts/mlir_kernels/expert_product.py +++ b/scripts/mlir_kernels/expert_product.py @@ -3,16 +3,18 @@ # 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:] hint = True ACC = '!gpu.mma_matrix<8x8xf32, "COp">' AOP = '!gpu.mma_matrix<8x8xf16, "AOp">' @@ -20,13 +22,16 @@ 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' +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 rb in 0..(rows + 63) / 64 across blocks {' if bf16 else ' 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(' 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(' let _d = mlir!( threads : 128, inputs : (%sw = &mut sw : memref<2048xf16, 3>, %sx = &mut sx : memref<1024xf16, 3>, %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 * 32..tb * 32 + 32][rb * 64..rb * 64 + 64])]) {') b = lambda s: e(' ' + s) consts = {} def c(n): @@ -64,10 +69,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 @@ -108,15 +123,28 @@ def c(n): accty = ', '.join([ACC] * 8) b(f'%res:8 = 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']): diff --git a/src/prefill.vx b/src/prefill.vx index f28bfea..6da4b56 100644 --- a/src/prefill.vx +++ b/src/prefill.vx @@ -802,6 +802,401 @@ fn pf_mm_q4_mlir(y : &mut Tensor, w : &Tensor, w : &Tensor, x : &Tensor, list : &Tensor, bases : &Tensor, stride : i32, rows : i32, cols : i32, tiles : i32) -> void { + spawn on(Topology::Device) { + for rb in 0..(rows + 63) / 64 across blocks { + for tb in 0..(tiles + 1) / 2 across blocks { + let mut sw = unsafe { Tensor::uninit() }; + let mut sx = unsafe { Tensor::uninit() }; + let _d = mlir!( threads : 128, inputs : (%sw = &mut sw : memref<2048xf16, 3>, %sx = &mut sx : memref<1024xf16, 3>, %y = y : memref, %w = w : memref, %rows = rows : i32, %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"], ensures : [writes_only(sw), writes_only(sx), reads_only(w), reads_only(x), reads_only(list), reads_only(bases), writes_only(y[tb * 32..tb * 32 + 32][rb * 64..rb * 64 + 64])]) { + %k0 = arith.constant 0 : index + %k1 = arith.constant 1 : index + %k2 = arith.constant 2 : index + %k4 = arith.constant 4 : index + %k8 = arith.constant 8 : index + %k12 = arith.constant 12 : index + %k16 = arith.constant 16 : index + %k24 = arith.constant 24 : index + %k32 = arith.constant 32 : index + %k64 = arith.constant 64 : index + %k128 = arith.constant 128 : index + %k192 = arith.constant 192 : index + %k256 = arith.constant 256 : index + %k264 = arith.constant 264 : index + %k272 = arith.constant 272 : index + %k280 = arith.constant 280 : index + %k320 = arith.constant 320 : index + %k384 = arith.constant 384 : index + %k448 = arith.constant 448 : index + %k512 = arith.constant 512 : index + %k520 = arith.constant 520 : index + %k528 = arith.constant 528 : index + %k536 = arith.constant 536 : index + %k576 = arith.constant 576 : index + %k640 = arith.constant 640 : index + %k704 = arith.constant 704 : index + %k768 = arith.constant 768 : index + %k832 = arith.constant 832 : index + %k896 = arith.constant 896 : index + %k960 = arith.constant 960 : index + %k1024 = arith.constant 1024 : index + %k1032 = arith.constant 1032 : index + %k1040 = arith.constant 1040 : index + %k1048 = arith.constant 1048 : index + %k1536 = arith.constant 1536 : index + %k1544 = arith.constant 1544 : index + %k1552 = arith.constant 1552 : index + %k1560 = arith.constant 1560 : index + %tid = gpu.thread_id x + %sg = arith.divui %tid, %k32 : index + %l = arith.remui %tid, %k32 : index + %th = arith.divui %sg, %k2 : index + %rh = arith.remui %sg, %k2 : index + %rbi = arith.index_cast %rb : i32 to index + %tbi = arith.index_cast %tb : i32 to index + %stridei = arith.index_cast %stride : i32 to index + %colsi = arith.index_cast %cols : i32 to index + %G = arith.divui %colsi, %k32 : index + %WPR = arith.divui %colsi, %k8 : index + %tbb = arith.muli %tbi, %k2 : index + %base32 = memref.load %bases[%tbb] : memref + %zi = arith.constant 0 : i32 + %bok = arith.cmpi sge, %base32, %zi : i32 + %basec = arith.maxsi %base32, %zi : i32 + %base = arith.index_cast %basec : i32 to index + %Gl = arith.select %bok, %G, %k0 : index + %sg16 = arith.muli %sg, %k16 : index + %l2 = arith.divui %l, %k2 : index + %kh = arith.remui %l, %k2 : index + %rl = arith.addi %sg16, %l2 : index + %rb64 = arith.muli %rbi, %k64 : index + %r = arith.addi %rb64, %rl : index + %bs = arith.muli %base, %stridei : index + %row = arith.addi %bs, %r : index + %rowsi = arith.index_cast %rows : i32 to index + %rok = arith.cmpi ult, %r, %rowsi : index + %rowc = arith.select %rok, %row, %k0 : index + %rw = arith.muli %rowc, %colsi : index + %kh16 = arith.muli %kh, %k16 : index + %wbase = arith.addi %rw, %kh16 : index + %hz = arith.constant dense<0.0> : vector<4xf16> + %kh1024 = arith.muli %kh, %k1024 : index + %swd = arith.addi %kh1024, %rl : index + %sg8 = arith.muli %sg, %k8 : index + %l4 = arith.divui %l, %k4 : index + %lm4 = arith.remui %l, %k4 : index + %tl = arith.addi %sg8, %l4 : index + %cl = arith.muli %lm4, %k8 : index + %tb32 = arith.muli %tbi, %k32 : index + %li = arith.addi %tb32, %tl : index + %from32 = memref.load %list[%li] : memref + %live = arith.cmpi sge, %from32, %zi : i32 + %fromc = arith.maxsi %from32, %zi : i32 + %from = arith.index_cast %fromc : i32 to index + %tl32 = arith.muli %tl, %k32 : index + %sxd = arith.addi %tl32, %cl : index + %sxd4 = arith.addi %sxd, %k4 : index + %shl = arith.constant dense<[0, 4, 8, 12]> : vector<4xi32> + %shh = arith.constant dense<[16, 20, 24, 28]> : vector<4xi32> + %m15 = arith.constant dense<15> : vector<4xi32> + %vz = arith.constant dense<0.0> : vector<4xf32> + %m8 = arith.constant -8.0 : f16 + %zf = arith.constant 0.0 : f32 + %z = gpu.subgroup_mma_constant_matrix %zf : !gpu.mma_matrix<8x8xf32, "COp"> + %th512 = arith.muli %th, %k512 : index + %th16 = arith.muli %th, %k16 : index + %rh32 = arith.muli %rh, %k32 : index + %tf0 = arith.addi %tb32, %th16 : index + %tf1 = arith.addi %tf0, %k8 : index + %from_t0 = memref.load %list[%tf0] : memref + %busy0 = arith.cmpi sge, %from_t0, %zi : i32 + %from_t1 = memref.load %list[%tf1] : memref + %busy1 = arith.cmpi sge, %from_t1, %zi : i32 + %res:8 = scf.for %g = %k0 to %Gl step %k1 iter_args(%a0 = %z, %a1 = %z, %a2 = %z, %a3 = %z, %a4 = %z, %a5 = %z, %a6 = %z, %a7 = %z) -> (!gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">) { + %g32w = arith.muli %g, %k32 : index + %wa = arith.addi %wbase, %g32w : index + %wa00 = arith.addi %wa, %k0 : index + %b00 = vector.load %w[%wa00] {alignment = 8} : memref, vector<4xbf16> + %we00 = arith.extf %b00 : vector<4xbf16> to vector<4xf32> + %t00 = arith.truncf %we00 : vector<4xf32> to vector<4xf16> + %d00 = arith.select %rok, %t00, %hz : vector<4xf16> + %wa01 = arith.addi %wa, %k4 : index + %b01 = vector.load %w[%wa01] {alignment = 8} : memref, vector<4xbf16> + %we01 = arith.extf %b01 : vector<4xbf16> to vector<4xf32> + %t01 = arith.truncf %we01 : vector<4xf32> to vector<4xf16> + %d01 = arith.select %rok, %t01, %hz : vector<4xf16> + %wa10 = arith.addi %wa, %k8 : index + %b10 = vector.load %w[%wa10] {alignment = 8} : memref, vector<4xbf16> + %we10 = arith.extf %b10 : vector<4xbf16> to vector<4xf32> + %t10 = arith.truncf %we10 : vector<4xf32> to vector<4xf16> + %d10 = arith.select %rok, %t10, %hz : vector<4xf16> + %wa11 = arith.addi %wa, %k12 : index + %b11 = vector.load %w[%wa11] {alignment = 8} : memref, vector<4xbf16> + %we11 = arith.extf %b11 : vector<4xbf16> to vector<4xf32> + %t11 = arith.truncf %we11 : vector<4xf32> to vector<4xf16> + %d11 = arith.select %rok, %t11, %hz : vector<4xf16> + %g32 = arith.muli %g, %k32 : index + %xc = arith.addi %g32, %cl : index + %xc4 = arith.addi %xc, %k4 : index + %x0r = vector.load %x[%from, %xc] {alignment = 16} : memref, vector<4xf32> + %x1r = vector.load %x[%from, %xc4] {alignment = 16} : memref, vector<4xf32> + %x0 = arith.select %live, %x0r, %vz : vector<4xf32> + %x1 = arith.select %live, %x1r, %vz : vector<4xf32> + %h0 = arith.truncf %x0 : vector<4xf32> to vector<4xf16> + %h1 = arith.truncf %x1 : vector<4xf32> to vector<4xf16> + gpu.barrier + %e0 = vector.extract %d00[0] : f16 from vector<4xf16> + memref.store %e0, %sw[%swd] : memref<2048xf16, 3> + %e1 = vector.extract %d00[1] : f16 from vector<4xf16> + %o1 = arith.addi %swd, %k64 : index + memref.store %e1, %sw[%o1] : memref<2048xf16, 3> + %e2 = vector.extract %d00[2] : f16 from vector<4xf16> + %o2 = arith.addi %swd, %k128 : index + memref.store %e2, %sw[%o2] : memref<2048xf16, 3> + %e3 = vector.extract %d00[3] : f16 from vector<4xf16> + %o3 = arith.addi %swd, %k192 : index + memref.store %e3, %sw[%o3] : memref<2048xf16, 3> + %e4 = vector.extract %d01[0] : f16 from vector<4xf16> + %o4 = arith.addi %swd, %k256 : index + memref.store %e4, %sw[%o4] : memref<2048xf16, 3> + %e5 = vector.extract %d01[1] : f16 from vector<4xf16> + %o5 = arith.addi %swd, %k320 : index + memref.store %e5, %sw[%o5] : memref<2048xf16, 3> + %e6 = vector.extract %d01[2] : f16 from vector<4xf16> + %o6 = arith.addi %swd, %k384 : index + memref.store %e6, %sw[%o6] : memref<2048xf16, 3> + %e7 = vector.extract %d01[3] : f16 from vector<4xf16> + %o7 = arith.addi %swd, %k448 : index + memref.store %e7, %sw[%o7] : memref<2048xf16, 3> + %e8 = vector.extract %d10[0] : f16 from vector<4xf16> + %o8 = arith.addi %swd, %k512 : index + memref.store %e8, %sw[%o8] : memref<2048xf16, 3> + %e9 = vector.extract %d10[1] : f16 from vector<4xf16> + %o9 = arith.addi %swd, %k576 : index + memref.store %e9, %sw[%o9] : memref<2048xf16, 3> + %e10 = vector.extract %d10[2] : f16 from vector<4xf16> + %o10 = arith.addi %swd, %k640 : index + memref.store %e10, %sw[%o10] : memref<2048xf16, 3> + %e11 = vector.extract %d10[3] : f16 from vector<4xf16> + %o11 = arith.addi %swd, %k704 : index + memref.store %e11, %sw[%o11] : memref<2048xf16, 3> + %e12 = vector.extract %d11[0] : f16 from vector<4xf16> + %o12 = arith.addi %swd, %k768 : index + memref.store %e12, %sw[%o12] : memref<2048xf16, 3> + %e13 = vector.extract %d11[1] : f16 from vector<4xf16> + %o13 = arith.addi %swd, %k832 : index + memref.store %e13, %sw[%o13] : memref<2048xf16, 3> + %e14 = vector.extract %d11[2] : f16 from vector<4xf16> + %o14 = arith.addi %swd, %k896 : index + memref.store %e14, %sw[%o14] : memref<2048xf16, 3> + %e15 = vector.extract %d11[3] : f16 from vector<4xf16> + %o15 = arith.addi %swd, %k960 : index + memref.store %e15, %sw[%o15] : memref<2048xf16, 3> + vector.store %h0, %sx[%sxd] {alignment = 8} : memref<1024xf16, 3>, vector<4xf16> + vector.store %h1, %sx[%sxd4] {alignment = 8} : memref<1024xf16, 3>, vector<4xf16> + gpu.barrier + %mm:8 = scf.if %busy1 -> (!gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">) { + vx.subgroup_schedule_barrier + %bo0_0f = arith.addi %rh32, %k0 : index + %mb0_0f = gpu.subgroup_mma_load_matrix %sw[%bo0_0f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo1_0f = arith.addi %rh32, %k8 : index + %mb1_0f = gpu.subgroup_mma_load_matrix %sw[%bo1_0f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo2_0f = arith.addi %rh32, %k16 : index + %mb2_0f = gpu.subgroup_mma_load_matrix %sw[%bo2_0f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo3_0f = arith.addi %rh32, %k24 : index + %mb3_0f = gpu.subgroup_mma_load_matrix %sw[%bo3_0f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + vx.subgroup_schedule_barrier + %ao0_0f = arith.addi %th512, %k0 : index + %ma0_0f = gpu.subgroup_mma_load_matrix %sx[%ao0_0f] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao1_0f = arith.addi %th512, %k256 : index + %ma1_0f = gpu.subgroup_mma_load_matrix %sx[%ao1_0f] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + vx.subgroup_schedule_barrier + %r0_0f = gpu.subgroup_mma_compute %ma0_0f, %mb0_0f, %a0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r1_0f = gpu.subgroup_mma_compute %ma0_0f, %mb1_0f, %a1 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r2_0f = gpu.subgroup_mma_compute %ma0_0f, %mb2_0f, %a2 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r3_0f = gpu.subgroup_mma_compute %ma0_0f, %mb3_0f, %a3 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r4_0f = gpu.subgroup_mma_compute %ma1_0f, %mb0_0f, %a4 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r5_0f = gpu.subgroup_mma_compute %ma1_0f, %mb1_0f, %a5 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r6_0f = gpu.subgroup_mma_compute %ma1_0f, %mb2_0f, %a6 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r7_0f = gpu.subgroup_mma_compute %ma1_0f, %mb3_0f, %a7 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + vx.subgroup_schedule_barrier + %bo0_8f = arith.addi %rh32, %k512 : index + %mb0_8f = gpu.subgroup_mma_load_matrix %sw[%bo0_8f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo1_8f = arith.addi %rh32, %k520 : index + %mb1_8f = gpu.subgroup_mma_load_matrix %sw[%bo1_8f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo2_8f = arith.addi %rh32, %k528 : index + %mb2_8f = gpu.subgroup_mma_load_matrix %sw[%bo2_8f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo3_8f = arith.addi %rh32, %k536 : index + %mb3_8f = gpu.subgroup_mma_load_matrix %sw[%bo3_8f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + vx.subgroup_schedule_barrier + %ao0_8f = arith.addi %th512, %k8 : index + %ma0_8f = gpu.subgroup_mma_load_matrix %sx[%ao0_8f] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao1_8f = arith.addi %th512, %k264 : index + %ma1_8f = gpu.subgroup_mma_load_matrix %sx[%ao1_8f] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + vx.subgroup_schedule_barrier + %r0_8f = gpu.subgroup_mma_compute %ma0_8f, %mb0_8f, %r0_0f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r1_8f = gpu.subgroup_mma_compute %ma0_8f, %mb1_8f, %r1_0f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r2_8f = gpu.subgroup_mma_compute %ma0_8f, %mb2_8f, %r2_0f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r3_8f = gpu.subgroup_mma_compute %ma0_8f, %mb3_8f, %r3_0f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r4_8f = gpu.subgroup_mma_compute %ma1_8f, %mb0_8f, %r4_0f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r5_8f = gpu.subgroup_mma_compute %ma1_8f, %mb1_8f, %r5_0f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r6_8f = gpu.subgroup_mma_compute %ma1_8f, %mb2_8f, %r6_0f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r7_8f = gpu.subgroup_mma_compute %ma1_8f, %mb3_8f, %r7_0f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + vx.subgroup_schedule_barrier + %bo0_16f = arith.addi %rh32, %k1024 : index + %mb0_16f = gpu.subgroup_mma_load_matrix %sw[%bo0_16f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo1_16f = arith.addi %rh32, %k1032 : index + %mb1_16f = gpu.subgroup_mma_load_matrix %sw[%bo1_16f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo2_16f = arith.addi %rh32, %k1040 : index + %mb2_16f = gpu.subgroup_mma_load_matrix %sw[%bo2_16f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo3_16f = arith.addi %rh32, %k1048 : index + %mb3_16f = gpu.subgroup_mma_load_matrix %sw[%bo3_16f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + vx.subgroup_schedule_barrier + %ao0_16f = arith.addi %th512, %k16 : index + %ma0_16f = gpu.subgroup_mma_load_matrix %sx[%ao0_16f] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao1_16f = arith.addi %th512, %k272 : index + %ma1_16f = gpu.subgroup_mma_load_matrix %sx[%ao1_16f] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + vx.subgroup_schedule_barrier + %r0_16f = gpu.subgroup_mma_compute %ma0_16f, %mb0_16f, %r0_8f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r1_16f = gpu.subgroup_mma_compute %ma0_16f, %mb1_16f, %r1_8f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r2_16f = gpu.subgroup_mma_compute %ma0_16f, %mb2_16f, %r2_8f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r3_16f = gpu.subgroup_mma_compute %ma0_16f, %mb3_16f, %r3_8f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r4_16f = gpu.subgroup_mma_compute %ma1_16f, %mb0_16f, %r4_8f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r5_16f = gpu.subgroup_mma_compute %ma1_16f, %mb1_16f, %r5_8f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r6_16f = gpu.subgroup_mma_compute %ma1_16f, %mb2_16f, %r6_8f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r7_16f = gpu.subgroup_mma_compute %ma1_16f, %mb3_16f, %r7_8f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + vx.subgroup_schedule_barrier + %bo0_24f = arith.addi %rh32, %k1536 : index + %mb0_24f = gpu.subgroup_mma_load_matrix %sw[%bo0_24f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo1_24f = arith.addi %rh32, %k1544 : index + %mb1_24f = gpu.subgroup_mma_load_matrix %sw[%bo1_24f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo2_24f = arith.addi %rh32, %k1552 : index + %mb2_24f = gpu.subgroup_mma_load_matrix %sw[%bo2_24f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo3_24f = arith.addi %rh32, %k1560 : index + %mb3_24f = gpu.subgroup_mma_load_matrix %sw[%bo3_24f] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + vx.subgroup_schedule_barrier + %ao0_24f = arith.addi %th512, %k24 : index + %ma0_24f = gpu.subgroup_mma_load_matrix %sx[%ao0_24f] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao1_24f = arith.addi %th512, %k280 : index + %ma1_24f = gpu.subgroup_mma_load_matrix %sx[%ao1_24f] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + vx.subgroup_schedule_barrier + %r0_24f = gpu.subgroup_mma_compute %ma0_24f, %mb0_24f, %r0_16f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r1_24f = gpu.subgroup_mma_compute %ma0_24f, %mb1_24f, %r1_16f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r2_24f = gpu.subgroup_mma_compute %ma0_24f, %mb2_24f, %r2_16f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r3_24f = gpu.subgroup_mma_compute %ma0_24f, %mb3_24f, %r3_16f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r4_24f = gpu.subgroup_mma_compute %ma1_24f, %mb0_24f, %r4_16f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r5_24f = gpu.subgroup_mma_compute %ma1_24f, %mb1_24f, %r5_16f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r6_24f = gpu.subgroup_mma_compute %ma1_24f, %mb2_24f, %r6_16f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r7_24f = gpu.subgroup_mma_compute %ma1_24f, %mb3_24f, %r7_16f : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + scf.yield %r0_24f, %r1_24f, %r2_24f, %r3_24f, %r4_24f, %r5_24f, %r6_24f, %r7_24f : !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp"> + } else { + %mh:8 = scf.if %busy0 -> (!gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">) { + vx.subgroup_schedule_barrier + %bo0_0h = arith.addi %rh32, %k0 : index + %mb0_0h = gpu.subgroup_mma_load_matrix %sw[%bo0_0h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo1_0h = arith.addi %rh32, %k8 : index + %mb1_0h = gpu.subgroup_mma_load_matrix %sw[%bo1_0h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo2_0h = arith.addi %rh32, %k16 : index + %mb2_0h = gpu.subgroup_mma_load_matrix %sw[%bo2_0h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo3_0h = arith.addi %rh32, %k24 : index + %mb3_0h = gpu.subgroup_mma_load_matrix %sw[%bo3_0h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + vx.subgroup_schedule_barrier + %ao0_0h = arith.addi %th512, %k0 : index + %ma0_0h = gpu.subgroup_mma_load_matrix %sx[%ao0_0h] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + vx.subgroup_schedule_barrier + %r0_0h = gpu.subgroup_mma_compute %ma0_0h, %mb0_0h, %a0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r1_0h = gpu.subgroup_mma_compute %ma0_0h, %mb1_0h, %a1 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r2_0h = gpu.subgroup_mma_compute %ma0_0h, %mb2_0h, %a2 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r3_0h = gpu.subgroup_mma_compute %ma0_0h, %mb3_0h, %a3 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + vx.subgroup_schedule_barrier + %bo0_8h = arith.addi %rh32, %k512 : index + %mb0_8h = gpu.subgroup_mma_load_matrix %sw[%bo0_8h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo1_8h = arith.addi %rh32, %k520 : index + %mb1_8h = gpu.subgroup_mma_load_matrix %sw[%bo1_8h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo2_8h = arith.addi %rh32, %k528 : index + %mb2_8h = gpu.subgroup_mma_load_matrix %sw[%bo2_8h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo3_8h = arith.addi %rh32, %k536 : index + %mb3_8h = gpu.subgroup_mma_load_matrix %sw[%bo3_8h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + vx.subgroup_schedule_barrier + %ao0_8h = arith.addi %th512, %k8 : index + %ma0_8h = gpu.subgroup_mma_load_matrix %sx[%ao0_8h] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + vx.subgroup_schedule_barrier + %r0_8h = gpu.subgroup_mma_compute %ma0_8h, %mb0_8h, %r0_0h : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r1_8h = gpu.subgroup_mma_compute %ma0_8h, %mb1_8h, %r1_0h : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r2_8h = gpu.subgroup_mma_compute %ma0_8h, %mb2_8h, %r2_0h : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r3_8h = gpu.subgroup_mma_compute %ma0_8h, %mb3_8h, %r3_0h : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + vx.subgroup_schedule_barrier + %bo0_16h = arith.addi %rh32, %k1024 : index + %mb0_16h = gpu.subgroup_mma_load_matrix %sw[%bo0_16h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo1_16h = arith.addi %rh32, %k1032 : index + %mb1_16h = gpu.subgroup_mma_load_matrix %sw[%bo1_16h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo2_16h = arith.addi %rh32, %k1040 : index + %mb2_16h = gpu.subgroup_mma_load_matrix %sw[%bo2_16h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo3_16h = arith.addi %rh32, %k1048 : index + %mb3_16h = gpu.subgroup_mma_load_matrix %sw[%bo3_16h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + vx.subgroup_schedule_barrier + %ao0_16h = arith.addi %th512, %k16 : index + %ma0_16h = gpu.subgroup_mma_load_matrix %sx[%ao0_16h] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + vx.subgroup_schedule_barrier + %r0_16h = gpu.subgroup_mma_compute %ma0_16h, %mb0_16h, %r0_8h : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r1_16h = gpu.subgroup_mma_compute %ma0_16h, %mb1_16h, %r1_8h : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r2_16h = gpu.subgroup_mma_compute %ma0_16h, %mb2_16h, %r2_8h : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r3_16h = gpu.subgroup_mma_compute %ma0_16h, %mb3_16h, %r3_8h : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + vx.subgroup_schedule_barrier + %bo0_24h = arith.addi %rh32, %k1536 : index + %mb0_24h = gpu.subgroup_mma_load_matrix %sw[%bo0_24h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo1_24h = arith.addi %rh32, %k1544 : index + %mb1_24h = gpu.subgroup_mma_load_matrix %sw[%bo1_24h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo2_24h = arith.addi %rh32, %k1552 : index + %mb2_24h = gpu.subgroup_mma_load_matrix %sw[%bo2_24h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo3_24h = arith.addi %rh32, %k1560 : index + %mb3_24h = gpu.subgroup_mma_load_matrix %sw[%bo3_24h] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + vx.subgroup_schedule_barrier + %ao0_24h = arith.addi %th512, %k24 : index + %ma0_24h = gpu.subgroup_mma_load_matrix %sx[%ao0_24h] {leadDimension = 32 : index} : memref<1024xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + vx.subgroup_schedule_barrier + %r0_24h = gpu.subgroup_mma_compute %ma0_24h, %mb0_24h, %r0_16h : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r1_24h = gpu.subgroup_mma_compute %ma0_24h, %mb1_24h, %r1_16h : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r2_24h = gpu.subgroup_mma_compute %ma0_24h, %mb2_24h, %r2_16h : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r3_24h = gpu.subgroup_mma_compute %ma0_24h, %mb3_24h, %r3_16h : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + scf.yield %r0_24h, %r1_24h, %r2_24h, %r3_24h, %a4, %a5, %a6, %a7 : !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp"> + } else { + scf.yield %a0, %a1, %a2, %a3, %a4, %a5, %a6, %a7 : !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp"> + } + scf.yield %mh#0, %mh#1, %mh#2, %mh#3, %mh#4, %mh#5, %mh#6, %mh#7 : !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp"> + } + scf.yield %mm#0, %mm#1, %mm#2, %mm#3, %mm#4, %mm#5, %mm#6, %mm#7 : !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp"> + } + %yr0 = arith.addi %tb32, %th16 : index + %yr1 = arith.addi %yr0, %k8 : index + %yc0 = arith.addi %rb64, %rh32 : index + %yc1 = arith.addi %yc0, %k8 : index + %yc2 = arith.addi %yc0, %k16 : index + %yc3 = arith.addi %yc0, %k24 : index + gpu.subgroup_mma_store_matrix %res#0, %y[%yr0, %yc0] {leadDimension = 0 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref + gpu.subgroup_mma_store_matrix %res#1, %y[%yr0, %yc1] {leadDimension = 0 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref + gpu.subgroup_mma_store_matrix %res#2, %y[%yr0, %yc2] {leadDimension = 0 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref + gpu.subgroup_mma_store_matrix %res#3, %y[%yr0, %yc3] {leadDimension = 0 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref + gpu.subgroup_mma_store_matrix %res#4, %y[%yr1, %yc0] {leadDimension = 0 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref + gpu.subgroup_mma_store_matrix %res#5, %y[%yr1, %yc1] {leadDimension = 0 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref + gpu.subgroup_mma_store_matrix %res#6, %y[%yr1, %yc2] {leadDimension = 0 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref + gpu.subgroup_mma_store_matrix %res#7, %y[%yr1, %yc3] {leadDimension = 0 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref + macro.yield %tb : i32 + }; + } + } + } + return; +} + /// The product of a Q4_0 matrix, in the format of `nn_matvec_q4`: a weight is (code - 8) times /// the f16 scale of its 32 columns. The weights go to shared memory as [column][row], and the /// inputs as [token][column], so that the lanes of a subgroup write consecutive words, and the @@ -1606,6 +2001,25 @@ fn pf_silu_mul(out : &mut Tensor, gu : &Tensor= 0: the positions of the experts with a token +/// (`e_ident`). The rows of padding are left as they are, and the down product reads none of them. +fn pf_silu_mul_live(out : &mut Tensor, gu : &Tensor, live : &Tensor, n : i32, rows : i32) -> void { + spawn on(Topology::Device) { + for r in 0..n across blocks { + for b in 0..(rows + 255) / 256 across blocks { + for l in 0..256 across lanes { + let i = b * 256 + l; + if i < rows && live[r] >= 0 { + let g = gu[r][i]; + out[r][i] = g / (1.0 + (0.0 - g).fast_exp()) * gu[r][rows + i]; + } + } + } + } + } + return; +} + /// The experts of each token of the chunk, as `nn_top_k` does for one token. fn pf_top_k(ids : &mut Tensor, weights : &mut Tensor, logits : &Tensor, n_tokens : i32, n : i32, k : i32) -> void { assert(n > 0 && n <= 256 && k > 0 && k <= n, "pf_top_k: n must be 1 to 256, and k must be 1 to n"); @@ -1823,7 +2237,7 @@ fn pf_experts(p : &mut Prefill, layer : &Layer, c : &Config, n : i32, tiles : i3 pf_top_k(&mut p.ids, &mut p.wts, &p.router, n, c.num_experts, k); let e_tiles = pf_sort_by_expert(p, n, k, c.num_experts); pf_mm(&mut p.e_gu, &layer.gate_up, &p.xn, &p.e_rows, &p.e_bases, 2 * inter, &p.no_bias, false, false, 2 * inter, c.hidden_size, e_tiles); - pf_silu_mul(&mut p.e_h, &p.e_gu, e_tiles * 16, inter); + pf_silu_mul_live(&mut p.e_h, &p.e_gu, &p.e_ident, e_tiles * 16, inter); pf_mm(&mut p.e_out, &layer.down, &p.e_h, &p.e_ident, &p.e_bases, c.hidden_size, &p.no_bias, false, false, c.hidden_size, inter, e_tiles); pf_combine(&mut p.x, &p.e_out, &p.wts, &p.slot, n, k, c.hidden_size); return; diff --git a/src/prefill35.vx b/src/prefill35.vx index d1fd979..47d70bd 100644 --- a/src/prefill35.vx +++ b/src/prefill35.vx @@ -29,7 +29,7 @@ import qwen::weights; /// The tensors of a chunk, made once. `rows`, `zeros` and the `e_` tensors are those of `Prefill`. /// `proj` is the output of `qkv` or `linear_in` for each token, and `y` the input of `attn_out` or /// `linear_out`. The `d` tensors are those of the DeltaNet, and the `s_` tensors those of the shared -/// expert. `router` has the logits of the experts, then that of the gate of the shared expert. +/// expert. `router` has the logits of the experts, then that of the gate of the shared expert, and zeros to a whole number of blocks of 64. struct Prefill35 { chunk : i32, tokens : Tensor, @@ -96,7 +96,7 @@ fn new_prefill35(c : &Config, chunk : i32) -> Prefill35 { beta: transfer(Tensor([chunk, vh]), Memory::HBM), decay: transfer(Tensor([chunk, vh]), Memory::HBM), o: transfer(Tensor([chunk, vh, 16, 8]), Memory::HBM), - router: transfer(Tensor([cap, experts + 1]), Memory::HBM), + router: transfer(Tensor([cap, (experts + 1 + 63) / 64 * 64]), Memory::HBM), ids: transfer(Tensor([chunk, k]), Memory::HBM), wts: transfer(Tensor([chunk, k]), Memory::HBM), e_rows: transfer(Tensor([positions]), Memory::HBM), @@ -989,7 +989,13 @@ fn pf35_experts(p : &mut Prefill35, layer : &Qwen35Layer, c : &Config, n : i32, let experts = c.num_experts; let inter = c.moe_intermediate_size; let shared = c.shared_expert_inter; - pf_mm_bf16(&mut p.router, &layer.router, &p.xn, &p.rows, &p.zeros, 0, &p.no_bias, false, false, experts + 1, c.hidden_size, tiles); + // With Q4_0 experts, whose products round to f16, the router rounds to f16 too, in the faster + // kernel. A bf16 file keeps the f32 products. + if layer.gate_up.dtype == U4 { + pf_mm_bf16_mlir(&mut p.router, &layer.router, &p.xn, &p.rows, &p.zeros, 0, experts + 1, c.hidden_size, tiles); + } else { + pf_mm_bf16(&mut p.router, &layer.router, &p.xn, &p.rows, &p.zeros, 0, &p.no_bias, false, false, experts + 1, c.hidden_size, tiles); + } pf_top_k(&mut p.ids, &mut p.wts, &p.router, n, experts, k); let e_tiles = p.e_rows.len() / 16; pf_count_experts(&mut p.e_counts, &mut p.e_lane_counts, &p.ids, n, k, experts); @@ -997,7 +1003,7 @@ fn pf35_experts(p : &mut Prefill35, layer : &Qwen35Layer, c : &Config, n : i32, pf_expert_bases(&mut p.e_bases, &p.e_counts, experts, e_tiles); pf_live_positions(&mut p.e_ident, &p.e_rows); pf_mm(&mut p.e_gu, &layer.gate_up, &p.xn, &p.e_rows, &p.e_bases, 2 * inter, &p.no_bias, false, false, 2 * inter, c.hidden_size, e_tiles); - pf_silu_mul(&mut p.e_h, &p.e_gu, e_tiles * 16, inter); + pf_silu_mul_live(&mut p.e_h, &p.e_gu, &p.e_ident, e_tiles * 16, inter); pf_mm(&mut p.e_out, &layer.down, &p.e_h, &p.e_ident, &p.e_bases, c.hidden_size, &p.no_bias, false, false, c.hidden_size, inter, e_tiles); pf_combine(&mut p.x, &p.e_out, &p.wts, &p.slot, n, k, c.hidden_size); pf_mm(&mut p.s_gu, &layer.shared_gate_up, &p.xn, &p.rows, &p.zeros, 0, &p.no_bias, false, false, 2 * shared, c.hidden_size, tiles); From 3d56b14c661a859ee63e0e0c682163f0b09da976 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:07:37 -0800 Subject: [PATCH 23/60] Prefill of Qwen3.6: dense Q4_0 products in blocks of 64 tokens (#89) expert_product.py --t64 prints pf_mm_q4_mlir64: pf_mm_q4_mlir with blocks of 64 tokens x 64 rows, so each weight that a block decodes serves 64 tokens in place of 32. Each SIMD group makes 32 tokens x 32 rows, with 16 sums. It does not skip padding, so it is for the dense products: the new pf35_mm uses it for the Q4_0 matrices of whole blocks of 64 rows (qkv, attn_out, linear_in, linear_out and the shared expert). new_prefill35 makes the tensors of the chunk for whole blocks of 64 tokens. The sums go in the same order, so the logits stay the same: a 48-step code-edit prompt gives the same tokens and logits as before. Informal, -O2, the real model, interleaved: linear_in 251 ms in place of 270; a prompt of 512 tokens about 1,148 ms in place of 1,180. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- scripts/mlir_kernels/expert_product.py | 122 ++++---- src/prefill.vx | 389 +++++++++++++++++++++++++ src/prefill35.vx | 26 +- 3 files changed, 480 insertions(+), 57 deletions(-) diff --git a/scripts/mlir_kernels/expert_product.py b/scripts/mlir_kernels/expert_product.py index f21a5a1..fb98530 100755 --- a/scripts/mlir_kernels/expert_product.py +++ b/scripts/mlir_kernels/expert_product.py @@ -15,6 +15,11 @@ 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">' @@ -24,14 +29,17 @@ name = 'pf_mm_q4_mlir' if mode == 'app' else ('mm_mlir2h' if hint else 'mm_mlir2') 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 + 63) / 64 across blocks {' if bf16 else ' 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(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, %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 * 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): @@ -51,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') @@ -91,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>') @@ -108,20 +123,21 @@ 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('%th16 = arith.muli %th, %k16 : index') +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] # 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. -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(8)) -accty = ', '.join([ACC] * 8) -b(f'%res:8 = scf.for %g = %k0 to %Gl step %k1 iter_args({accs}) -> ({accty}) {{') +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) if bf16: # Lane l loads columns kh * 16 to + 15 of its row, as 4 vectors of 4. @@ -156,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) @@ -172,13 +189,14 @@ 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') 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 8 sums; those of the other rows go through as they are.""" - prev = [f'%a{i}' for i in range(8)] + 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') @@ -189,7 +207,7 @@ def mma(d, tag, rows): 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}} : memref<1024xf16, 3> -> {AOP}') + 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) @@ -200,27 +218,31 @@ def mma(d, tag, rows): cur[n] = f'%r{n}_{k8}{tag}' prev = cur d('scf.yield ' + ', '.join(prev) + ' : ' + accty) -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) +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('%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/src/prefill.vx b/src/prefill.vx index 6da4b56..2002312 100644 --- a/src/prefill.vx +++ b/src/prefill.vx @@ -802,6 +802,395 @@ fn pf_mm_q4_mlir(y : &mut Tensor, w : &Tensor, w : &Tensor, scales : &Tensor, x : &Tensor, list : &Tensor, bases : &Tensor, stride : i32, rows : i32, cols : i32, tiles : i32) -> void { + spawn on(Topology::Device) { + for rb in 0..rows / 64 across blocks { + for tb in 0..(tiles + 3) / 4 across blocks { + let mut sw = unsafe { Tensor::uninit() }; + let mut sx = unsafe { Tensor::uninit() }; + let _d = mlir!( threads : 128, inputs : (%sw = &mut sw : memref<2048xf16, 3>, %sx = &mut sx : memref<2048xf16, 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"], 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 * 64..tb * 64 + 64][rb * 64..rb * 64 + 64])]) { + %k0 = arith.constant 0 : index + %k1 = arith.constant 1 : index + %k2 = arith.constant 2 : index + %k4 = arith.constant 4 : index + %k8 = arith.constant 8 : index + %k16 = arith.constant 16 : index + %k24 = arith.constant 24 : index + %k32 = arith.constant 32 : index + %k64 = arith.constant 64 : index + %k128 = arith.constant 128 : index + %k192 = arith.constant 192 : index + %k256 = arith.constant 256 : index + %k264 = arith.constant 264 : index + %k272 = arith.constant 272 : index + %k280 = arith.constant 280 : index + %k320 = arith.constant 320 : index + %k384 = arith.constant 384 : index + %k448 = arith.constant 448 : index + %k512 = arith.constant 512 : index + %k520 = arith.constant 520 : index + %k528 = arith.constant 528 : index + %k536 = arith.constant 536 : index + %k576 = arith.constant 576 : index + %k640 = arith.constant 640 : index + %k704 = arith.constant 704 : index + %k768 = arith.constant 768 : index + %k776 = arith.constant 776 : index + %k784 = arith.constant 784 : index + %k792 = arith.constant 792 : index + %k832 = arith.constant 832 : index + %k896 = arith.constant 896 : index + %k960 = arith.constant 960 : index + %k1024 = arith.constant 1024 : index + %k1032 = arith.constant 1032 : index + %k1040 = arith.constant 1040 : index + %k1048 = arith.constant 1048 : index + %k1536 = arith.constant 1536 : index + %k1544 = arith.constant 1544 : index + %k1552 = arith.constant 1552 : index + %k1560 = arith.constant 1560 : index + %tid = gpu.thread_id x + %sg = arith.divui %tid, %k32 : index + %l = arith.remui %tid, %k32 : index + %th = arith.divui %sg, %k2 : index + %rh = arith.remui %sg, %k2 : index + %rbi = arith.index_cast %rb : i32 to index + %tbi = arith.index_cast %tb : i32 to index + %stridei = arith.index_cast %stride : i32 to index + %colsi = arith.index_cast %cols : i32 to index + %G = arith.divui %colsi, %k32 : index + %WPR = arith.divui %colsi, %k8 : index + %tbb = arith.muli %tbi, %k4 : index + %base32 = memref.load %bases[%tbb] : memref + %zi = arith.constant 0 : i32 + %bok = arith.cmpi sge, %base32, %zi : i32 + %basec = arith.maxsi %base32, %zi : i32 + %base = arith.index_cast %basec : i32 to index + %Gl = arith.select %bok, %G, %k0 : index + %sg16 = arith.muli %sg, %k16 : index + %l2 = arith.divui %l, %k2 : index + %kh = arith.remui %l, %k2 : index + %rl = arith.addi %sg16, %l2 : index + %rb64 = arith.muli %rbi, %k64 : index + %r = arith.addi %rb64, %rl : index + %bs = arith.muli %base, %stridei : index + %row = arith.addi %bs, %r : index + %rw = arith.muli %row, %WPR : index + %kh2 = arith.muli %kh, %k2 : index + %wbase = arith.addi %rw, %kh2 : index + %sbase = arith.muli %row, %G : index + %kh1024 = arith.muli %kh, %k1024 : index + %swd = arith.addi %kh1024, %rl : index + %sg8 = arith.muli %sg, %k8 : index + %l4 = arith.divui %l, %k4 : index + %lm4 = arith.remui %l, %k4 : index + %tl = arith.addi %sg8, %l4 : index + %cl = arith.muli %lm4, %k8 : index + %tb32 = arith.muli %tbi, %k64 : index + %li = arith.addi %tb32, %tl : index + %from32 = memref.load %list[%li] : memref + %live = arith.cmpi sge, %from32, %zi : i32 + %fromc = arith.maxsi %from32, %zi : i32 + %from = arith.index_cast %fromc : i32 to index + %tl32 = arith.muli %tl, %k32 : index + %sxd = arith.addi %tl32, %cl : index + %sxd4 = arith.addi %sxd, %k4 : index + %tl_1 = arith.addi %tl, %k32 : index + %li_1 = arith.addi %tb32, %tl_1 : index + %from32_1 = memref.load %list[%li_1] : memref + %live_1 = arith.cmpi sge, %from32_1, %zi : i32 + %fromc_1 = arith.maxsi %from32_1, %zi : i32 + %from_1 = arith.index_cast %fromc_1 : i32 to index + %tl32_1 = arith.muli %tl_1, %k32 : index + %sxd_1 = arith.addi %tl32_1, %cl : index + %sxd4_1 = arith.addi %sxd_1, %k4 : index + %shl = arith.constant dense<[0, 4, 8, 12]> : vector<4xi32> + %shh = arith.constant dense<[16, 20, 24, 28]> : vector<4xi32> + %m15 = arith.constant dense<15> : vector<4xi32> + %vz = arith.constant dense<0.0> : vector<4xf32> + %m8 = arith.constant -8.0 : f16 + %zf = arith.constant 0.0 : f32 + %z = gpu.subgroup_mma_constant_matrix %zf : !gpu.mma_matrix<8x8xf32, "COp"> + %th512 = arith.muli %th, %k1024 : index + %th16 = arith.muli %th, %k32 : index + %rh32 = arith.muli %rh, %k32 : index + %res:16 = scf.for %g = %k0 to %Gl step %k1 iter_args(%a0 = %z, %a1 = %z, %a2 = %z, %a3 = %z, %a4 = %z, %a5 = %z, %a6 = %z, %a7 = %z, %a8 = %z, %a9 = %z, %a10 = %z, %a11 = %z, %a12 = %z, %a13 = %z, %a14 = %z, %a15 = %z) -> (!gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">) { + %g4 = arith.muli %g, %k4 : index + %wa = arith.addi %wbase, %g4 : index + %q = vector.load %w[%wa] {alignment = 8} : memref, vector<2xi32> + %sa = arith.addi %sbase, %g : index + %s = memref.load %sc[%sa] : memref + %m = arith.mulf %s, %m8 : f16 + %sv = vector.broadcast %s : f16 to vector<4xf16> + %mv = vector.broadcast %m : f16 to vector<4xf16> + %q0 = vector.extract %q[0] : i32 from vector<2xi32> + %qb0 = vector.broadcast %q0 : i32 to vector<4xi32> + %s00 = arith.shrui %qb0, %shl : vector<4xi32> + %n00 = arith.andi %s00, %m15 : vector<4xi32> + %f00 = arith.uitofp %n00 : vector<4xi32> to vector<4xf16> + %d00 = vector.fma %f00, %sv, %mv : vector<4xf16> + %s01 = arith.shrui %qb0, %shh : vector<4xi32> + %n01 = arith.andi %s01, %m15 : vector<4xi32> + %f01 = arith.uitofp %n01 : vector<4xi32> to vector<4xf16> + %d01 = vector.fma %f01, %sv, %mv : vector<4xf16> + %q1 = vector.extract %q[1] : i32 from vector<2xi32> + %qb1 = vector.broadcast %q1 : i32 to vector<4xi32> + %s10 = arith.shrui %qb1, %shl : vector<4xi32> + %n10 = arith.andi %s10, %m15 : vector<4xi32> + %f10 = arith.uitofp %n10 : vector<4xi32> to vector<4xf16> + %d10 = vector.fma %f10, %sv, %mv : vector<4xf16> + %s11 = arith.shrui %qb1, %shh : vector<4xi32> + %n11 = arith.andi %s11, %m15 : vector<4xi32> + %f11 = arith.uitofp %n11 : vector<4xi32> to vector<4xf16> + %d11 = vector.fma %f11, %sv, %mv : vector<4xf16> + %g32 = arith.muli %g, %k32 : index + %xc = arith.addi %g32, %cl : index + %xc4 = arith.addi %xc, %k4 : index + %x0r = vector.load %x[%from, %xc] {alignment = 16} : memref, vector<4xf32> + %x1r = vector.load %x[%from, %xc4] {alignment = 16} : memref, vector<4xf32> + %x0 = arith.select %live, %x0r, %vz : vector<4xf32> + %x1 = arith.select %live, %x1r, %vz : vector<4xf32> + %h0 = arith.truncf %x0 : vector<4xf32> to vector<4xf16> + %h1 = arith.truncf %x1 : vector<4xf32> to vector<4xf16> + %x0r_1 = vector.load %x[%from_1, %xc] {alignment = 16} : memref, vector<4xf32> + %x1r_1 = vector.load %x[%from_1, %xc4] {alignment = 16} : memref, vector<4xf32> + %x0_1 = arith.select %live_1, %x0r_1, %vz : vector<4xf32> + %x1_1 = arith.select %live_1, %x1r_1, %vz : vector<4xf32> + %h0_1 = arith.truncf %x0_1 : vector<4xf32> to vector<4xf16> + %h1_1 = arith.truncf %x1_1 : vector<4xf32> to vector<4xf16> + gpu.barrier + %e0 = vector.extract %d00[0] : f16 from vector<4xf16> + memref.store %e0, %sw[%swd] : memref<2048xf16, 3> + %e1 = vector.extract %d00[1] : f16 from vector<4xf16> + %o1 = arith.addi %swd, %k64 : index + memref.store %e1, %sw[%o1] : memref<2048xf16, 3> + %e2 = vector.extract %d00[2] : f16 from vector<4xf16> + %o2 = arith.addi %swd, %k128 : index + memref.store %e2, %sw[%o2] : memref<2048xf16, 3> + %e3 = vector.extract %d00[3] : f16 from vector<4xf16> + %o3 = arith.addi %swd, %k192 : index + memref.store %e3, %sw[%o3] : memref<2048xf16, 3> + %e4 = vector.extract %d01[0] : f16 from vector<4xf16> + %o4 = arith.addi %swd, %k256 : index + memref.store %e4, %sw[%o4] : memref<2048xf16, 3> + %e5 = vector.extract %d01[1] : f16 from vector<4xf16> + %o5 = arith.addi %swd, %k320 : index + memref.store %e5, %sw[%o5] : memref<2048xf16, 3> + %e6 = vector.extract %d01[2] : f16 from vector<4xf16> + %o6 = arith.addi %swd, %k384 : index + memref.store %e6, %sw[%o6] : memref<2048xf16, 3> + %e7 = vector.extract %d01[3] : f16 from vector<4xf16> + %o7 = arith.addi %swd, %k448 : index + memref.store %e7, %sw[%o7] : memref<2048xf16, 3> + %e8 = vector.extract %d10[0] : f16 from vector<4xf16> + %o8 = arith.addi %swd, %k512 : index + memref.store %e8, %sw[%o8] : memref<2048xf16, 3> + %e9 = vector.extract %d10[1] : f16 from vector<4xf16> + %o9 = arith.addi %swd, %k576 : index + memref.store %e9, %sw[%o9] : memref<2048xf16, 3> + %e10 = vector.extract %d10[2] : f16 from vector<4xf16> + %o10 = arith.addi %swd, %k640 : index + memref.store %e10, %sw[%o10] : memref<2048xf16, 3> + %e11 = vector.extract %d10[3] : f16 from vector<4xf16> + %o11 = arith.addi %swd, %k704 : index + memref.store %e11, %sw[%o11] : memref<2048xf16, 3> + %e12 = vector.extract %d11[0] : f16 from vector<4xf16> + %o12 = arith.addi %swd, %k768 : index + memref.store %e12, %sw[%o12] : memref<2048xf16, 3> + %e13 = vector.extract %d11[1] : f16 from vector<4xf16> + %o13 = arith.addi %swd, %k832 : index + memref.store %e13, %sw[%o13] : memref<2048xf16, 3> + %e14 = vector.extract %d11[2] : f16 from vector<4xf16> + %o14 = arith.addi %swd, %k896 : index + memref.store %e14, %sw[%o14] : memref<2048xf16, 3> + %e15 = vector.extract %d11[3] : f16 from vector<4xf16> + %o15 = arith.addi %swd, %k960 : index + memref.store %e15, %sw[%o15] : memref<2048xf16, 3> + vector.store %h0, %sx[%sxd] {alignment = 8} : memref<2048xf16, 3>, vector<4xf16> + vector.store %h1, %sx[%sxd4] {alignment = 8} : memref<2048xf16, 3>, vector<4xf16> + vector.store %h0_1, %sx[%sxd_1] {alignment = 8} : memref<2048xf16, 3>, vector<4xf16> + vector.store %h1_1, %sx[%sxd4_1] {alignment = 8} : memref<2048xf16, 3>, vector<4xf16> + gpu.barrier + vx.subgroup_schedule_barrier + %bo0_0 = arith.addi %rh32, %k0 : index + %mb0_0 = gpu.subgroup_mma_load_matrix %sw[%bo0_0] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo1_0 = arith.addi %rh32, %k8 : index + %mb1_0 = gpu.subgroup_mma_load_matrix %sw[%bo1_0] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo2_0 = arith.addi %rh32, %k16 : index + %mb2_0 = gpu.subgroup_mma_load_matrix %sw[%bo2_0] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo3_0 = arith.addi %rh32, %k24 : index + %mb3_0 = gpu.subgroup_mma_load_matrix %sw[%bo3_0] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + vx.subgroup_schedule_barrier + %ao0_0 = arith.addi %th512, %k0 : index + %ma0_0 = gpu.subgroup_mma_load_matrix %sx[%ao0_0] {leadDimension = 32 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao1_0 = arith.addi %th512, %k256 : index + %ma1_0 = gpu.subgroup_mma_load_matrix %sx[%ao1_0] {leadDimension = 32 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao2_0 = arith.addi %th512, %k512 : index + %ma2_0 = gpu.subgroup_mma_load_matrix %sx[%ao2_0] {leadDimension = 32 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao3_0 = arith.addi %th512, %k768 : index + %ma3_0 = gpu.subgroup_mma_load_matrix %sx[%ao3_0] {leadDimension = 32 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + vx.subgroup_schedule_barrier + %r0_0 = gpu.subgroup_mma_compute %ma0_0, %mb0_0, %a0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r1_0 = gpu.subgroup_mma_compute %ma0_0, %mb1_0, %a1 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r2_0 = gpu.subgroup_mma_compute %ma0_0, %mb2_0, %a2 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r3_0 = gpu.subgroup_mma_compute %ma0_0, %mb3_0, %a3 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r4_0 = gpu.subgroup_mma_compute %ma1_0, %mb0_0, %a4 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r5_0 = gpu.subgroup_mma_compute %ma1_0, %mb1_0, %a5 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r6_0 = gpu.subgroup_mma_compute %ma1_0, %mb2_0, %a6 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r7_0 = gpu.subgroup_mma_compute %ma1_0, %mb3_0, %a7 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r8_0 = gpu.subgroup_mma_compute %ma2_0, %mb0_0, %a8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r9_0 = gpu.subgroup_mma_compute %ma2_0, %mb1_0, %a9 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r10_0 = gpu.subgroup_mma_compute %ma2_0, %mb2_0, %a10 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r11_0 = gpu.subgroup_mma_compute %ma2_0, %mb3_0, %a11 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r12_0 = gpu.subgroup_mma_compute %ma3_0, %mb0_0, %a12 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r13_0 = gpu.subgroup_mma_compute %ma3_0, %mb1_0, %a13 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r14_0 = gpu.subgroup_mma_compute %ma3_0, %mb2_0, %a14 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r15_0 = gpu.subgroup_mma_compute %ma3_0, %mb3_0, %a15 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + vx.subgroup_schedule_barrier + %bo0_8 = arith.addi %rh32, %k512 : index + %mb0_8 = gpu.subgroup_mma_load_matrix %sw[%bo0_8] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo1_8 = arith.addi %rh32, %k520 : index + %mb1_8 = gpu.subgroup_mma_load_matrix %sw[%bo1_8] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo2_8 = arith.addi %rh32, %k528 : index + %mb2_8 = gpu.subgroup_mma_load_matrix %sw[%bo2_8] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo3_8 = arith.addi %rh32, %k536 : index + %mb3_8 = gpu.subgroup_mma_load_matrix %sw[%bo3_8] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + vx.subgroup_schedule_barrier + %ao0_8 = arith.addi %th512, %k8 : index + %ma0_8 = gpu.subgroup_mma_load_matrix %sx[%ao0_8] {leadDimension = 32 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao1_8 = arith.addi %th512, %k264 : index + %ma1_8 = gpu.subgroup_mma_load_matrix %sx[%ao1_8] {leadDimension = 32 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao2_8 = arith.addi %th512, %k520 : index + %ma2_8 = gpu.subgroup_mma_load_matrix %sx[%ao2_8] {leadDimension = 32 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao3_8 = arith.addi %th512, %k776 : index + %ma3_8 = gpu.subgroup_mma_load_matrix %sx[%ao3_8] {leadDimension = 32 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + vx.subgroup_schedule_barrier + %r0_8 = gpu.subgroup_mma_compute %ma0_8, %mb0_8, %r0_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r1_8 = gpu.subgroup_mma_compute %ma0_8, %mb1_8, %r1_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r2_8 = gpu.subgroup_mma_compute %ma0_8, %mb2_8, %r2_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r3_8 = gpu.subgroup_mma_compute %ma0_8, %mb3_8, %r3_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r4_8 = gpu.subgroup_mma_compute %ma1_8, %mb0_8, %r4_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r5_8 = gpu.subgroup_mma_compute %ma1_8, %mb1_8, %r5_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r6_8 = gpu.subgroup_mma_compute %ma1_8, %mb2_8, %r6_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r7_8 = gpu.subgroup_mma_compute %ma1_8, %mb3_8, %r7_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r8_8 = gpu.subgroup_mma_compute %ma2_8, %mb0_8, %r8_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r9_8 = gpu.subgroup_mma_compute %ma2_8, %mb1_8, %r9_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r10_8 = gpu.subgroup_mma_compute %ma2_8, %mb2_8, %r10_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r11_8 = gpu.subgroup_mma_compute %ma2_8, %mb3_8, %r11_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r12_8 = gpu.subgroup_mma_compute %ma3_8, %mb0_8, %r12_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r13_8 = gpu.subgroup_mma_compute %ma3_8, %mb1_8, %r13_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r14_8 = gpu.subgroup_mma_compute %ma3_8, %mb2_8, %r14_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r15_8 = gpu.subgroup_mma_compute %ma3_8, %mb3_8, %r15_0 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + vx.subgroup_schedule_barrier + %bo0_16 = arith.addi %rh32, %k1024 : index + %mb0_16 = gpu.subgroup_mma_load_matrix %sw[%bo0_16] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo1_16 = arith.addi %rh32, %k1032 : index + %mb1_16 = gpu.subgroup_mma_load_matrix %sw[%bo1_16] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo2_16 = arith.addi %rh32, %k1040 : index + %mb2_16 = gpu.subgroup_mma_load_matrix %sw[%bo2_16] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo3_16 = arith.addi %rh32, %k1048 : index + %mb3_16 = gpu.subgroup_mma_load_matrix %sw[%bo3_16] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + vx.subgroup_schedule_barrier + %ao0_16 = arith.addi %th512, %k16 : index + %ma0_16 = gpu.subgroup_mma_load_matrix %sx[%ao0_16] {leadDimension = 32 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao1_16 = arith.addi %th512, %k272 : index + %ma1_16 = gpu.subgroup_mma_load_matrix %sx[%ao1_16] {leadDimension = 32 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao2_16 = arith.addi %th512, %k528 : index + %ma2_16 = gpu.subgroup_mma_load_matrix %sx[%ao2_16] {leadDimension = 32 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao3_16 = arith.addi %th512, %k784 : index + %ma3_16 = gpu.subgroup_mma_load_matrix %sx[%ao3_16] {leadDimension = 32 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + vx.subgroup_schedule_barrier + %r0_16 = gpu.subgroup_mma_compute %ma0_16, %mb0_16, %r0_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r1_16 = gpu.subgroup_mma_compute %ma0_16, %mb1_16, %r1_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r2_16 = gpu.subgroup_mma_compute %ma0_16, %mb2_16, %r2_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r3_16 = gpu.subgroup_mma_compute %ma0_16, %mb3_16, %r3_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r4_16 = gpu.subgroup_mma_compute %ma1_16, %mb0_16, %r4_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r5_16 = gpu.subgroup_mma_compute %ma1_16, %mb1_16, %r5_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r6_16 = gpu.subgroup_mma_compute %ma1_16, %mb2_16, %r6_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r7_16 = gpu.subgroup_mma_compute %ma1_16, %mb3_16, %r7_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r8_16 = gpu.subgroup_mma_compute %ma2_16, %mb0_16, %r8_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r9_16 = gpu.subgroup_mma_compute %ma2_16, %mb1_16, %r9_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r10_16 = gpu.subgroup_mma_compute %ma2_16, %mb2_16, %r10_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r11_16 = gpu.subgroup_mma_compute %ma2_16, %mb3_16, %r11_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r12_16 = gpu.subgroup_mma_compute %ma3_16, %mb0_16, %r12_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r13_16 = gpu.subgroup_mma_compute %ma3_16, %mb1_16, %r13_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r14_16 = gpu.subgroup_mma_compute %ma3_16, %mb2_16, %r14_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r15_16 = gpu.subgroup_mma_compute %ma3_16, %mb3_16, %r15_8 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + vx.subgroup_schedule_barrier + %bo0_24 = arith.addi %rh32, %k1536 : index + %mb0_24 = gpu.subgroup_mma_load_matrix %sw[%bo0_24] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo1_24 = arith.addi %rh32, %k1544 : index + %mb1_24 = gpu.subgroup_mma_load_matrix %sw[%bo1_24] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo2_24 = arith.addi %rh32, %k1552 : index + %mb2_24 = gpu.subgroup_mma_load_matrix %sw[%bo2_24] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + %bo3_24 = arith.addi %rh32, %k1560 : index + %mb3_24 = gpu.subgroup_mma_load_matrix %sw[%bo3_24] {leadDimension = 64 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "BOp"> + vx.subgroup_schedule_barrier + %ao0_24 = arith.addi %th512, %k24 : index + %ma0_24 = gpu.subgroup_mma_load_matrix %sx[%ao0_24] {leadDimension = 32 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao1_24 = arith.addi %th512, %k280 : index + %ma1_24 = gpu.subgroup_mma_load_matrix %sx[%ao1_24] {leadDimension = 32 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao2_24 = arith.addi %th512, %k536 : index + %ma2_24 = gpu.subgroup_mma_load_matrix %sx[%ao2_24] {leadDimension = 32 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + %ao3_24 = arith.addi %th512, %k792 : index + %ma3_24 = gpu.subgroup_mma_load_matrix %sx[%ao3_24] {leadDimension = 32 : index} : memref<2048xf16, 3> -> !gpu.mma_matrix<8x8xf16, "AOp"> + vx.subgroup_schedule_barrier + %r0_24 = gpu.subgroup_mma_compute %ma0_24, %mb0_24, %r0_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r1_24 = gpu.subgroup_mma_compute %ma0_24, %mb1_24, %r1_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r2_24 = gpu.subgroup_mma_compute %ma0_24, %mb2_24, %r2_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r3_24 = gpu.subgroup_mma_compute %ma0_24, %mb3_24, %r3_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r4_24 = gpu.subgroup_mma_compute %ma1_24, %mb0_24, %r4_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r5_24 = gpu.subgroup_mma_compute %ma1_24, %mb1_24, %r5_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r6_24 = gpu.subgroup_mma_compute %ma1_24, %mb2_24, %r6_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r7_24 = gpu.subgroup_mma_compute %ma1_24, %mb3_24, %r7_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r8_24 = gpu.subgroup_mma_compute %ma2_24, %mb0_24, %r8_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r9_24 = gpu.subgroup_mma_compute %ma2_24, %mb1_24, %r9_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r10_24 = gpu.subgroup_mma_compute %ma2_24, %mb2_24, %r10_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r11_24 = gpu.subgroup_mma_compute %ma2_24, %mb3_24, %r11_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r12_24 = gpu.subgroup_mma_compute %ma3_24, %mb0_24, %r12_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r13_24 = gpu.subgroup_mma_compute %ma3_24, %mb1_24, %r13_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r14_24 = gpu.subgroup_mma_compute %ma3_24, %mb2_24, %r14_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + %r15_24 = gpu.subgroup_mma_compute %ma3_24, %mb3_24, %r15_16 : !gpu.mma_matrix<8x8xf16, "AOp">, !gpu.mma_matrix<8x8xf16, "BOp"> -> !gpu.mma_matrix<8x8xf32, "COp"> + scf.yield %r0_24, %r1_24, %r2_24, %r3_24, %r4_24, %r5_24, %r6_24, %r7_24, %r8_24, %r9_24, %r10_24, %r11_24, %r12_24, %r13_24, %r14_24, %r15_24 : !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp">, !gpu.mma_matrix<8x8xf32, "COp"> + } + %yr0 = arith.addi %tb32, %th16 : index + %yr1 = arith.addi %yr0, %k8 : index + %yr2 = arith.addi %yr0, %k16 : index + %yr3 = arith.addi %yr0, %k24 : index + %yc0 = arith.addi %rb64, %rh32 : index + %yc1 = arith.addi %yc0, %k8 : index + %yc2 = arith.addi %yc0, %k16 : index + %yc3 = arith.addi %yc0, %k24 : index + gpu.subgroup_mma_store_matrix %res#0, %y[%yr0, %yc0] {leadDimension = 0 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref + gpu.subgroup_mma_store_matrix %res#1, %y[%yr0, %yc1] {leadDimension = 0 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref + gpu.subgroup_mma_store_matrix %res#2, %y[%yr0, %yc2] {leadDimension = 0 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref + gpu.subgroup_mma_store_matrix %res#3, %y[%yr0, %yc3] {leadDimension = 0 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref + gpu.subgroup_mma_store_matrix %res#4, %y[%yr1, %yc0] {leadDimension = 0 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref + gpu.subgroup_mma_store_matrix %res#5, %y[%yr1, %yc1] {leadDimension = 0 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref + gpu.subgroup_mma_store_matrix %res#6, %y[%yr1, %yc2] {leadDimension = 0 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref + gpu.subgroup_mma_store_matrix %res#7, %y[%yr1, %yc3] {leadDimension = 0 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref + gpu.subgroup_mma_store_matrix %res#8, %y[%yr2, %yc0] {leadDimension = 0 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref + gpu.subgroup_mma_store_matrix %res#9, %y[%yr2, %yc1] {leadDimension = 0 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref + gpu.subgroup_mma_store_matrix %res#10, %y[%yr2, %yc2] {leadDimension = 0 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref + gpu.subgroup_mma_store_matrix %res#11, %y[%yr2, %yc3] {leadDimension = 0 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref + gpu.subgroup_mma_store_matrix %res#12, %y[%yr3, %yc0] {leadDimension = 0 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref + gpu.subgroup_mma_store_matrix %res#13, %y[%yr3, %yc1] {leadDimension = 0 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref + gpu.subgroup_mma_store_matrix %res#14, %y[%yr3, %yc2] {leadDimension = 0 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref + gpu.subgroup_mma_store_matrix %res#15, %y[%yr3, %yc3] {leadDimension = 0 : index} : !gpu.mma_matrix<8x8xf32, "COp">, memref + macro.yield %tb : i32 + }; + } + } + } + return; +} + /// The product of a bf16 matrix as `pf_mm_q4_mlir`, from `expert_product.py --bf16`: each weight /// goes to f16 in shared memory, as each Q4_0 weight does there. For a router: its weights are /// below 0.4, and the f16 of a weight below 6.1e-5 is off by 3e-8 at most. Rows need not be a diff --git a/src/prefill35.vx b/src/prefill35.vx index 47d70bd..a001510 100644 --- a/src/prefill35.vx +++ b/src/prefill35.vx @@ -70,7 +70,7 @@ fn new_prefill35(c : &Config, chunk : i32) -> Prefill35 { let k = c.experts_per_token; let experts = c.num_experts; let positions = expert_positions(c, chunk); - let cap = (chunk + 31) / 32 * 32; + let cap = (chunk + 63) / 64 * 64; let mut ident = Tensor([positions]); for p in 0..positions { ident[p] = p; @@ -964,6 +964,18 @@ fn pf_gated_flash_attention(y : &mut Tensor, q : &Tens // ------------------------------------------------------------------------------ experts --- +/// A dense product of the chunk: `pf_mm` with no bias and no `add`, or, for a Q4_0 matrix of whole +/// blocks of 64 rows, `pf_mm_q4_mlir64`, whose blocks of 64 tokens decode each weight for 64 tokens +/// in place of 32. `new_prefill35` makes the tensors of the chunk for whole blocks of 64 tokens. +fn pf35_mm(y : &mut Tensor, m : &WeightMatrix, x : &Tensor, list : &Tensor, zeros : &Tensor, no_bias : &Tensor, rows : i32, cols : i32, tiles : i32) -> void { + if m.dtype == U4 && rows % 64 == 0 { + pf_mm_q4_mlir64(y, &m.codes, &m.group_scales, x, list, zeros, 0, rows, cols, tiles); + } else { + pf_mm(y, m, x, list, zeros, 0, no_bias, false, false, rows, cols, tiles); + } + return; +} + /// x[t] += sigmoid(router[t][at]) * out[t], for t below n: the shared expert times its gate. fn pf35_add_shared(x : &mut Tensor, out : &Tensor, router : &Tensor, at : i32, n : i32, dim : i32) -> void { spawn on(Topology::Device) { @@ -1006,9 +1018,9 @@ fn pf35_experts(p : &mut Prefill35, layer : &Qwen35Layer, c : &Config, n : i32, pf_silu_mul_live(&mut p.e_h, &p.e_gu, &p.e_ident, e_tiles * 16, inter); pf_mm(&mut p.e_out, &layer.down, &p.e_h, &p.e_ident, &p.e_bases, c.hidden_size, &p.no_bias, false, false, c.hidden_size, inter, e_tiles); pf_combine(&mut p.x, &p.e_out, &p.wts, &p.slot, n, k, c.hidden_size); - pf_mm(&mut p.s_gu, &layer.shared_gate_up, &p.xn, &p.rows, &p.zeros, 0, &p.no_bias, false, false, 2 * shared, c.hidden_size, tiles); + pf35_mm(&mut p.s_gu, &layer.shared_gate_up, &p.xn, &p.rows, &p.zeros, &p.no_bias, 2 * shared, c.hidden_size, tiles); pf_silu_mul(&mut p.s_h, &p.s_gu, n, shared); - pf_mm(&mut p.s_out, &layer.shared_down, &p.s_h, &p.rows, &p.zeros, 0, &p.no_bias, false, false, c.hidden_size, shared, tiles); + pf35_mm(&mut p.s_out, &layer.shared_down, &p.s_h, &p.rows, &p.zeros, &p.no_bias, c.hidden_size, shared, tiles); pf35_add_shared(&mut p.x, &p.s_out, &p.router, experts, n, c.hidden_size); return; } @@ -1033,19 +1045,19 @@ fn pf35_chunk(w : &Qwen35Weights, s : &mut Qwen35State, p : &mut Prefill35, star let layer = &w.layers[l]; pf35_rms_norm(&mut p.xn, &p.x, &layer.attn_norm, n, c.hidden_size, eps); if layer.full_attention { - pf_mm(&mut p.proj, &layer.qkv, &p.xn, &p.rows, &p.zeros, 0, &p.no_bias, false, false, qkv_rows, c.hidden_size, tiles); + pf35_mm(&mut p.proj, &layer.qkv, &p.xn, &p.rows, &p.zeros, &p.no_bias, qkv_rows, c.hidden_size, tiles); pf_gated_norm_rope_and_store(&mut p.q, &mut ls.k, &mut ls.v, &p.proj, &layer.q_norm, &layer.k_norm, &s.cos, &s.sin, start, n, c.num_q_heads, c.num_kv_heads, c.rotary_dim, eps); pf_gated_flash_attention(&mut p.y, &p.q, &ls.k, &ls.v, &p.proj, start, n, c.num_q_heads, c.num_q_heads / c.num_kv_heads, qkv_rows - c.num_q_heads * 256, 0.0625); // The product goes to xn, which is free until the norm, as in `pf_chunk`. - pf_mm(&mut p.xn, &layer.attn_out, &p.y, &p.rows, &p.zeros, 0, &p.no_bias, false, false, c.hidden_size, c.num_q_heads * 256, tiles); + pf35_mm(&mut p.xn, &layer.attn_out, &p.y, &p.rows, &p.zeros, &p.no_bias, c.hidden_size, c.num_q_heads * 256, tiles); } else { - pf_mm(&mut p.proj, &layer.linear_in, &p.xn, &p.rows, &p.zeros, 0, &p.no_bias, false, false, a_at + vh, c.hidden_size, tiles); + pf35_mm(&mut p.proj, &layer.linear_in, &p.xn, &p.rows, &p.zeros, &p.no_bias, a_at + vh, c.hidden_size, tiles); pf_dn_conv(&mut p.dq, &mut p.dk, &mut p.dv, &ls.conv, &p.proj, &layer.conv, n, kh, vh); pf_dn_conv_state(&mut ls.conv, &p.proj, n, 2 * kh + vh); pf_dn_gates(&mut p.beta, &mut p.decay, &p.proj, &layer.neg_a, &layer.dt_bias, b_at, a_at, n, vh); pf_dn_recur(&mut p.o, &mut ls.s, &p.dq, &p.dk, &p.dv, &p.beta, &p.decay, vh / kh, n, vh); pf_dn_gated_norm(&mut p.y, &p.o, &p.proj, &layer.linear_norm, z_at, n, vh, eps); - pf_mm(&mut p.xn, &layer.linear_out, &p.y, &p.rows, &p.zeros, 0, &p.no_bias, false, false, c.hidden_size, vh * 128, tiles); + pf35_mm(&mut p.xn, &layer.linear_out, &p.y, &p.rows, &p.zeros, &p.no_bias, c.hidden_size, vh * 128, tiles); } pf35_add_rms_norm(&mut p.x, &mut p.xn, &layer.mlp_norm, n, c.hidden_size, eps); pf35_experts(p, layer, c, n, tiles); From 1f3cd295d6acad5446af4e23431beff9b06bea97 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:17:05 -0800 Subject: [PATCH 24/60] ci: give the tests 60 minutes The pull requests of Qwen3.6 (#95 and #97) stopped at the limit of 30 minutes with no failed test: #95 passed 90 RUN lines and #97 passed 95 before the cancel. A RUN line that compiles the app takes 90 to 115 s on the macOS runner, so the whole suite needs more than 30 minutes now. Issue: #89 --- .github/workflows/ci.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 22d1076..47a014a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,8 +13,9 @@ 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 + # 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 From cbba4e5d2b74a81d140ccd9107c14fc9b1489604 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:43:10 -0800 Subject: [PATCH 25/60] ci: test again with the time limit of main This commit changes no file. The tests of this pull request stopped at the limit of 30 minutes, with no failed test. main now gives the tests 60 minutes (#100). A push makes GitHub test a new merge with main. From 86e7cb31ab732e88c6ec6e4b0a960a92de024540 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:43:10 -0800 Subject: [PATCH 26/60] ci: test again with the time limit of main This commit changes no file. The tests of this pull request stopped at the limit of 30 minutes, with no failed test. main now gives the tests 60 minutes (#100). A push makes GitHub test a new merge with main. From 8271f9e189586328a5a859b4634a548195bd93c5 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Sat, 21 Nov 2026 00:41:45 -0800 Subject: [PATCH 27/60] ci: test again with the time limit of main This commit changes no file. The tests of this pull request stopped at the limit of 30 minutes, with no failed test. main now gives the tests 60 minutes (#100). A push makes GitHub test a new merge with main. From f0b28dc7bbea86a061ede1481a753575e8add397 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Sat, 21 Nov 2026 02:42:15 -0800 Subject: [PATCH 28/60] ci: test again with the time limit of main This commit changes no file. The tests of this pull request stopped at the limit of 30 minutes, with no failed test. main now gives the tests 60 minutes (#100). A push makes GitHub test a new merge with main. From 8ecf3598cbab539534e5d2d7aa689d763d3d03c6 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:34:43 -0800 Subject: [PATCH 29/60] qwen app: compile the prompt kernels of Qwen3.6 before the first clock (#89) The first run of a kernel compiles it, so the first run of a prompt took about 1 s more than the next runs. Before the first clock starts, run_qwen35 now runs the first tokens of the prompt (up to 16) 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. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- src/main.vx | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/main.vx b/src/main.vx index 53d7378..25990c6 100644 --- a/src/main.vx +++ b/src/main.vx @@ -591,6 +591,18 @@ fn run_qwen35(path : *const i8, t : &Tokenizer, text_mode : bool, chat : bool, i // 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()); + 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 { From 7c4c9aadafffdc85b450305add43d23b1ec13aee Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:10:24 -0800 Subject: [PATCH 30/60] benchmark: a runner for Qwen3.6 against llama.cpp, as the benchmarking policy asks docs/benchmarks/qwen36-m4/ holds the prompts and the scripts of the benchmark. make_prompts.py writes 6 prompts of 64 to 32,768 tokens of the app's source code, and 24 code prompts in the chat format of Qwen3.6. run.sh runs the app at -O2 and llama.cpp on them. It chooses the draft lengths of each program on 12 prompts and measures them on 12 others. parse.py writes runs.csv and summary.md. The results come in a later commit, after a run on a quiet Mac. Issue: #89 --- docs/benchmarks/qwen36-m4/make_prompts.py | 163 ++ docs/benchmarks/qwen36-m4/parse.py | 326 +++ .../prompts/context/llama/ctx16384.txt | 902 ++++++++ .../prompts/context/llama/ctx2048.txt | 138 ++ .../prompts/context/llama/ctx32768.txt | 1975 +++++++++++++++++ .../prompts/context/llama/ctx512.txt | 43 + .../qwen36-m4/prompts/context/llama/ctx64.txt | 6 + .../prompts/context/llama/ctx8192.txt | 418 ++++ .../qwen36-m4/prompts/context/vx/ctx16384.txt | 902 ++++++++ .../qwen36-m4/prompts/context/vx/ctx2048.txt | 138 ++ .../qwen36-m4/prompts/context/vx/ctx32768.txt | 1975 +++++++++++++++++ .../qwen36-m4/prompts/context/vx/ctx512.txt | 43 + .../qwen36-m4/prompts/context/vx/ctx64.txt | 6 + .../qwen36-m4/prompts/context/vx/ctx8192.txt | 418 ++++ .../prompts/heldout/llama/complete1.txt | 102 + .../prompts/heldout/llama/complete2.txt | 112 + .../prompts/heldout/llama/complete3.txt | 134 ++ .../qwen36-m4/prompts/heldout/llama/edit1.txt | 128 ++ .../qwen36-m4/prompts/heldout/llama/edit2.txt | 132 ++ .../qwen36-m4/prompts/heldout/llama/edit3.txt | 134 ++ .../prompts/heldout/llama/explain1.txt | 126 ++ .../prompts/heldout/llama/explain2.txt | 129 ++ .../prompts/heldout/llama/explain3.txt | 134 ++ .../prompts/heldout/llama/write1.txt | 8 + .../prompts/heldout/llama/write2.txt | 8 + .../prompts/heldout/llama/write3.txt | 8 + .../prompts/heldout/vx/complete1.txt | 101 + .../prompts/heldout/vx/complete2.txt | 111 + .../prompts/heldout/vx/complete3.txt | 133 ++ .../qwen36-m4/prompts/heldout/vx/edit1.txt | 127 ++ .../qwen36-m4/prompts/heldout/vx/edit2.txt | 131 ++ .../qwen36-m4/prompts/heldout/vx/edit3.txt | 133 ++ .../qwen36-m4/prompts/heldout/vx/explain1.txt | 125 ++ .../qwen36-m4/prompts/heldout/vx/explain2.txt | 128 ++ .../qwen36-m4/prompts/heldout/vx/explain3.txt | 133 ++ .../qwen36-m4/prompts/heldout/vx/write1.txt | 7 + .../qwen36-m4/prompts/heldout/vx/write2.txt | 7 + .../qwen36-m4/prompts/heldout/vx/write3.txt | 7 + docs/benchmarks/qwen36-m4/prompts/tokens.csv | 31 + .../prompts/twelve/llama/complete1.txt | 130 ++ .../prompts/twelve/llama/complete2.txt | 146 ++ .../prompts/twelve/llama/complete3.txt | 136 ++ .../qwen36-m4/prompts/twelve/llama/edit1.txt | 183 ++ .../qwen36-m4/prompts/twelve/llama/edit2.txt | 152 ++ .../qwen36-m4/prompts/twelve/llama/edit3.txt | 207 ++ .../prompts/twelve/llama/explain1.txt | 153 ++ .../prompts/twelve/llama/explain2.txt | 144 ++ .../prompts/twelve/llama/explain3.txt | 236 ++ .../qwen36-m4/prompts/twelve/llama/write1.txt | 8 + .../qwen36-m4/prompts/twelve/llama/write2.txt | 8 + .../qwen36-m4/prompts/twelve/llama/write3.txt | 8 + .../qwen36-m4/prompts/twelve/vx/complete1.txt | 129 ++ .../qwen36-m4/prompts/twelve/vx/complete2.txt | 145 ++ .../qwen36-m4/prompts/twelve/vx/complete3.txt | 135 ++ .../qwen36-m4/prompts/twelve/vx/edit1.txt | 182 ++ .../qwen36-m4/prompts/twelve/vx/edit2.txt | 151 ++ .../qwen36-m4/prompts/twelve/vx/edit3.txt | 206 ++ .../qwen36-m4/prompts/twelve/vx/explain1.txt | 152 ++ .../qwen36-m4/prompts/twelve/vx/explain2.txt | 143 ++ .../qwen36-m4/prompts/twelve/vx/explain3.txt | 235 ++ .../qwen36-m4/prompts/twelve/vx/write1.txt | 7 + .../qwen36-m4/prompts/twelve/vx/write2.txt | 7 + .../qwen36-m4/prompts/twelve/vx/write3.txt | 7 + docs/benchmarks/qwen36-m4/run.sh | 209 ++ 64 files changed, 13001 insertions(+) create mode 100755 docs/benchmarks/qwen36-m4/make_prompts.py create mode 100755 docs/benchmarks/qwen36-m4/parse.py create mode 100644 docs/benchmarks/qwen36-m4/prompts/context/llama/ctx16384.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/context/llama/ctx2048.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/context/llama/ctx32768.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/context/llama/ctx512.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/context/llama/ctx64.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/context/llama/ctx8192.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/context/vx/ctx16384.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/context/vx/ctx2048.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/context/vx/ctx32768.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/context/vx/ctx512.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/context/vx/ctx64.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/context/vx/ctx8192.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/heldout/llama/complete1.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/heldout/llama/complete2.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/heldout/llama/complete3.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/heldout/llama/edit1.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/heldout/llama/edit2.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/heldout/llama/edit3.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/heldout/llama/explain1.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/heldout/llama/explain2.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/heldout/llama/explain3.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/heldout/llama/write1.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/heldout/llama/write2.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/heldout/llama/write3.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/heldout/vx/complete1.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/heldout/vx/complete2.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/heldout/vx/complete3.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/heldout/vx/edit1.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/heldout/vx/edit2.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/heldout/vx/edit3.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/heldout/vx/explain1.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/heldout/vx/explain2.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/heldout/vx/explain3.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/heldout/vx/write1.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/heldout/vx/write2.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/heldout/vx/write3.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/tokens.csv create mode 100644 docs/benchmarks/qwen36-m4/prompts/twelve/llama/complete1.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/twelve/llama/complete2.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/twelve/llama/complete3.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/twelve/llama/edit1.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/twelve/llama/edit2.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/twelve/llama/edit3.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/twelve/llama/explain1.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/twelve/llama/explain2.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/twelve/llama/explain3.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/twelve/llama/write1.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/twelve/llama/write2.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/twelve/llama/write3.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/twelve/vx/complete1.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/twelve/vx/complete2.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/twelve/vx/complete3.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/twelve/vx/edit1.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/twelve/vx/edit2.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/twelve/vx/edit3.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/twelve/vx/explain1.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/twelve/vx/explain2.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/twelve/vx/explain3.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/twelve/vx/write1.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/twelve/vx/write2.txt create mode 100644 docs/benchmarks/qwen36-m4/prompts/twelve/vx/write3.txt create mode 100755 docs/benchmarks/qwen36-m4/run.sh diff --git a/docs/benchmarks/qwen36-m4/make_prompts.py b/docs/benchmarks/qwen36-m4/make_prompts.py new file mode 100755 index 0000000..4539cca --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/parse.py b/docs/benchmarks/qwen36-m4/parse.py new file mode 100755 index 0000000..a07f964 --- /dev/null +++ b/docs/benchmarks/qwen36-m4/parse.py @@ -0,0 +1,326 @@ +#!/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=… LOOKUP_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", + "lookup": "llama-lookup", + "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", "lookup": "LOOKUP_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-lookup and llama-speculative-simple print the same lines + 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 + + +def generated_text(path): + """The output of the app after the line of the compiler, without its lines of times and drafts.""" + lines = path.read_text(errors="replace").split("\n") + start = next((i + 1 for i, line in enumerate(lines) if line.startswith("[JIT] Compiling to native object")), None) + assert start is not None, f"{path} has no line of the compiler" + lines = [re.sub(r"rounds=\d+ drafted=\d+ accepted=\d+;", "", line) for line in lines[start:] + if not line.startswith("time ")] + return "\n".join(lines).rstrip("\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() + r = parse_log(program, (out / "logs" / f"{name}.txt").read_text(errors="replace")) + 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"), + 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())) + 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): + return [r for r in rows if r["table"] == table and r["rc"] == 0 and r["ms_per_token"] is not None + 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 same_text(out, rows, table): + """For each run with --draft, whether its text is that of the run without drafts.""" + same = [] + for r in timed(rows, table, PROGRAMS["vxdraft"]): + plain = out / re.sub(r"\.vxdraft\d+\.txt$", ".vx.txt", r["log"]) + if plain.exists(): + same.append(generated_text(plain) == generated_text(out / r["log"])) + return same + + +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("") + 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("") + lines += [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 ''} |") + same = same_text(out, rows, "T") + say("") + say(f"- qwen-vx text with and without drafts: the same in {sum(same)} of {len(same)} pairs") + 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) + 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) + cells.append(f"{acc} / {dr} ({100 * acc / dr:.0f}%)" if dr else "") + say(f"| {kind or 'all 12'} | " + " | ".join(cells) + " |") + same = same_text(out, rows, "C") + say("") + say(f"- qwen-vx text with and without drafts: the same in {sum(same)} of {len(same)} pairs") + 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) + 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/qwen36-m4/prompts/context/llama/ctx16384.txt b/docs/benchmarks/qwen36-m4/prompts/context/llama/ctx16384.txt new file mode 100644 index 0000000..86bc604 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/context/llama/ctx2048.txt b/docs/benchmarks/qwen36-m4/prompts/context/llama/ctx2048.txt new file mode 100644 index 0000000..90e3bb2 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/context/llama/ctx32768.txt b/docs/benchmarks/qwen36-m4/prompts/context/llama/ctx32768.txt new file mode 100644 index 0000000..893602a --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/context/llama/ctx512.txt b/docs/benchmarks/qwen36-m4/prompts/context/llama/ctx512.txt new file mode 100644 index 0000000..f61da32 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/context/vx/ctx16384.txt b/docs/benchmarks/qwen36-m4/prompts/context/vx/ctx16384.txt new file mode 100644 index 0000000..f6748f0 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/context/vx/ctx2048.txt b/docs/benchmarks/qwen36-m4/prompts/context/vx/ctx2048.txt new file mode 100644 index 0000000..dd56539 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/context/vx/ctx32768.txt b/docs/benchmarks/qwen36-m4/prompts/context/vx/ctx32768.txt new file mode 100644 index 0000000..68a31d9 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/context/vx/ctx512.txt b/docs/benchmarks/qwen36-m4/prompts/context/vx/ctx512.txt new file mode 100644 index 0000000..f266cda --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/heldout/llama/complete1.txt b/docs/benchmarks/qwen36-m4/prompts/heldout/llama/complete1.txt new file mode 100644 index 0000000..12241e6 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/heldout/llama/complete2.txt b/docs/benchmarks/qwen36-m4/prompts/heldout/llama/complete2.txt new file mode 100644 index 0000000..1a872a5 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/heldout/llama/complete3.txt b/docs/benchmarks/qwen36-m4/prompts/heldout/llama/complete3.txt new file mode 100644 index 0000000..8ba9deb --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/heldout/llama/edit1.txt b/docs/benchmarks/qwen36-m4/prompts/heldout/llama/edit1.txt new file mode 100644 index 0000000..5874050 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/heldout/llama/edit2.txt b/docs/benchmarks/qwen36-m4/prompts/heldout/llama/edit2.txt new file mode 100644 index 0000000..e1dfddf --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/heldout/llama/edit3.txt b/docs/benchmarks/qwen36-m4/prompts/heldout/llama/edit3.txt new file mode 100644 index 0000000..9ba76fa --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/heldout/llama/explain1.txt b/docs/benchmarks/qwen36-m4/prompts/heldout/llama/explain1.txt new file mode 100644 index 0000000..273f2a3 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/heldout/llama/explain2.txt b/docs/benchmarks/qwen36-m4/prompts/heldout/llama/explain2.txt new file mode 100644 index 0000000..4118f9c --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/heldout/llama/explain3.txt b/docs/benchmarks/qwen36-m4/prompts/heldout/llama/explain3.txt new file mode 100644 index 0000000..70bcbd5 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/heldout/llama/write1.txt b/docs/benchmarks/qwen36-m4/prompts/heldout/llama/write1.txt new file mode 100644 index 0000000..9e393b6 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/heldout/llama/write2.txt b/docs/benchmarks/qwen36-m4/prompts/heldout/llama/write2.txt new file mode 100644 index 0000000..11f00b9 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/heldout/llama/write3.txt b/docs/benchmarks/qwen36-m4/prompts/heldout/llama/write3.txt new file mode 100644 index 0000000..2bd5648 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/heldout/vx/complete1.txt b/docs/benchmarks/qwen36-m4/prompts/heldout/vx/complete1.txt new file mode 100644 index 0000000..9e8250e --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/heldout/vx/complete2.txt b/docs/benchmarks/qwen36-m4/prompts/heldout/vx/complete2.txt new file mode 100644 index 0000000..d8f89e1 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/heldout/vx/complete3.txt b/docs/benchmarks/qwen36-m4/prompts/heldout/vx/complete3.txt new file mode 100644 index 0000000..8dac3a8 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/heldout/vx/edit1.txt b/docs/benchmarks/qwen36-m4/prompts/heldout/vx/edit1.txt new file mode 100644 index 0000000..0ac411a --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/heldout/vx/edit2.txt b/docs/benchmarks/qwen36-m4/prompts/heldout/vx/edit2.txt new file mode 100644 index 0000000..022308f --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/heldout/vx/edit3.txt b/docs/benchmarks/qwen36-m4/prompts/heldout/vx/edit3.txt new file mode 100644 index 0000000..032730c --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/heldout/vx/explain1.txt b/docs/benchmarks/qwen36-m4/prompts/heldout/vx/explain1.txt new file mode 100644 index 0000000..86e53dd --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/heldout/vx/explain2.txt b/docs/benchmarks/qwen36-m4/prompts/heldout/vx/explain2.txt new file mode 100644 index 0000000..75cc3ff --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/heldout/vx/explain3.txt b/docs/benchmarks/qwen36-m4/prompts/heldout/vx/explain3.txt new file mode 100644 index 0000000..a0c208f --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/heldout/vx/write1.txt b/docs/benchmarks/qwen36-m4/prompts/heldout/vx/write1.txt new file mode 100644 index 0000000..316ba64 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/heldout/vx/write2.txt b/docs/benchmarks/qwen36-m4/prompts/heldout/vx/write2.txt new file mode 100644 index 0000000..bcb9afb --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/heldout/vx/write3.txt b/docs/benchmarks/qwen36-m4/prompts/heldout/vx/write3.txt new file mode 100644 index 0000000..d992c11 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/tokens.csv b/docs/benchmarks/qwen36-m4/prompts/tokens.csv new file mode 100644 index 0000000..68741a9 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/twelve/llama/complete1.txt b/docs/benchmarks/qwen36-m4/prompts/twelve/llama/complete1.txt new file mode 100644 index 0000000..e4f8827 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/twelve/llama/complete2.txt b/docs/benchmarks/qwen36-m4/prompts/twelve/llama/complete2.txt new file mode 100644 index 0000000..64b29cb --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/twelve/llama/complete3.txt b/docs/benchmarks/qwen36-m4/prompts/twelve/llama/complete3.txt new file mode 100644 index 0000000..4452b50 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/twelve/llama/edit1.txt b/docs/benchmarks/qwen36-m4/prompts/twelve/llama/edit1.txt new file mode 100644 index 0000000..2acb824 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/twelve/llama/edit2.txt b/docs/benchmarks/qwen36-m4/prompts/twelve/llama/edit2.txt new file mode 100644 index 0000000..e53583a --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/twelve/llama/edit3.txt b/docs/benchmarks/qwen36-m4/prompts/twelve/llama/edit3.txt new file mode 100644 index 0000000..a8c37da --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/twelve/llama/explain1.txt b/docs/benchmarks/qwen36-m4/prompts/twelve/llama/explain1.txt new file mode 100644 index 0000000..3a16598 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/twelve/llama/explain2.txt b/docs/benchmarks/qwen36-m4/prompts/twelve/llama/explain2.txt new file mode 100644 index 0000000..c7e5699 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/twelve/llama/explain3.txt b/docs/benchmarks/qwen36-m4/prompts/twelve/llama/explain3.txt new file mode 100644 index 0000000..dd94476 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/twelve/llama/write1.txt b/docs/benchmarks/qwen36-m4/prompts/twelve/llama/write1.txt new file mode 100644 index 0000000..a9a637f --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/twelve/llama/write2.txt b/docs/benchmarks/qwen36-m4/prompts/twelve/llama/write2.txt new file mode 100644 index 0000000..2b5a941 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/twelve/llama/write3.txt b/docs/benchmarks/qwen36-m4/prompts/twelve/llama/write3.txt new file mode 100644 index 0000000..3f4730e --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/twelve/vx/complete1.txt b/docs/benchmarks/qwen36-m4/prompts/twelve/vx/complete1.txt new file mode 100644 index 0000000..14de931 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/twelve/vx/complete2.txt b/docs/benchmarks/qwen36-m4/prompts/twelve/vx/complete2.txt new file mode 100644 index 0000000..24b2590 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/twelve/vx/complete3.txt b/docs/benchmarks/qwen36-m4/prompts/twelve/vx/complete3.txt new file mode 100644 index 0000000..402843f --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/twelve/vx/edit1.txt b/docs/benchmarks/qwen36-m4/prompts/twelve/vx/edit1.txt new file mode 100644 index 0000000..d90c707 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/twelve/vx/edit2.txt b/docs/benchmarks/qwen36-m4/prompts/twelve/vx/edit2.txt new file mode 100644 index 0000000..a8d2349 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/twelve/vx/edit3.txt b/docs/benchmarks/qwen36-m4/prompts/twelve/vx/edit3.txt new file mode 100644 index 0000000..6b9b566 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/twelve/vx/explain1.txt b/docs/benchmarks/qwen36-m4/prompts/twelve/vx/explain1.txt new file mode 100644 index 0000000..07afd8c --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/twelve/vx/explain2.txt b/docs/benchmarks/qwen36-m4/prompts/twelve/vx/explain2.txt new file mode 100644 index 0000000..be0ac30 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/twelve/vx/explain3.txt b/docs/benchmarks/qwen36-m4/prompts/twelve/vx/explain3.txt new file mode 100644 index 0000000..f08793b --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/twelve/vx/write1.txt b/docs/benchmarks/qwen36-m4/prompts/twelve/vx/write1.txt new file mode 100644 index 0000000..4c6ec5f --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/twelve/vx/write2.txt b/docs/benchmarks/qwen36-m4/prompts/twelve/vx/write2.txt new file mode 100644 index 0000000..ff6783d --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/prompts/twelve/vx/write3.txt b/docs/benchmarks/qwen36-m4/prompts/twelve/vx/write3.txt new file mode 100644 index 0000000..4c6caf4 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/run.sh b/docs/benchmarks/qwen36-m4/run.sh new file mode 100755 index 0000000..631d23c --- /dev/null +++ b/docs/benchmarks/qwen36-m4/run.sh @@ -0,0 +1,209 @@ +#!/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, llama-speculative-simple with the MTP heads each of MTP_DRAFTS, and llama-lookup +# each of LOOKUP_DRAFTS. Table C uses the length with the fastest geometric mean. +# llama-speculative-simple with n-gram drafts (ngram-mod) keeps the settings of llama.cpp. +# 6. Table C: the 12 held-out prompts, 512 generated tokens. The programs are the app, the app +# with --draft, llama-completion, llama-lookup, and llama-speculative-simple with n-gram +# drafts and with 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. +# 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, MTP_N and LOOKUP_N. +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="3 5 7 9 11 15" +MTP_DRAFTS="1 2 3 4 6" +LOOKUP_DRAFTS="4 8 16" +PROMPT_RUNS=${PROMPT_RUNS:-3} +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} +P=$HERE/prompts +CONTEXTS="64 512 2048 8192 16384 32768" +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; } +lookup() { llama llama-lookup "$@" -b 4096; } +spec() { llama llama-speculative-simple "$@"; } + +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 "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" +} >> 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" 256 + else + run "A.llama.ctx$c.r$r" completion "$P/context/llama/ctx$c.txt" 256 $((c + 512)) + fi + done + done +done + +# 4. Table P +want P && for r in $(seq 1 "$ROUNDS"); do + for c in 512 2048 8192; 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 +PROMPTS="edit1 complete1 write1 explain1 edit2 complete2 write2 explain2 edit3 complete3 write3 explain3" +if want T; then + cases="vx completion ngram" + for d in $DRAFTS; do cases="$cases vxdraft$d"; done + for d in $MTP_DRAFTS; do cases="$cases mtp$d"; done + for d in $LOOKUP_DRAFTS; do cases="$cases lookup$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" 512 ;; + vxdraft*) run "T.$n.r1.$kind" vx "$P/twelve/vx/$n.txt" 512 --draft "${kind#vxdraft}" ;; + completion) run "T.$n.r1.completion" completion "$f" 512 8192 ;; + ngram) run "T.$n.r1.ngram" spec "$f" 512 8192 --spec-type ngram-mod ;; + mtp*) run "T.$n.r1.$kind" spec "$f" 512 8192 --spec-type draft-mtp -md "$MTP" -ngld 99 --spec-draft-n-max "${kind#mtp}" ;; + lookup*) run "T.$n.r1.$kind" lookup "$f" 512 8192 --spec-draft-n-max "${kind#lookup}" ;; + 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:?} LOOKUP_N=${LOOKUP_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 lookup ngram mtp); do + case $kind in + vx) run "C.$n.r$r.vx" vx "$P/heldout/vx/$n.txt" 512 ;; + vxdraft) run "C.$n.r$r.vxdraft$DRAFT" vx "$P/heldout/vx/$n.txt" 512 --draft "$DRAFT" ;; + completion) run "C.$n.r$r.completion" completion "$f" 512 8192 ;; + lookup) run "C.$n.r$r.lookup$LOOKUP_N" lookup "$f" 512 8192 --spec-draft-n-max "$LOOKUP_N" ;; + ngram) run "C.$n.r$r.ngram" spec "$f" 512 8192 --spec-type ngram-mod ;; + mtp) run "C.$n.r$r.mtp$MTP_N" spec "$f" 512 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 From 04024cc5fda0a6004b136db0c8931f41ba733782 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:41:37 -0800 Subject: [PATCH 31/60] benchmark: check the text of every draft run, and drop llama-lookup A smoke test of the runner on Qwen3.6 found three problems on the llama.cpp side: - llama-lookup cannot roll back the DeltaNet state when it rejects a draft. Its llama_decode calls then fail, it samples old logits, and its text degenerates at about 0.5 ms a token. The runner now uses llama-speculative-simple with ngram-cache, the same n-gram cache with checkpoints. That tool always drafts 8 tokens, so it is not tuned. - llama-speculative-simple stops the clock of the prompt before the GPU ends the prompt. On a 1,799-token prompt this moved 0.77 s into the decode time of ngram-mod. llama-timing.patch adds llama_synchronize, and run.sh records the commit and the patch of llama.cpp in env.txt. - The draft tools stop after the check that passes -n, so they can write a few more tokens. parse.py now compares the text of each draft run with the run without drafts: qwen-vx --draft must write the same text, and a llama.cpp draft run must start with the whole text of llama-completion. Runs with other text or with error lines stay in runs.csv and are out of the summary. A table gives where qwen-vx and llama-completion start to write different text. run.sh can also take smaller lists of contexts, prompts and lengths for a short test, and the text starts after the last line of vxc. Issue: #89 --- docs/benchmarks/qwen36-m4/llama-timing.patch | 14 +++ docs/benchmarks/qwen36-m4/parse.py | 105 ++++++++++++++----- docs/benchmarks/qwen36-m4/run.sh | 74 +++++++------ 3 files changed, 138 insertions(+), 55 deletions(-) create mode 100644 docs/benchmarks/qwen36-m4/llama-timing.patch diff --git a/docs/benchmarks/qwen36-m4/llama-timing.patch b/docs/benchmarks/qwen36-m4/llama-timing.patch new file mode 100644 index 0000000..30232c6 --- /dev/null +++ b/docs/benchmarks/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/qwen36-m4/parse.py b/docs/benchmarks/qwen36-m4/parse.py index a07f964..63a649b 100755 --- a/docs/benchmarks/qwen36-m4/parse.py +++ b/docs/benchmarks/qwen36-m4/parse.py @@ -7,7 +7,7 @@ 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=… LOOKUP_N=…, for run.sh. +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. @@ -27,12 +27,12 @@ "vx": "qwen-vx", "vxdraft": "qwen-vx --draft", "completion": "llama-completion", - "lookup": "llama-lookup", + "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", "lookup": "LOOKUP_N"} +CHOICES = {"vxdraft": "DRAFT", "mtp": "MTP_N"} KINDS = ["edit", "complete", "write", "explain"] SETS = {"T": "twelve", "C": "heldout"} @@ -58,7 +58,7 @@ def parse_log(program, 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-lookup and llama-speculative-simple print the same lines + else: # llama-speculative-simple m = re.search(r"decoded +(\d+) tokens in +([0-9.]+) seconds", text) if m: r["timed_tokens"] = int(m[1]) @@ -73,14 +73,28 @@ def parse_log(program, text): return r -def generated_text(path): - """The output of the app after the line of the compiler, without its lines of times and drafts.""" +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 + 1 for i, line in enumerate(lines) if line.startswith("[JIT] Compiling to native object")), None) - assert start is not None, f"{path} has no line of the compiler" - lines = [re.sub(r"rounds=\d+ drafted=\d+ accepted=\d+;", "", line) for line in lines[start:] - if not line.startswith("time ")] - return "\n".join(lines).rstrip("\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): @@ -105,7 +119,8 @@ def read_rows(out): 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() - r = parse_log(program, (out / "logs" / f"{name}.txt").read_text(errors="replace")) + 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 @@ -118,6 +133,7 @@ def read_rows(out): 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 @@ -141,7 +157,10 @@ def spread(xs, fmt="{:.2f}"): def timed(rows, table, program=None, setting=None): + """The runs of the summary: no failed runs, no runs with error lines, and no runs with drafts that + wrote other text than the runs without drafts.""" 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 r.get("same_text") is not False and (program is None or r["program"] == program) and (setting is None or r["setting"] == setting)] @@ -166,14 +185,35 @@ def choose(rows): return " ".join(words) -def same_text(out, rows, table): - """For each run with --draft, whether its text is that of the run without drafts.""" - same = [] - for r in timed(rows, table, PROGRAMS["vxdraft"]): - plain = out / re.sub(r"\.vxdraft\d+\.txt$", ".vx.txt", r["log"]) - if plain.exists(): - same.append(generated_text(plain) == generated_text(out / r["log"])) - return same +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.""" + for r in rows: + r["same_text"] = "" + 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) + + +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: + plain = "qwen-vx" if p == PROGRAMS["vxdraft"] else "llama-completion" + differ = [r["log"] 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 the summary: {', '.join(differ)}" if differ else "")) def summary(out, rows): @@ -183,6 +223,10 @@ def summary(out, rows): 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)) @@ -241,9 +285,8 @@ def summary(out, rows): 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 ''} |") - same = same_text(out, rows, "T") say("") - say(f"- qwen-vx text with and without drafts: the same in {sum(same)} of {len(same)} pairs") + say_same_text(say, rows, "T") say("") programs = [p for p in PROGRAMS.values() if timed(rows, "C", p)] @@ -294,9 +337,22 @@ def compare(a, b): acc, dr = sum(r["accepted"] or 0 for r in rr), sum(r["drafted"] or 0 for r in rr) cells.append(f"{acc} / {dr} ({100 * acc / dr:.0f}%)" if dr else "") say(f"| {kind or 'all 12'} | " + " | ".join(cells) + " |") - same = same_text(out, rows, "C") say("") - say(f"- qwen-vx text with and without drafts: the same in {sum(same)} of {len(same)} pairs") + 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"): @@ -315,6 +371,7 @@ def main(): 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 diff --git a/docs/benchmarks/qwen36-m4/run.sh b/docs/benchmarks/qwen36-m4/run.sh index 631d23c..95afd78 100755 --- a/docs/benchmarks/qwen36-m4/run.sh +++ b/docs/benchmarks/qwen36-m4/run.sh @@ -10,28 +10,38 @@ # 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, llama-speculative-simple with the MTP heads each of MTP_DRAFTS, and llama-lookup -# each of LOOKUP_DRAFTS. Table C uses the length with the fastest geometric mean. -# llama-speculative-simple with n-gram drafts (ngram-mod) keeps the settings of llama.cpp. +# 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, llama-lookup, and llama-speculative-simple with n-gram -# drafts and with the MTP heads. +# 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, MTP_N and LOOKUP_N. +# 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="3 5 7 9 11 15" -MTP_DRAFTS="1 2 3 4 6" -LOOKUP_DRAFTS="4 8 16" +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)} @@ -40,8 +50,8 @@ 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 -CONTEXTS="64 512 2048 8192 16384 32768" want() { [[ " $STAGES " == *" $1 "* ]]; } mkdir -p "$OUT/logs" cd "$OUT" || exit 1 @@ -75,7 +85,6 @@ llama() { # TOOL PROMPT N CTX [options] 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; } -lookup() { llama llama-lookup "$@" -b 4096; } spec() { llama llama-speculative-simple "$@"; } run() { # NAME COMMAND...: one run, its output in logs/NAME.txt, a line in log.txt @@ -100,11 +109,16 @@ run() { # NAME COMMAND...: one run, its output in logs/NAME.txt, a line in log.t 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. @@ -140,9 +154,9 @@ 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" 256 + 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" 256 $((c + 512)) + run "A.llama.ctx$c.r$r" completion "$P/context/llama/ctx$c.txt" "$A_TOKENS" $((c + 512)) fi done done @@ -150,7 +164,7 @@ done # 4. Table P want P && for r in $(seq 1 "$ROUNDS"); do - for c in 512 2048 8192; 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" @@ -162,24 +176,22 @@ want P && for r in $(seq 1 "$ROUNDS"); do done # 5. Table T -PROMPTS="edit1 complete1 write1 explain1 edit2 complete2 write2 explain2 edit3 complete3 write3 explain3" if want T; then - cases="vx completion ngram" + 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 - for d in $LOOKUP_DRAFTS; do cases="$cases lookup$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" 512 ;; - vxdraft*) run "T.$n.r1.$kind" vx "$P/twelve/vx/$n.txt" 512 --draft "${kind#vxdraft}" ;; - completion) run "T.$n.r1.completion" completion "$f" 512 8192 ;; - ngram) run "T.$n.r1.ngram" spec "$f" 512 8192 --spec-type ngram-mod ;; - mtp*) run "T.$n.r1.$kind" spec "$f" 512 8192 --spec-type draft-mtp -md "$MTP" -ngld 99 --spec-draft-n-max "${kind#mtp}" ;; - lookup*) run "T.$n.r1.$kind" lookup "$f" 512 8192 --spec-draft-n-max "${kind#lookup}" ;; + 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 @@ -187,21 +199,21 @@ if want T; then 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:?} LOOKUP_N=${LOOKUP_N:?}" | tee -a log.txt env.txt + 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 lookup ngram mtp); do + 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" 512 ;; - vxdraft) run "C.$n.r$r.vxdraft$DRAFT" vx "$P/heldout/vx/$n.txt" 512 --draft "$DRAFT" ;; - completion) run "C.$n.r$r.completion" completion "$f" 512 8192 ;; - lookup) run "C.$n.r$r.lookup$LOOKUP_N" lookup "$f" 512 8192 --spec-draft-n-max "$LOOKUP_N" ;; - ngram) run "C.$n.r$r.ngram" spec "$f" 512 8192 --spec-type ngram-mod ;; - mtp) run "C.$n.r$r.mtp$MTP_N" spec "$f" 512 8192 --spec-type draft-mtp -md "$MTP" -ngld 99 --spec-draft-n-max "$MTP_N" ;; + 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 From 5a9aadcae72057ce6ce061ee6e724edfa41d825c Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:09:53 -0800 Subject: [PATCH 32/60] benchmark: date the folder of the Qwen3.6 benchmark The policy names each folder of a measurement by its date. The full run starts on 2026-11-20. Issue: #89 --- .../{qwen36-m4 => 2026-11-20-qwen36-m4}/llama-timing.patch | 0 .../{qwen36-m4 => 2026-11-20-qwen36-m4}/make_prompts.py | 0 docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/parse.py | 0 .../prompts/context/llama/ctx16384.txt | 0 .../prompts/context/llama/ctx2048.txt | 0 .../prompts/context/llama/ctx32768.txt | 0 .../prompts/context/llama/ctx512.txt | 0 .../prompts/context/llama/ctx64.txt | 0 .../prompts/context/llama/ctx8192.txt | 0 .../prompts/context/vx/ctx16384.txt | 0 .../prompts/context/vx/ctx2048.txt | 0 .../prompts/context/vx/ctx32768.txt | 0 .../prompts/context/vx/ctx512.txt | 0 .../prompts/context/vx/ctx64.txt | 0 .../prompts/context/vx/ctx8192.txt | 0 .../prompts/heldout/llama/complete1.txt | 0 .../prompts/heldout/llama/complete2.txt | 0 .../prompts/heldout/llama/complete3.txt | 0 .../prompts/heldout/llama/edit1.txt | 0 .../prompts/heldout/llama/edit2.txt | 0 .../prompts/heldout/llama/edit3.txt | 0 .../prompts/heldout/llama/explain1.txt | 0 .../prompts/heldout/llama/explain2.txt | 0 .../prompts/heldout/llama/explain3.txt | 0 .../prompts/heldout/llama/write1.txt | 0 .../prompts/heldout/llama/write2.txt | 0 .../prompts/heldout/llama/write3.txt | 0 .../prompts/heldout/vx/complete1.txt | 0 .../prompts/heldout/vx/complete2.txt | 0 .../prompts/heldout/vx/complete3.txt | 0 .../prompts/heldout/vx/edit1.txt | 0 .../prompts/heldout/vx/edit2.txt | 0 .../prompts/heldout/vx/edit3.txt | 0 .../prompts/heldout/vx/explain1.txt | 0 .../prompts/heldout/vx/explain2.txt | 0 .../prompts/heldout/vx/explain3.txt | 0 .../prompts/heldout/vx/write1.txt | 0 .../prompts/heldout/vx/write2.txt | 0 .../prompts/heldout/vx/write3.txt | 0 .../{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/tokens.csv | 0 .../prompts/twelve/llama/complete1.txt | 0 .../prompts/twelve/llama/complete2.txt | 0 .../prompts/twelve/llama/complete3.txt | 0 .../prompts/twelve/llama/edit1.txt | 0 .../prompts/twelve/llama/edit2.txt | 0 .../prompts/twelve/llama/edit3.txt | 0 .../prompts/twelve/llama/explain1.txt | 0 .../prompts/twelve/llama/explain2.txt | 0 .../prompts/twelve/llama/explain3.txt | 0 .../prompts/twelve/llama/write1.txt | 0 .../prompts/twelve/llama/write2.txt | 0 .../prompts/twelve/llama/write3.txt | 0 .../prompts/twelve/vx/complete1.txt | 0 .../prompts/twelve/vx/complete2.txt | 0 .../prompts/twelve/vx/complete3.txt | 0 .../prompts/twelve/vx/edit1.txt | 0 .../prompts/twelve/vx/edit2.txt | 0 .../prompts/twelve/vx/edit3.txt | 0 .../prompts/twelve/vx/explain1.txt | 0 .../prompts/twelve/vx/explain2.txt | 0 .../prompts/twelve/vx/explain3.txt | 0 .../prompts/twelve/vx/write1.txt | 0 .../prompts/twelve/vx/write2.txt | 0 .../prompts/twelve/vx/write3.txt | 0 docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/run.sh | 0 65 files changed, 0 insertions(+), 0 deletions(-) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/llama-timing.patch (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/make_prompts.py (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/parse.py (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/context/llama/ctx16384.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/context/llama/ctx2048.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/context/llama/ctx32768.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/context/llama/ctx512.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/context/llama/ctx64.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/context/llama/ctx8192.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/context/vx/ctx16384.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/context/vx/ctx2048.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/context/vx/ctx32768.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/context/vx/ctx512.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/context/vx/ctx64.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/context/vx/ctx8192.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/heldout/llama/complete1.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/heldout/llama/complete2.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/heldout/llama/complete3.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/heldout/llama/edit1.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/heldout/llama/edit2.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/heldout/llama/edit3.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/heldout/llama/explain1.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/heldout/llama/explain2.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/heldout/llama/explain3.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/heldout/llama/write1.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/heldout/llama/write2.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/heldout/llama/write3.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/heldout/vx/complete1.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/heldout/vx/complete2.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/heldout/vx/complete3.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/heldout/vx/edit1.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/heldout/vx/edit2.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/heldout/vx/edit3.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/heldout/vx/explain1.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/heldout/vx/explain2.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/heldout/vx/explain3.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/heldout/vx/write1.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/heldout/vx/write2.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/heldout/vx/write3.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/tokens.csv (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/twelve/llama/complete1.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/twelve/llama/complete2.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/twelve/llama/complete3.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/twelve/llama/edit1.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/twelve/llama/edit2.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/twelve/llama/edit3.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/twelve/llama/explain1.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/twelve/llama/explain2.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/twelve/llama/explain3.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/twelve/llama/write1.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/twelve/llama/write2.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/twelve/llama/write3.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/twelve/vx/complete1.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/twelve/vx/complete2.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/twelve/vx/complete3.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/twelve/vx/edit1.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/twelve/vx/edit2.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/twelve/vx/edit3.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/twelve/vx/explain1.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/twelve/vx/explain2.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/twelve/vx/explain3.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/twelve/vx/write1.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/twelve/vx/write2.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/prompts/twelve/vx/write3.txt (100%) rename docs/benchmarks/{qwen36-m4 => 2026-11-20-qwen36-m4}/run.sh (100%) diff --git a/docs/benchmarks/qwen36-m4/llama-timing.patch b/docs/benchmarks/2026-11-20-qwen36-m4/llama-timing.patch similarity index 100% rename from docs/benchmarks/qwen36-m4/llama-timing.patch rename to docs/benchmarks/2026-11-20-qwen36-m4/llama-timing.patch diff --git a/docs/benchmarks/qwen36-m4/make_prompts.py b/docs/benchmarks/2026-11-20-qwen36-m4/make_prompts.py similarity index 100% rename from docs/benchmarks/qwen36-m4/make_prompts.py rename to docs/benchmarks/2026-11-20-qwen36-m4/make_prompts.py diff --git a/docs/benchmarks/qwen36-m4/parse.py b/docs/benchmarks/2026-11-20-qwen36-m4/parse.py similarity index 100% rename from docs/benchmarks/qwen36-m4/parse.py rename to docs/benchmarks/2026-11-20-qwen36-m4/parse.py diff --git a/docs/benchmarks/qwen36-m4/prompts/context/llama/ctx16384.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/llama/ctx16384.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/context/llama/ctx16384.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/llama/ctx16384.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/context/llama/ctx2048.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/llama/ctx2048.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/context/llama/ctx2048.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/llama/ctx2048.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/context/llama/ctx32768.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/llama/ctx32768.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/context/llama/ctx32768.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/llama/ctx32768.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/context/llama/ctx512.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/llama/ctx512.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/context/llama/ctx512.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/llama/ctx512.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/context/llama/ctx64.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/llama/ctx64.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/context/llama/ctx64.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/llama/ctx64.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/context/llama/ctx8192.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/llama/ctx8192.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/context/llama/ctx8192.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/llama/ctx8192.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/context/vx/ctx16384.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/vx/ctx16384.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/context/vx/ctx16384.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/vx/ctx16384.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/context/vx/ctx2048.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/vx/ctx2048.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/context/vx/ctx2048.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/vx/ctx2048.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/context/vx/ctx32768.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/vx/ctx32768.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/context/vx/ctx32768.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/vx/ctx32768.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/context/vx/ctx512.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/vx/ctx512.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/context/vx/ctx512.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/vx/ctx512.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/context/vx/ctx64.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/vx/ctx64.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/context/vx/ctx64.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/vx/ctx64.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/context/vx/ctx8192.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/vx/ctx8192.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/context/vx/ctx8192.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/context/vx/ctx8192.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/heldout/llama/complete1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/complete1.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/heldout/llama/complete1.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/complete1.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/heldout/llama/complete2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/complete2.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/heldout/llama/complete2.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/complete2.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/heldout/llama/complete3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/complete3.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/heldout/llama/complete3.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/complete3.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/heldout/llama/edit1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/edit1.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/heldout/llama/edit1.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/edit1.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/heldout/llama/edit2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/edit2.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/heldout/llama/edit2.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/edit2.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/heldout/llama/edit3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/edit3.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/heldout/llama/edit3.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/edit3.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/heldout/llama/explain1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/explain1.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/heldout/llama/explain1.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/explain1.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/heldout/llama/explain2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/explain2.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/heldout/llama/explain2.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/explain2.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/heldout/llama/explain3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/explain3.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/heldout/llama/explain3.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/explain3.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/heldout/llama/write1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/write1.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/heldout/llama/write1.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/write1.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/heldout/llama/write2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/write2.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/heldout/llama/write2.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/write2.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/heldout/llama/write3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/write3.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/heldout/llama/write3.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/llama/write3.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/heldout/vx/complete1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/complete1.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/heldout/vx/complete1.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/complete1.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/heldout/vx/complete2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/complete2.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/heldout/vx/complete2.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/complete2.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/heldout/vx/complete3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/complete3.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/heldout/vx/complete3.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/complete3.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/heldout/vx/edit1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/edit1.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/heldout/vx/edit1.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/edit1.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/heldout/vx/edit2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/edit2.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/heldout/vx/edit2.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/edit2.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/heldout/vx/edit3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/edit3.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/heldout/vx/edit3.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/edit3.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/heldout/vx/explain1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/explain1.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/heldout/vx/explain1.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/explain1.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/heldout/vx/explain2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/explain2.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/heldout/vx/explain2.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/explain2.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/heldout/vx/explain3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/explain3.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/heldout/vx/explain3.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/explain3.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/heldout/vx/write1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/write1.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/heldout/vx/write1.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/write1.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/heldout/vx/write2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/write2.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/heldout/vx/write2.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/write2.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/heldout/vx/write3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/write3.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/heldout/vx/write3.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/heldout/vx/write3.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/tokens.csv b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/tokens.csv similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/tokens.csv rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/tokens.csv diff --git a/docs/benchmarks/qwen36-m4/prompts/twelve/llama/complete1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/complete1.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/twelve/llama/complete1.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/complete1.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/twelve/llama/complete2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/complete2.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/twelve/llama/complete2.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/complete2.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/twelve/llama/complete3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/complete3.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/twelve/llama/complete3.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/complete3.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/twelve/llama/edit1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/edit1.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/twelve/llama/edit1.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/edit1.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/twelve/llama/edit2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/edit2.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/twelve/llama/edit2.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/edit2.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/twelve/llama/edit3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/edit3.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/twelve/llama/edit3.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/edit3.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/twelve/llama/explain1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/explain1.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/twelve/llama/explain1.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/explain1.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/twelve/llama/explain2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/explain2.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/twelve/llama/explain2.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/explain2.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/twelve/llama/explain3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/explain3.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/twelve/llama/explain3.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/explain3.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/twelve/llama/write1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/write1.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/twelve/llama/write1.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/write1.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/twelve/llama/write2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/write2.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/twelve/llama/write2.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/write2.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/twelve/llama/write3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/write3.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/twelve/llama/write3.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/llama/write3.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/twelve/vx/complete1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/complete1.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/twelve/vx/complete1.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/complete1.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/twelve/vx/complete2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/complete2.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/twelve/vx/complete2.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/complete2.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/twelve/vx/complete3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/complete3.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/twelve/vx/complete3.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/complete3.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/twelve/vx/edit1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/edit1.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/twelve/vx/edit1.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/edit1.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/twelve/vx/edit2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/edit2.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/twelve/vx/edit2.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/edit2.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/twelve/vx/edit3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/edit3.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/twelve/vx/edit3.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/edit3.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/twelve/vx/explain1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/explain1.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/twelve/vx/explain1.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/explain1.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/twelve/vx/explain2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/explain2.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/twelve/vx/explain2.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/explain2.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/twelve/vx/explain3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/explain3.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/twelve/vx/explain3.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/explain3.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/twelve/vx/write1.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/write1.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/twelve/vx/write1.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/write1.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/twelve/vx/write2.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/write2.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/twelve/vx/write2.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/write2.txt diff --git a/docs/benchmarks/qwen36-m4/prompts/twelve/vx/write3.txt b/docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/write3.txt similarity index 100% rename from docs/benchmarks/qwen36-m4/prompts/twelve/vx/write3.txt rename to docs/benchmarks/2026-11-20-qwen36-m4/prompts/twelve/vx/write3.txt diff --git a/docs/benchmarks/qwen36-m4/run.sh b/docs/benchmarks/2026-11-20-qwen36-m4/run.sh similarity index 100% rename from docs/benchmarks/qwen36-m4/run.sh rename to docs/benchmarks/2026-11-20-qwen36-m4/run.sh From 8e0be8c4fad28331b35bc2a7e1cfb3c62d917590 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Sat, 21 Nov 2026 00:06:40 -0800 Subject: [PATCH 33/60] benchmark: let llama-speculative-simple read prompts of more than 2,048 tokens llama-speculative-simple refuses a prompt that is longer than its batch, which has 2,048 tokens by default. The tuning prompt edit3 has 2,251 tokens, so its 7 runs with drafts failed. The runner now gives the program -b 4096. Decode does not change: the batch sets only how the prompt goes to the model. Issue: #89 --- docs/benchmarks/2026-11-20-qwen36-m4/run.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/run.sh b/docs/benchmarks/2026-11-20-qwen36-m4/run.sh index 95afd78..4180b54 100755 --- a/docs/benchmarks/2026-11-20-qwen36-m4/run.sh +++ b/docs/benchmarks/2026-11-20-qwen36-m4/run.sh @@ -85,7 +85,9 @@ llama() { # TOOL PROMPT N CTX [options] 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; } -spec() { llama llama-speculative-simple "$@"; } +# 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 From 9fde977fcbdd1d8b2f74449da673709bc565de7d Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Sat, 21 Nov 2026 00:06:40 -0800 Subject: [PATCH 34/60] benchmark: count the llama.cpp runs with drafts whose text differs On Qwen3.6, the drafts of llama.cpp can change its greedy text. In table T, 26 of 84 runs left the text of llama-completion, with no error lines. On 3 prompts, ngram-mod, ngram-cache and the MTP heads leave it at the same character, and the texts stay coherent. This points to a near tie that the shape of the batches changes. The summary now counts these runs, and lists each one with the number of equal characters at the start of the two texts. A run of qwen-vx --draft must still write the text of qwen-vx. Issue: #89 --- docs/benchmarks/2026-11-20-qwen36-m4/parse.py | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/parse.py b/docs/benchmarks/2026-11-20-qwen36-m4/parse.py index 63a649b..06bc898 100755 --- a/docs/benchmarks/2026-11-20-qwen36-m4/parse.py +++ b/docs/benchmarks/2026-11-20-qwen36-m4/parse.py @@ -157,10 +157,11 @@ def spread(xs, fmt="{:.2f}"): def timed(rows, table, program=None, setting=None): - """The runs of the summary: no failed runs, no runs with error lines, and no runs with drafts that - wrote other text than the runs without drafts.""" + """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 r.get("same_text") is not False + 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)] @@ -196,24 +197,29 @@ def plain_log(r): 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.""" + 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_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: - plain = "qwen-vx" if p == PROGRAMS["vxdraft"] else "llama-completion" - differ = [r["log"] for r in rr if not r["same_text"]] + 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 the summary: {', '.join(differ)}" if differ else "")) + + (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): From 0be9d5777093a704487cd75b5408e40dd99afac6 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:41:59 -0800 Subject: [PATCH 35/60] benchmark: show the speedup of the llama.cpp drafts in the summary The policy asks for the speedup of drafts against plain decoding of the same program. The summary now gives it for each program of llama.cpp with drafts, against llama-completion. The table of drafts also gives the accepted tokens for each check of qwen-vx --draft. llama.cpp does not print its number of checks. Each start of run.sh adds its settings to env.txt, so the summary now shows each of these lines once. Issue: #89 --- docs/benchmarks/2026-11-20-qwen36-m4/parse.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/parse.py b/docs/benchmarks/2026-11-20-qwen36-m4/parse.py index 06bc898..dfb6847 100755 --- a/docs/benchmarks/2026-11-20-qwen36-m4/parse.py +++ b/docs/benchmarks/2026-11-20-qwen36-m4/parse.py @@ -237,7 +237,9 @@ def summary(out, rows): if wrong: say("llama.cpp read another number of tokens for: " + ", ".join(wrong)) say("") - lines += [line.strip() for line in open(out / "env.txt") if line.startswith(("flash attention:", "draft lengths"))] + # 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") @@ -330,6 +332,9 @@ def compare(a, b): 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("") @@ -341,7 +346,9 @@ def compare(a, b): 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) - cells.append(f"{acc} / {dr} ({100 * acc / dr:.0f}%)" if dr else "") + 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") From eb3fa07c8c4ee8a958654a28065d065d65dde075 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:01:50 -0800 Subject: [PATCH 36/60] benchmark: check that the two weight files hold the same model Three scripts read the weight file of the app and the GGUF file on the CPU. bytes_per_token.py gives the bytes of weights that one generated token reads. compare_bits.py checks that each Q4_0 matrix has the same codes and scales in both files. perplexity.py measures both sets of weights with one program, scripts/reference.py. weights.txt has their output for Qwen3.6-35B-A3B. Issue: #89 --- .../2026-11-20-qwen36-m4/bytes_per_token.py | 52 +++++++++ .../2026-11-20-qwen36-m4/compare_bits.py | 101 ++++++++++++++++++ .../2026-11-20-qwen36-m4/perplexity.py | 72 +++++++++++++ .../2026-11-20-qwen36-m4/weights.txt | 58 ++++++++++ 4 files changed, 283 insertions(+) create mode 100755 docs/benchmarks/2026-11-20-qwen36-m4/bytes_per_token.py create mode 100755 docs/benchmarks/2026-11-20-qwen36-m4/compare_bits.py create mode 100755 docs/benchmarks/2026-11-20-qwen36-m4/perplexity.py create mode 100644 docs/benchmarks/2026-11-20-qwen36-m4/weights.txt 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/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/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% From 7cf911a7e2314b3ad6490aa257306244ba004091 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:01:50 -0800 Subject: [PATCH 37/60] benchmark: the results of Qwen3.6-35B-A3B against llama.cpp on an M4 The report of the run on 2026-11-20 and 2026-11-21, with its data: the summary, one row for each run, the logs in one archive, the settings of each start of run.sh, the build settings and source diff of llama.cpp, and an archive of the side measurements that the report names. On the 12 held-out prompts, qwen-vx decodes 44.5 tokens a second against 38.3 for llama-completion (1.16x). With the MTP heads of the model, llama.cpp makes 58.6 tokens a second, against 51.7 for qwen-vx --draft. parse.py now ends the lines of runs.csv with a newline only, not "\r\n". Issue: #89 --- .../2026-11-20-qwen36-m4/.gitignore | 2 + .../benchmarks/2026-11-20-qwen36-m4/README.md | 365 ++++++++++++++ docs/benchmarks/2026-11-20-qwen36-m4/env.txt | 61 +++ .../2026-11-20-qwen36-m4/extra.tar.xz | Bin 0 -> 18572 bytes .../2026-11-20-qwen36-m4/llama.cpp-build.txt | 13 + .../2026-11-20-qwen36-m4/llama.cpp.diff | 14 + docs/benchmarks/2026-11-20-qwen36-m4/log.txt | 467 ++++++++++++++++++ .../2026-11-20-qwen36-m4/logs.tar.xz | Bin 0 -> 129048 bytes docs/benchmarks/2026-11-20-qwen36-m4/parse.py | 2 +- docs/benchmarks/2026-11-20-qwen36-m4/runs.csv | 457 +++++++++++++++++ .../2026-11-20-qwen36-m4/summary.md | 129 +++++ 11 files changed, 1509 insertions(+), 1 deletion(-) create mode 100644 docs/benchmarks/2026-11-20-qwen36-m4/.gitignore create mode 100644 docs/benchmarks/2026-11-20-qwen36-m4/README.md create mode 100644 docs/benchmarks/2026-11-20-qwen36-m4/env.txt create mode 100644 docs/benchmarks/2026-11-20-qwen36-m4/extra.tar.xz create mode 100644 docs/benchmarks/2026-11-20-qwen36-m4/llama.cpp-build.txt create mode 100644 docs/benchmarks/2026-11-20-qwen36-m4/llama.cpp.diff create mode 100644 docs/benchmarks/2026-11-20-qwen36-m4/log.txt create mode 100644 docs/benchmarks/2026-11-20-qwen36-m4/logs.tar.xz create mode 100644 docs/benchmarks/2026-11-20-qwen36-m4/runs.csv create mode 100644 docs/benchmarks/2026-11-20-qwen36-m4/summary.md 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/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 0000000000000000000000000000000000000000..3c4d0297302651d18d222808d283d983095f8911 GIT binary patch literal 18572 zcmV(mK=Z%-H+ooF000E$*0e?hz{`*UfPg3=0UQ7T0002-*S_)T|NlrsT>vtk3eiP6 znrzUvv%1i15@=&>)9rkrX_jD=Jx0ITnEYB-3rX14iLoL9Ukw_uI3p0)JM;CmxTSA1 zNw!N%_jwbVNa0x!*)cqP4hNasw0LQ$y>FK4R;^)b9&nPQA`$#nVsF((Z9FiZ;EMY` z`jo!ju&nZf(L!Opjubg#gT*4QV(cxR*NHQfynK_TEc&q-L$7`x(~R^s(%`{Q#!rcH z-_ls?1;Z}jJq}dekpbKrQ(rFh5o2+Ug8i?Hkx<^=@=U(#ED-K$_pw^khKIp5VaKl_WKquJ>HZZZKw=WD(iq}#pat3TC2WC=5qhj8_tB($4X&*DD zV>O8>jdaGv8P+M94PwBYkbArdrDR$HaL-#}wRE$eM^{K4FGHCG_2(`H{yTq=cVAZ@ zn?0nUp74R9V@8pnGwK(C`tt_TcSMu6N=PwSz9!|)h6Ok9?%UI+Ka6G@E6yW;0_sM>JYo^OPKgMI9*$`n7 zH=OUvYR&9wi??j`?|oMV0_yk^QG_Wz!UoFYvXox>E^W?8y>w0;SY3Ob@eS}Icpxla zU(Pjewqnil_QjbPhVYcY3Jf=_DvW~1wu#(h_JaLgp8c%_rIFI;LqLc^DzAhIP16&> z*UgSxXk-W&YO zOr^x;fTdoOYO95EmRIuPd-dJ`7WAu3q)Htjtn4*PLyIlguT4?Wg@)I-R8oms-9~ae z!4>$S@GwW8zFu*{(!;zfq!4&1TM?@npdxb4MrCjmpE7CqxTx$eU`X~;?sJ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{h7H$Q1;MHr^sU0}Om&N&7UYG?>6}1H z$3mWDu=X57c#4gpg4{tb$6_?HVpUSt+MH0Bb2H?X^h1%@>yA!+|Or4QDFbq9nxXBe@|?>k041(3wGzD1G#NY3|I zsjU%+>$Fo-5l{1K8*|pd>s+IZDYR<33&_O(iRJX(*#?|$A}OAe7fPFI!HKhI`=@Py zIegvavtvOh7ELD6aV~1gUP*NqC6UlDA>ObV?JS8TEHZ&$WvK_ViD2@^#{&JpZ>2R( zE0sf^^5Mn66)wY<_p92S$Rq1bu?bt$c5=vz_4UX5XmYt;Ajkj!`i>5%{cFW)00HNa X0f2xgqm->qvBYQl0ssI200dcDtoj=r literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..9e384e8832b563e9101aa246c3c54352e260dafe GIT binary patch literal 129048 zcmV(jK=!}=H+ooF000E$*0e?hz|!vrfRK(2Apsl!0000%N6&!&|Gs3bT>v&4$r`iS z_Jj@QW8D+rD9vrpQ!ATeZo%IQo%9oTTQIk0Y*j%053e8*+Lwabr+(OB^GJh?Lj1FHhUU=7_wry?-pf75OyC z0$B6@_6%4PH|z*1Ikt>>WEm+}HvR}!Gu?yPC?#;fzG>)94{v0L)KMy(c|aG2;1yTz zC;@X72zp6;s_yrt*jTuNdcHbCFgeQ;$M{spLsdoM{JrP`q_O?@XvbQ$^ zRXEEh`smOp@x{ppPTHHN7<{XuCSt#ZLLT+3w@_lgpcbYq>e!Vb-a^3(e} zl?1i+6Q$NpoKiCocOLex-Sr)^_r}ZVwqm-{YG14%beIo^NHFrzU5Ay4I`HEDx7zpA!z}ri?Vv!I3+?lsm zbnCj9ZbC;o@7a1=-SD}UkkpM-U}^-+o(VrZ$#&fW>6yvYN*t?1)ceRj&#uacpooA1 z3Bama==3)jRcYy@-dU2P`9jX!Z_be*k!C2O%_gIgX>Jjy)H&m4u z-M}{e+-{%`&_Xk{2_2E*zgdQ~E$HN0);H1gOa&W9S*#JtsU9-LTi2n9Fh#SoJ0Y(B zV)03VN9{Sb@~>Rx6nNp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@Eq8{RS3H;`Q=SzS{RycTwuTd`jP($@wd z304E}dJ5!mK7i;lu`IUe7vTH^wb0;($Kq=F^?MZjjezt!&s7L4FHZMi?5HDw%6YPw z2Fc95+31R`n(2Iwy2oIRyj9eEzE79qL>Uo+islhaj&dM|%?_jX|K^^I`d>U&>AX(` zy&@=|b+O+x%6^p~>WTd;-DaDdFXb8jxJnc@`-5lU@qc54t*J`d-bF?I7EFxvkj>_1 zi9mB-INtxKc1WxcdoOVG@hQ*BL>hXK19g?E^GK#xrAj4C&mM6(fTWz%k-B>?=KN>?004i9GD}smW=8-4 d?(YYHkd6%i007ZR_7xNtJ1_$P00004Sz58MtM~u_ literal 0 HcmV?d00001 diff --git a/docs/benchmarks/2026-11-20-qwen36-m4/parse.py b/docs/benchmarks/2026-11-20-qwen36-m4/parse.py index dfb6847..3a5ee85 100755 --- a/docs/benchmarks/2026-11-20-qwen36-m4/parse.py +++ b/docs/benchmarks/2026-11-20-qwen36-m4/parse.py @@ -141,7 +141,7 @@ def read_rows(out): def write_csv(out, rows): with open(out / "runs.csv", "w", newline="") as f: - w = csv.DictWriter(f, list(rows[0].keys())) + 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()}) 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 | + From 5487a52cb90dae373ffdaa9344c4d8168f1d068c Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:16:04 -0800 Subject: [PATCH 38/60] qwen app: a draft rule for Qwen3.5/Qwen3.6 (#89) draft_length35 gives 1 draft token for a match of 2 to 11 tokens, 4 for 12 to 15, and 11 for MATCH_MAX (16). generate_with_drafts35 uses it, with no backoff after misses. The rule of arch 0 (draft_length) does not change. A round of Qwen3.6 costs about 25 ms for 1 position and 30 ms for 2, and then about 16 ms more for each 2 positions. So a draft of 1 token pays even at short matches, and only long matches pay for long drafts. A simulation of the draft loop replayed the greedy outputs of the 12 tuning prompts of docs/benchmarks/2026-11-20-qwen36-m4 (prompts/twelve only), with the measured cost of each round. It gives the counts of rounds, drafted and accepted tokens of the benchmark logs exactly. A search over the draft length for each range of match lengths found this rule. With each kind of prompt left out of the search, the search found the same rule, and the rule beat the old one on the kind left out. tests/generate_qwen35.vx: the round after the 12-token match now drafts 4 tokens. README: use --draft 11 with Qwen3.6. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- README.md | 3 ++- src/main.vx | 22 +++++----------------- src/speculate.vx | 20 ++++++++++++++++++++ tests/generate_qwen35.vx | 5 +++-- 4 files changed, 30 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 21094d4..937e9f2 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,8 @@ pip install -r requirements.txt 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. + `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. 1. Generate a few tokens with the NumPy reference. It prints the prompt as token ids: diff --git a/src/main.vx b/src/main.vx index 53d7378..62e927c 100644 --- a/src/main.vx +++ b/src/main.vx @@ -458,20 +458,14 @@ fn generate_with_drafts35(w : &Qwen35Weights, s : &mut Qwen35State, t : &Tokeniz let mut rounds = 0; let mut drafted = 0; let mut accepted = 0; - let mut misses = 0; - let mut missed_length = 0; 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(); + // 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 { @@ -532,12 +526,6 @@ fn generate_with_drafts35(w : &Qwen35Weights, s : &mut Qwen35State, t : &Tokeniz // before the first miss. commit_round35(w, s, &r, 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); diff --git a/src/speculate.vx b/src/speculate.vx index 7de9678..a7fe1b1 100644 --- a/src/speculate.vx +++ b/src/speculate.vx @@ -158,6 +158,26 @@ fn draft_length(length : i32) -> i32 { return 7; } +/// `draft_length` for Qwen3.5 and Qwen3.6 (arch 1): none below 2, 1 for 2 to 11, 4 for 12 to 15, +/// and 11 for MATCH_MAX. A round of these models costs about 25 ms for 1 position and 30 ms for 2, +/// and then about 16 ms more for each 2 positions, so a draft of 1 token pays at short matches. +/// A simulation of the draft loop on the greedy outputs of the 12 tuning prompts of +/// docs/benchmarks/2026-11-20-qwen36-m4 (prompts/twelve) found this rule best. With each kind of +/// prompt left out of the search, the search found the same rule, and it beat `draft_length` on +/// the kind left out. +fn draft_length35(length : i32) -> i32 { + if length < 2 { + return 0; + } + if length < 12 { + return 1; + } + if length < MATCH_MAX { + return 4; + } + return 11; +} + /// Up to `k` tokens of the context after position `end`. fn tokens_after(context : &Vec, end : i32, k : i32) -> Vec { let mut draft = Vec::new(); diff --git a/tests/generate_qwen35.vx b/tests/generate_qwen35.vx index 334a6b2..ac1066f 100644 --- a/tests/generate_qwen35.vx +++ b/tests/generate_qwen35.vx @@ -8,7 +8,8 @@ // past position 2,048, where its blocks take 64 SIMD groups for each head in place of 32. // - the Q4_0 file with --draft 7, against the same file without it: the lines of the steps must be // the same, logits too. The prompt repeats its first 10 tokens at its end, and the model gives -// 109 and 99 after it, as it did after their first copy, so a round of 7 draft tokens runs. +// 109 and 99 after it, as it did after their first copy. So the last 12 tokens match, and a round +// of 4 draft tokens runs (`draft_length35`). // - the Q4_0 file with --prompt-runs 3: a time for each run of the prompt, and the lines of the // steps of the file without it. // @@ -53,5 +54,5 @@ // LONG-BF16: 8 steps, same tokens, logits within 0.001 // LONG: 8 steps, same tokens, logits within 0.003 // STEPS: {{^}}32{{$}} -// DRAFT: rounds=1 drafted=7 accepted=0; +// DRAFT: rounds=1 drafted=4 accepted=0; // RUNS: {{^}}3{{$}} From 99967df053de750c9657ef9133fe7e7972a93b74 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:27:50 -0800 Subject: [PATCH 39/60] qwen35: run the shared expert at the same time as the router add_experts_shared now starts the SwiGLU of the shared expert first, because it needs only xn. The concurrent encoder puts a barrier only where a launch reads what an earlier one wrote. So the shared SwiGLU runs with the router, the shared gate with top-k, and the shared down product 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 give the same bits as one position (tests/round35.vx). docs/optimizations.md: entry 15, and a note that merging the norm into the router and the SwiGLUs was slower. Issue: #34 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- docs/optimizations.md | 29 ++++++++++++++++++++++++++--- src/qwen35.vx | 21 ++++++++++++++------- src/round35.vx | 6 ++++-- 3 files changed, 44 insertions(+), 12 deletions(-) diff --git a/docs/optimizations.md b/docs/optimizations.md index a181788..d0a7f93 100644 --- a/docs/optimizations.md +++ b/docs/optimizations.md @@ -317,6 +317,22 @@ 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. + ## 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,6 +356,12 @@ 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. @@ -351,9 +373,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/src/qwen35.vx b/src/qwen35.vx index 5e49016..3e5542d 100644 --- a/src/qwen35.vx +++ b/src/qwen35.vx @@ -172,25 +172,32 @@ fn shared_gate(out : &mut Tensor, logits : &Tensor, xn : &Tensor, shared_weight : &mut Tensor, shared_mlp : &mut Tensor, shared_id : &Tensor, layer : &Qwen35Layer, c : &Config) -> void { let k = c.experts_per_token; let inter = c.moe_intermediate_size; let shared = c.shared_expert_inter; - nn_matvec(&mut e.router_logits, &layer.router, xn, c.num_experts + 1, c.hidden_size); - nn_top_k(&mut e.ids, &mut e.weights, &e.router_logits, c.num_experts, k); - shared_gate(shared_weight, &e.router_logits, c.num_experts); if layer.gate_up.dtype == U4 { assert(layer.down.dtype == U4 && layer.shared_gate_up.dtype == U4 && layer.shared_down.dtype == U4, "the experts of a Qwen3.5 model must all be Q4_0, or all bf16"); - moe_swiglu_q4_blocks(&mut e.mlp, &layer.gate_up.codes, &layer.gate_up.group_scales, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); - moe_down_q4_add_blocks(x, &layer.down.codes, &layer.down.group_scales, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); moe_swiglu_q4_blocks(shared_mlp, &layer.shared_gate_up.codes, &layer.shared_gate_up.group_scales, shared_id, xn, 1, shared, c.hidden_size, 1); + nn_matvec(&mut e.router_logits, &layer.router, xn, c.num_experts + 1, c.hidden_size); + nn_top_k(&mut e.ids, &mut e.weights, &e.router_logits, c.num_experts, k); + shared_gate(shared_weight, &e.router_logits, c.num_experts); + moe_swiglu_q4_blocks(&mut e.mlp, &layer.gate_up.codes, &layer.gate_up.group_scales, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); moe_down_q4_add_blocks(x, &layer.shared_down.codes, &layer.shared_down.group_scales, shared_id, shared_weight, shared_mlp, 1, c.hidden_size, shared, 1); + moe_down_q4_add_blocks(x, &layer.down.codes, &layer.down.group_scales, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); } else { assert(layer.gate_up.dtype == BF16 && layer.down.dtype == BF16 && layer.shared_gate_up.dtype == BF16 && layer.shared_down.dtype == BF16, "the experts of a Qwen3.5 model must all be Q4_0, or all bf16"); - nn_moe_swiglu(&mut e.mlp, &layer.gate_up.bf16, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); - nn_moe_down_add(x, &layer.down.bf16, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); nn_moe_swiglu(shared_mlp, &layer.shared_gate_up.bf16, shared_id, xn, 1, shared, c.hidden_size, 1); + nn_matvec(&mut e.router_logits, &layer.router, xn, c.num_experts + 1, c.hidden_size); + nn_top_k(&mut e.ids, &mut e.weights, &e.router_logits, c.num_experts, k); + shared_gate(shared_weight, &e.router_logits, c.num_experts); + nn_moe_swiglu(&mut e.mlp, &layer.gate_up.bf16, &e.ids, xn, k, inter, c.hidden_size, c.num_experts); nn_moe_down_add(x, &layer.shared_down.bf16, shared_id, shared_weight, shared_mlp, 1, c.hidden_size, shared, 1); + nn_moe_down_add(x, &layer.down.bf16, &e.ids, &e.weights, &e.mlp, k, c.hidden_size, inter, c.num_experts); } return; } diff --git a/src/round35.vx b/src/round35.vx index c4dd934..785f2e2 100644 --- a/src/round35.vx +++ b/src/round35.vx @@ -692,13 +692,15 @@ fn run_round35(w : &Qwen35Weights, s : &mut Qwen35State, r : &mut Round35, token } add_rows(&mut r.x, &r.add, n, c.hidden_size); rms_norm_f32_rows(&mut r.xn, &r.x, &layer.mlp_norm, n, c.hidden_size, eps); + // The order of `add_experts_shared`: the shared expert is added to x before the chosen + // experts, so that the bits are the same as those of one position. + moe_swiglu_q4_blocks_rows(&mut r.shared_mlp, &layer.shared_gate_up.codes, &layer.shared_gate_up.group_scales, &r.shared_ids, &r.xn, n, 1, c.shared_expert_inter, c.hidden_size, 1); nn_matvec_rows(&mut r.router, &layer.router, &r.xn, n, c.num_experts + 1, c.hidden_size); nn_top_k_rows(&mut r.ids, &mut r.weights, &r.router, n, c.num_experts, k); shared_gate_rows(&mut r.shared_weight, &r.router, n, c.num_experts); moe_swiglu_q4_blocks_rows(&mut r.mlp, &layer.gate_up.codes, &layer.gate_up.group_scales, &r.ids, &r.xn, n, k, c.moe_intermediate_size, c.hidden_size, c.num_experts); - moe_down_q4_add_blocks_rows(&mut r.x, &layer.down.codes, &layer.down.group_scales, &r.ids, &r.weights, &r.mlp, n, k, c.hidden_size, c.moe_intermediate_size, c.num_experts); - moe_swiglu_q4_blocks_rows(&mut r.shared_mlp, &layer.shared_gate_up.codes, &layer.shared_gate_up.group_scales, &r.shared_ids, &r.xn, n, 1, c.shared_expert_inter, c.hidden_size, 1); moe_down_q4_add_blocks_rows(&mut r.x, &layer.shared_down.codes, &layer.shared_down.group_scales, &r.shared_ids, &r.shared_weight, &r.shared_mlp, n, 1, c.hidden_size, c.shared_expert_inter, 1); + moe_down_q4_add_blocks_rows(&mut r.x, &layer.down.codes, &layer.down.group_scales, &r.ids, &r.weights, &r.mlp, n, k, c.hidden_size, c.moe_intermediate_size, c.num_experts); l = l + 1; } rms_norm_f32_rows(&mut r.xn, &r.x, &w.final_norm, n, c.hidden_size, eps); From fb030aaf53c3a98eaba50a5ccf317cd47147585b Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:22:03 -0800 Subject: [PATCH 40/60] convert: write the MTP layer of Qwen3.6-35B-A3B A Qwen3.5 MoE model with mtp_num_hidden_layers = 1 now gets its MTP layer in the weight file: mtp.embed_norm, mtp.hidden_norm, mtp.fc, mtp.layers.0.* (the tensors of a layer with full attention) and mtp.final_norm. They come after all the other tensors, so these keep their order and bytes. A new config integer, mtp_layers, takes the next free slot of the version 2 header, so an older file reads 0. The norms hold 1 + w, as the other norms of the model. mtp.fc is a weight matrix, Q4_0 in a q4_0 file. An importance file need not have the MTP layer. make_tiny_model.py --qwen35 --mtp adds the layer to the tiny model, after its other weights, which do not change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- scripts/convert.py | 70 ++++++++++++++++++++++------------- scripts/make_tiny_model.py | 31 +++++++++++++--- scripts/qwen_weights.py | 61 +++++++++++++++++++++++++------ scripts/test_qwen_weights.py | 71 ++++++++++++++++++++++++++++++++++++ 4 files changed, 190 insertions(+), 43 deletions(-) diff --git a/scripts/convert.py b/scripts/convert.py index e8b96f5..475a1ad 100644 --- a/scripts/convert.py +++ b/scripts/convert.py @@ -57,23 +57,12 @@ def convert_qwen3_5(config, hf): 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"] - heads, head_dim, hidden = config["num_q_heads"], config["head_dim"], config["hidden_size"] - experts, moe_inter = config["num_experts"], config["moe_intermediate_size"] 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): - 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"] + 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")] @@ -84,22 +73,53 @@ def convert_qwen3_5(config, hf): 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"] - 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"] + 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.""" diff --git a/scripts/make_tiny_model.py b/scripts/make_tiny_model.py index 5f63149..c40c7a6 100644 --- a/scripts/make_tiny_model.py +++ b/scripts/make_tiny_model.py @@ -21,7 +21,8 @@ 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. +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. @@ -125,6 +126,9 @@ "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 @@ -236,8 +240,9 @@ def tiny_moe_model(): return tensors -def tiny_qwen35_model(): - """The tensors of the tiny Qwen3.5 MoE model, as bf16 bits with their Hugging Face names.""" +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"] @@ -247,8 +252,15 @@ def tiny_qwen35_model(): shared = c["shared_expert_intermediate_size"] src = "model.language_model." shapes = {src + "embed_tokens.weight": (c["vocab_size"], hidden)} - for layer, kind in enumerate(c["layer_types"]): - p = f"{src}layers.{layer}." + 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) @@ -277,6 +289,8 @@ def tiny_qwen35_model(): 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 @@ -324,6 +338,7 @@ def main(): 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("--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") @@ -331,8 +346,12 @@ def main(): 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" + assert not args.mtp or args.qwen35, "--mtp needs --qwen35" if args.moe or args.qwen35: - hf_config, hf = (MOE_CONFIG, tiny_moe_model()) if args.moe else (QWEN35_CONFIG, tiny_qwen35_model()) + 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, hf_config, hf) config, tensors = convert.convert_tensors(qwen_weights.config_from_json(hf_config), hf) diff --git a/scripts/qwen_weights.py b/scripts/qwen_weights.py index c26a355..88f02aa 100644 --- a/scripts/qwen_weights.py +++ b/scripts/qwen_weights.py @@ -72,6 +72,23 @@ `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 @@ -118,6 +135,7 @@ "conv_width", "rotary_dim", "shared_expert_intermediate_size", + "mtp_layers", ] # The integers that the header of each version has room for. CONFIG_INT_SLOTS = {1: 16, 2: 32} @@ -135,7 +153,7 @@ # 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", - "linear_in", "linear_out", "shared_gate_up", "shared_down") + "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. @@ -188,10 +206,12 @@ def has_full_attention(config, layer): return not config.get("arch", 0) or (layer + 1) % config["full_attention_interval"] == 0 -def layer_names(config, layer): - """The names of the tensors of one layer of an arch 1 model, in file order.""" - prefix = f"layers.{layer}." - if has_full_attention(config, layer): +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"] @@ -224,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): @@ -234,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"] @@ -266,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] @@ -281,9 +314,11 @@ def tensor_shapes(config): return shapes -def arch1_layer_shapes(config, layer): - """The shape of each tensor of one layer of an arch 1 model, by name.""" - prefix = f"layers.{layer}." +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"] @@ -298,7 +333,7 @@ def arch1_layer_shapes(config, layer): } if shared: shapes.update(shared_gate_up=(2 * shared, hidden), shared_down=(hidden, shared)) - if has_full_attention(config, layer): + if full: shapes.update( qkv=(2 * q_heads * head_dim + 2 * config["num_kv_heads"] * head_dim, hidden), q_norm=(head_dim,), @@ -680,8 +715,9 @@ def quantize(config, tensors, weight_format, importance=None): tensors[name + ".scale"] = lambda part=parts[2]: ("f16", part()) continue if dtype == "u4": - assert importance is None or name in importance, f"the importance file has no {name}" - weights = None if importance is None else importance[name] + # An importance file need not have the MTP layer, which importance.py does not run. + assert importance is None or name in importance or name.startswith("mtp."), f"the importance file has no {name}" + weights = None if importance is None else importance.get(name) quantizer, scale_dtype = (lambda matrix, weights=weights: quantize_q4_0(matrix, weights)), "f16" else: quantizer, scale_dtype = quantize_fp8, "f32" @@ -760,7 +796,7 @@ def config_from_json(hf): def config_from_qwen3_5(hf): """The config of the weight file, from the `config.json` of a Qwen3.5 MoE model, such as - Qwen3.6-35B-A3B. The file keeps only the text model: no vision tower and no MTP layer.""" + Qwen3.6-35B-A3B. The file keeps only the text model and its MTP layer: no vision tower.""" text = hf["text_config"] assert text["model_type"] == "qwen3_5_moe_text", f"text model_type {text['model_type']}" interval = text["full_attention_interval"] @@ -802,6 +838,7 @@ def config_from_qwen3_5(hf): # it is plain RoPE on the first rotary_dim values of each head. "rotary_dim": int(head_dim * rope.get("partial_rotary_factor", 1.0)), "shared_expert_intermediate_size": text["shared_expert_intermediate_size"], + "mtp_layers": text.get("mtp_num_hidden_layers", 0), "rope_theta": float(rope["rope_theta"]), "rms_norm_eps": float(text["rms_norm_eps"]), } diff --git a/scripts/test_qwen_weights.py b/scripts/test_qwen_weights.py index e8c74ac..071aed3 100644 --- a/scripts/test_qwen_weights.py +++ b/scripts/test_qwen_weights.py @@ -474,5 +474,76 @@ def test_the_bf16_file_holds_the_hugging_face_tensors_in_its_order(self): 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=" Date: Sun, 22 Nov 2026 02:44:53 -0800 Subject: [PATCH 41/60] qwen app: drafts from the MTP layer of Qwen3.6 (--mtp K) With a weight file that has the MTP layer, --mtp K drafts up to K tokens with it and checks them with the round kernels of --draft, so the text is the same as without --mtp. src/mtp35.vx has the MTP layer. Row p takes h of position p, after final_norm, and the token of position p + 1, and its attention has its own KV cache with row p at position p. The prompt fills the rows one chunk at a time after each chunk of the model. A draft runs one row (mtp35_step) from the last token and h, and each later draft from the h of the MTP layer itself. After a round, the rows of the kept tokens run again with the true h of the model from the round. A draft scores only the 65,536 tokens of the lowest ids (--mtp-vocab changes this), 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: a round of 2 positions costs little more than a plain step, but 3 or 4 positions cost a second pass of the round kernels. weights.vx loads the MTP layer when the config has mtp_layers = 1, with load_qwen35_layer for the layers of the model too. tests/generate_qwen35.vx: on the tiny model with the MTP layer and a prompt of 2 chunks, --mtp 3 gives the steps of the file without the layer, logits too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- README.md | 7 + src/main.vx | 214 ++++++++++++++++++++++++++++++- src/mtp35.vx | 267 +++++++++++++++++++++++++++++++++++++++ src/weights.vx | 216 ++++++++++++++++++------------- tests/generate_qwen35.vx | 14 ++ 5 files changed, 622 insertions(+), 96 deletions(-) create mode 100644 src/mtp35.vx diff --git a/README.md b/README.md index 8b0ebd4..0513f3a 100644 --- a/README.md +++ b/README.md @@ -110,6 +110,13 @@ pip install -r requirements.txt 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 `--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. + 1. Generate a few tokens with the NumPy reference. It prints the prompt as token ids: ```sh diff --git a/src/main.vx b/src/main.vx index 1c464a0..b178108 100644 --- a/src/main.vx +++ b/src/main.vx @@ -30,6 +30,7 @@ import std::time; import std::vec; import qwen::weights; import qwen::model; +import qwen::mtp35; import qwen::qwen35; import qwen::prefill35; import qwen::prefill; @@ -63,6 +64,10 @@ struct Options { lines : bool, draft : *const i8, has_draft : bool, + mtp : *const i8, + has_mtp : bool, + mtp_vocab : *const i8, + has_mtp_vocab : bool, think : bool, ignore_eos : bool, prompt_runs : *const i8, @@ -76,7 +81,7 @@ fn parse_options(argc : i32, argv : *mut *mut i8) -> Options { 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, think: false, ignore_eos: false, prompt_runs: empty, has_prompt_runs: 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, mtp: empty, has_mtp: false, mtp_vocab: empty, has_mtp_vocab: false, think: false, ignore_eos: false, prompt_runs: empty, has_prompt_runs: false, }; let mut i = 2; while i < argc { @@ -123,6 +128,12 @@ fn parse_options(argc : i32, argv : *mut *mut i8) -> Options { } else if same(name, "--draft") { o.draft = value; o.has_draft = true; + } else if same(name, "--mtp") { + o.mtp = value; + o.has_mtp = true; + } else if same(name, "--mtp-vocab") { + o.mtp_vocab = value; + o.has_mtp_vocab = true; } else if same(name, "--prompt-runs") { o.prompt_runs = value; o.has_prompt_runs = true; @@ -544,11 +555,165 @@ fn generate_with_drafts35(w : &Qwen35Weights, s : &mut Qwen35State, t : &Tokeniz 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 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(w : &Qwen35Weights, s : &mut Qwen35State, m : &mut Mtp35State, t : &Tokenizer, eos : i32, text_mode : bool, prompt : &Vec, first : i32, steps : i32, max : 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"); + 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; + // 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(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); + step = 1; + pos = pos + 1; + going = show(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. + let mut warm = Vec::new(); + for n in 1..max + 2 { + 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 rounds = 0; + let mut drafted = 0; + let mut accepted = 0; + let mut kept : f64 = MTP_LONG_SHARE; + while going && step + 1 < steps { + let room = steps - step - 1; + let want = if kept >= MTP_LONG_SHARE { + max + } else { + 1 + }; + let k = 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); + step = step + 1; + pos = pos + 1; + let mut logit : f32 = 0.0; + if !text_mode { + logit = read_logit(&s.logits, token); + } + going = show(t, eos, text_mode, step, token, logit); + } else { + // Draft j + 1, from row pos - 1 + j of the MTP layer, goes to slots[j]. + m.token = upload_token(token); + for j in 0..k { + mtp35_step(w, s, m, pos - 1 + j, true, vocab); + copy_token(&mut slots[j].next, &m.token); + } + let mut draft = Vec::new(); + 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; + let mut j = 0; + let mut more = true; + while more && going { + token = choice[j]; + step = step + 1; + let mut logit : f32 = 0.0; + if !text_mode { + logit = round_logit(&r.logits, j, token); + } + going = show(t, eos, text_mode, step, token, logit); + more = j < k && draft[j] == token; + if more { + accepted = accepted + 1; + j = j + 1; + kept = kept * 0.9 + 0.1; + } else if j < k { + 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 - 1 then run with the true h of positions pos to pos + j - 1 + // and the kept drafts; h of position pos + j is the input of the next round. + commit_round35(w, s, &r, j + 1); + for i in 0..j { + take_row(&mut m.h, &r.xn, i, c.hidden_size); + m.token = upload_token(draft[i]); + mtp35_step(w, s, m, pos + i, false, vocab); + } + take_row(&mut m.h, &r.xn, j, c.hidden_size); + pos = pos + j + 1; + } + } + 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(path : *const i8, t : &Tokenizer, text_mode : bool, chat : bool, ignore_eos : bool, prompt : &Vec, steps : i32, draft : i32, runs : i32) -> i32 { +fn run_qwen35(path : *const i8, t : &Tokenizer, text_mode : bool, chat : bool, ignore_eos : bool, prompt : &Vec, steps : i32, draft : i32, mtp : i32, mtp_vocab : i32, runs : i32) -> i32 { let w = load_qwen35_weights(path); let eos = if ignore_eos { -1 @@ -600,7 +765,18 @@ fn run_qwen35(path : *const i8, t : &Tokenizer, text_mode : bool, chat : bool, i warm_prompt.push(prompt[i]); } let mut warm = new_qwen35_state(&w.config, warm_prompt.len()); - prefill_qwen35_with(&w, &mut warm, &mut p, &warm_prompt); + // 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(); @@ -610,7 +786,14 @@ fn run_qwen35(path : *const i8, t : &Tokenizer, text_mode : bool, chat : bool, i s = new_qwen35_state(&w.config, count + steps); } let prompt_start = Instant::now(); - prefill_qwen35_with(&w, &mut s, &mut p, prompt); + 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)); @@ -621,11 +804,20 @@ fn run_qwen35(path : *const i8, t : &Tokenizer, text_mode : bool, chat : bool, i } let mut start = Instant::now(); let mut decoded = 0; + assert(draft == 0 || mtp == 0, "give --draft or --mtp, not both"); if draft > 0 { decoded = generate_with_drafts35(&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(&w, &mut s, &mut m, t, eos, text_mode, prompt, tokens[0], steps, mtp, vocab, &mut start); + } for step in 0..steps { - if draft > 0 { + if draft > 0 || mtp > 0 { break; } let token = tokens[step]; @@ -703,7 +895,17 @@ fn main(argc : i32, argv : *mut *mut i8) -> i32 { 1 }; assert(runs >= 1, "--prompt-runs must be at least 1"); - return run_qwen35(o.weights, &t, text_mode, o.chat, o.ignore_eos, &prompt, steps, draft, runs); + let mtp = if o.has_mtp { + parse_numbers(o.mtp)[0] + } else { + 0 + }; + let mtp_vocab = if o.has_mtp_vocab { + parse_numbers(o.mtp_vocab)[0] + } else { + 0 + }; + return run_qwen35(o.weights, &t, text_mode, o.chat, o.ignore_eos, &prompt, steps, draft, mtp, mtp_vocab, runs); } assert(!o.has_prompt_runs, "--prompt-runs needs a Qwen3.5 or Qwen3.6 file"); let w = load_weights(o.weights); diff --git a/src/mtp35.vx b/src/mtp35.vx new file mode 100644 index 0000000..d51f233 --- /dev/null +++ b/src/mtp35.vx @@ -0,0 +1,267 @@ +//===- mtp35.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 multi-token prediction (MTP) layer of Qwen3.6-35B-A3B, for drafts. Row p of the MTP layer +// takes the hidden state h_p of position p (after final_norm) and the token of position p + 1, +// and predicts the token of position p + 2. Its attention has its own KV cache, with row p at +// position p. (llama.cpp puts the row at position p + 1. RoPE gives the same scores for both, +// because it depends only on the distance of two positions.) +// +// The prompt fills rows 0 to count - 2 of the KV cache, a chunk at a time, after each chunk of +// the model (`prefill_qwen35_mtp`). A draft then runs one row with `mtp35_step`: the first draft +// after token t at position p takes h_{p - 1} of the model, and each later draft the h of the +// MTP layer itself. When a round keeps tokens, rows of the true h of the model go over the rows +// of the drafts. The drafts only choose what a round checks, so they do not change the text. +import core::convert; +import core::num; +import std::nn; +import std::vec; +import qwen::gated_attention; +import qwen::model; +import qwen::prefill; +import qwen::prefill35; +import qwen::products; +import qwen::qwen35; +import qwen::weights; + +/// The state of the MTP layer: its KV cache, and `token` and `h`, the inputs of the next row. +/// `cat` holds the two norms of a row, the embedding first, for `fc`. +struct Mtp35State { + k : Tensor, + v : Tensor, + token : Tensor, + h : Tensor, + cat : Tensor, +} + +/// The MTP state for the `max_seq` positions of `s`. +fn new_mtp35_state(c : &Config, max_seq : i32) -> Mtp35State { + assert(c.mtp_layers == 1, "new_mtp35_state: the weight file has no MTP layer"); + let rows = (max_seq + 63) / 64 * 64; + return Mtp35State { + k: transfer(Tensor([rows, c.num_kv_heads, 256]), Memory::HBM), + v: transfer(Tensor([rows, c.num_kv_heads, 256]), Memory::HBM), + token: transfer(Tensor([1]), Memory::HBM), + h: transfer(Tensor([c.hidden_size]), Memory::HBM), + cat: transfer(Tensor([2 * c.hidden_size]), Memory::HBM), + }; +} + +/// A state of one value in each tensor, for a program without --mtp. +fn new_mtp35_state_none() -> Mtp35State { + return Mtp35State { + k: transfer(Tensor([1, 1, 1]), Memory::HBM), + v: transfer(Tensor([1, 1, 1]), Memory::HBM), + token: transfer(Tensor([1]), Memory::HBM), + h: transfer(Tensor([1]), Memory::HBM), + cat: transfer(Tensor([1]), Memory::HBM), + }; +} + +/// y[0] = x[0]: a copy of a token in GPU memory. +fn copy_token(y : &mut Tensor, x : &Tensor) -> void { + spawn on(Topology::Device) { + for b in 0..1 across blocks { + for l in 0..32 across lanes { + if l == 0 { + y[0] = x[0]; + } + } + } + } + return; +} + +/// y[i] = x[i], for i below n. +fn copy_f32(y : &mut Tensor, x : &Tensor, n : i32) -> void { + assert(y.len() >= n && x.len() >= n, "copy_f32: a tensor has fewer than n values"); + spawn on(Topology::Device) { + for b in 0..(n + 255) / 256 across blocks { + for l in 0..256 across lanes { + let i = b * 256 + l; + if i < n { + y[i] = x[i]; + } + } + } + } + return; +} + +/// y[at + i] = the RMSNorm of x times w, for i below n: `rms_norm_f32` into a part of y. +fn rms_norm_f32_at(y : &mut Tensor, at : i32, x : &Tensor, w : &Tensor, n : i32, eps : f32) -> void { + assert(n > 0 && at >= 0 && y.len() >= at + n && x.len() >= n && w.len() >= n, "rms_norm_f32_at: a tensor has too few values"); + spawn on(Topology::Device) { + for b in 0..1 across blocks { + let mut part = unsafe { Tensor::uninit() }; + for l in 0..1024 across lanes { + let mut s : f32 = 0.0; + let mut i = l; + while i < n { + s = s + x[i] * x[i]; + i = i + 1024; + } + part[l] = s; + } + let ss = lanes::sum(&part, 1024); + let inv = 1.0 / (ss / (n as f32) + eps).sqrt(); + for l in 0..1024 across lanes { + for j in 0..(n + 1023) / 1024 { + let i = j * 1024 + l; + if i < n { + y[at + i] = x[i] * inv * w[i]; + } + } + } + } + } + return; +} + +/// y[t][at + i] = the RMSNorm of x[t] times w, for t below n and i below dim: `pf35_rms_norm` into +/// a part of each row of y. +fn pf35_rms_norm_at(y : &mut Tensor, at : i32, x : &Tensor, w : &Tensor, n : i32, dim : i32, eps : f32) -> void { + assert(n > 0 && at >= 0 && y.extent(0) >= n && y.extent(1) >= at + dim && x.extent(0) >= n && x.extent(1) >= dim, "pf35_rms_norm_at: a tensor has too few values"); + spawn on(Topology::Device) { + for t in 0..n across blocks { + let mut part = unsafe { Tensor::uninit() }; + for l in 0..1024 across lanes { + let mut s : f32 = 0.0; + let mut i = l; + while i < dim { + s = s + x[t][i] * x[t][i]; + i = i + 1024; + } + part[l] = s; + } + let ss = lanes::sum(&part, 1024); + let inv = 1.0 / (ss / (dim as f32) + eps).sqrt(); + for l in 0..1024 across lanes { + for j in 0..(dim + 1023) / 1024 { + let i = j * 1024 + l; + if i < dim { + y[t][at + i] = x[t][i] * inv * w[i]; + } + } + } + } + } + return; +} + +/// Row `pos` of the MTP layer: the token in `m.token` and the h in `m.h`. The row goes to the KV +/// cache of the MTP layer, and its output h to `m.h`. With `predict`, `m.token` gets the token +/// that the row predicts, for position pos + 2, so m.token and m.h are then the inputs of the next +/// draft. The prediction is among tokens 0 to vocab - 1 only: the first rows of lm_head, which a +/// BPE vocabulary gives to its most frequent tokens. The row uses the scratch tensors of `s` (x, xn, proj, y, q, parts, the experts and +/// logits), but not its KV caches or states. +fn mtp35_step(w : &Qwen35Weights, s : &mut Qwen35State, m : &mut Mtp35State, pos : i32, predict : bool, vocab : i32) -> void { + let c = &w.config; + let eps = c.rms_norm_eps as f32; + let hidden = c.hidden_size; + let qkv_rows = (2 * c.num_q_heads + 2 * c.num_kv_heads) * 256; + assert(w.mtp.len() == 1 && pos >= 0 && pos < s.max_seq, "mtp35_step: the model needs an MTP layer, and the row must fit in the KV cache"); + assert(vocab >= 8 && vocab % 8 == 0 && vocab <= c.vocab_size, "mtp35_step: vocab must be a multiple of 8, up to the vocabulary of the model"); + let mtp = &w.mtp[0]; + let layer = &mtp.layer; + nn_embed(&mut s.x, &w.embed, &m.token, hidden); + rms_norm_f32_at(&mut m.cat, 0, &s.x, &mtp.embed_norm, hidden, eps); + rms_norm_f32_at(&mut m.cat, hidden, &m.h, &mtp.hidden_norm, hidden, eps); + matvec(&mut s.x, &mtp.fc, &m.cat, hidden, 2 * hidden); + rms_norm_f32(&mut s.xn, &s.x, &layer.attn_norm, hidden, eps); + matvec(&mut s.proj, &layer.qkv, &s.xn, qkv_rows, hidden); + gated_norm_rope_and_store(&mut s.q, &mut m.k, &mut m.v, &s.proj, &layer.q_norm, &layer.k_norm, &s.cos, &s.sin, pos, c.num_q_heads, c.num_kv_heads, c.rotary_dim, eps); + gated_attention(&mut s.y, &mut s.parts, &s.q, &m.k, &m.v, &s.proj, pos, c.num_q_heads, c.num_kv_heads); + matvec_add(&mut s.x, &layer.attn_out, &s.y, hidden, c.num_q_heads * 256); + rms_norm_f32(&mut s.xn, &s.x, &layer.mlp_norm, hidden, eps); + add_experts_shared(&mut s.experts, &mut s.x, &s.xn, &mut s.shared_weight, &mut s.shared_mlp, &s.shared_id, layer, c); + rms_norm_f32(&mut m.h, &s.x, &mtp.final_norm, hidden, eps); + if predict { + matvec(&mut s.logits, &w.lm_head, &m.h, vocab, hidden); + nn_argmax(&mut m.token, &s.logits, vocab); + } + return; +} + +/// Rows start to start + n - 1 of the MTP layer, after `pf35_chunk` ran positions start to +/// start + n - 1 of the prompt: the hidden states of the model are in p.x, and `next_tokens` has +/// the token after each, prompt[start + 1] to prompt[start + n]. `cat` is [rows of p.x, 2 * +/// hidden]. The rows go to the KV cache of the MTP layer; p.x, p.xn and the other tensors of the +/// chunk get other values. +fn pf35_mtp_chunk(w : &Qwen35Weights, s : &Qwen35State, m : &mut Mtp35State, p : &mut Prefill35, cat : &mut Tensor, next_tokens : &Tensor, start : i32, n : i32) -> void { + let c = &w.config; + let eps = c.rms_norm_eps as f32; + let hidden = c.hidden_size; + let tiles = (n + 15) / 16; + let qkv_rows = (2 * c.num_q_heads + 2 * c.num_kv_heads) * 256; + let mtp = &w.mtp[0]; + let layer = &mtp.layer; + pf35_rms_norm(&mut p.xn, &p.x, &w.final_norm, n, hidden, eps); + pf35_rms_norm_at(cat, hidden, &p.xn, &mtp.hidden_norm, n, hidden, eps); + pf_embed(&mut p.x, &w.embed, next_tokens, n, hidden); + pf35_rms_norm_at(cat, 0, &p.x, &mtp.embed_norm, n, hidden, eps); + pf35_mm(&mut p.x, &mtp.fc, cat, &p.rows, &p.zeros, &p.no_bias, hidden, 2 * hidden, tiles); + pf35_rms_norm(&mut p.xn, &p.x, &layer.attn_norm, n, hidden, eps); + pf35_mm(&mut p.proj, &layer.qkv, &p.xn, &p.rows, &p.zeros, &p.no_bias, qkv_rows, hidden, tiles); + pf_gated_norm_rope_and_store(&mut p.q, &mut m.k, &mut m.v, &p.proj, &layer.q_norm, &layer.k_norm, &s.cos, &s.sin, start, n, c.num_q_heads, c.num_kv_heads, c.rotary_dim, eps); + pf_gated_flash_attention(&mut p.y, &p.q, &m.k, &m.v, &p.proj, start, n, c.num_q_heads, c.num_q_heads / c.num_kv_heads, qkv_rows - c.num_q_heads * 256, 0.0625); + pf35_mm(&mut p.xn, &layer.attn_out, &p.y, &p.rows, &p.zeros, &p.no_bias, hidden, c.num_q_heads * 256, tiles); + pf35_add_rms_norm(&mut p.x, &mut p.xn, &layer.mlp_norm, n, hidden, eps); + pf35_experts(p, layer, c, n, tiles); + return; +} + +/// `prefill_qwen35_with`, and rows 0 to count - 2 of the MTP layer. After it, `s.xn` holds no +/// value that a later step reads; `predict_qwen35` gives h of the last position in s.xn. +fn prefill_qwen35_mtp(w : &Qwen35Weights, s : &mut Qwen35State, m : &mut Mtp35State, p : &mut Prefill35, prompt : &Vec) -> void { + let c = &w.config; + let count = prompt.len(); + assert(count > 0 && count <= s.max_seq, "prefill_qwen35_mtp: the prompt must have tokens and fit in the state"); + let chunk = p.tokens.len(); + let mut cat = transfer(Tensor([p.x.extent(0), 2 * c.hidden_size]), Memory::HBM); + let mut start = 0; + while start < count { + let n = i32::min(chunk, count - start); + let mut ids = Tensor([chunk]); + let mut after = Tensor([chunk]); + let mut rows = Tensor([p.rows.len()]); + for t in 0..p.rows.len() { + rows[t] = -1; + if t < n { + rows[t] = t; + } + } + for t in 0..chunk { + ids[t] = 0; + after[t] = 0; + if t < n { + ids[t] = prompt[start + t]; + } + if start + t + 1 < count && t < n { + after[t] = prompt[start + t + 1]; + } + } + p.tokens = transfer(ids, Memory::HBM); + p.rows = transfer(rows, Memory::HBM); + pf35_chunk(w, s, p, start, n); + if start + n == count { + pf_take_row(&mut s.x, &p.x, n - 1, c.hidden_size); + } + // The last position of the prompt has no token after it yet: its row is the first draft. + let mtp_rows = if start + n == count { + n - 1 + } else { + n + }; + if mtp_rows > 0 { + let next_tokens = transfer(after, Memory::HBM); + pf35_mtp_chunk(w, s, m, p, &mut cat, &next_tokens, start, mtp_rows); + } + start = start + n; + } + return; +} diff --git a/src/weights.vx b/src/weights.vx index 771f24c..b2c2f3c 100644 --- a/src/weights.vx +++ b/src/weights.vx @@ -83,6 +83,8 @@ struct Config { shared_expert_inter : i32, // RoPE turns the first rotary_dim values of each head: head_dim in a version 1 file. rotary_dim : i32, + // The MTP layers of an arch 1 model: 0 or 1, and 0 in a file without them. + mtp_layers : i32, rope_theta : f64, rms_norm_eps : f64, } @@ -166,13 +168,27 @@ struct Qwen35Layer { shared_down : WeightMatrix, } -/// All the weights of an arch 1 model, in GPU memory. +/// The multi-token prediction (MTP) layer of an arch 1 model, which predicts the token after the +/// next one. Its input is the embedding of a token and the hidden state h of the position before +/// it, after final_norm. `fc` takes the two norms, the embedding first, and `layer` has full +/// attention. The norms hold 1 + w, as those of a layer. +struct Mtp35 { + embed_norm : Tensor, + hidden_norm : Tensor, + fc : WeightMatrix, + layer : Qwen35Layer, + final_norm : Tensor, +} + +/// All the weights of an arch 1 model, in GPU memory. `mtp` has the MTP layer of a file with +/// mtp_layers = 1, and is empty otherwise. struct Qwen35Weights { config : Config, embed : Tensor, layers : Vec, final_norm : Tensor, lm_head : WeightMatrix, + mtp : Vec, } /// A weight file mapped into memory, and the position of the next tensor to load. @@ -422,12 +438,14 @@ fn read_config(r : &Reader) -> Config { conv_width: v2_int(r, 22, 0), shared_expert_inter: v2_int(r, 24, 0), rotary_dim: v2_int(r, 23, head_dim), + mtp_layers: v2_int(r, 25, 0), rope_theta: unsafe { floats[floats_at] }, rms_norm_eps: unsafe { floats[floats_at + 1] }, }; assert(config.weight_format >= FORMAT_BF16 && config.weight_format <= FORMAT_Q4_0_Q6, "the weight file has an unknown weight format"); assert(config.num_experts == 0 || (config.experts_per_token > 0 && config.experts_per_token <= config.num_experts), "a model must use between 1 and all of its experts for each token"); assert((r.version == VERSION_2) == (config.arch == ARCH_QWEN35), "an arch 1 model needs a version 2 file, and only it"); + assert(config.mtp_layers == 0 || config.mtp_layers == 1, "a model can have at most one MTP layer"); return config; } @@ -456,105 +474,123 @@ fn load_qwen35_weights(path : *const i8) -> Qwen35Weights { assert(config.linear_k_heads > 0 && config.linear_v_heads % config.linear_k_heads == 0, "each key head of a Gated DeltaNet must serve the same number of value heads"); assert(!config.tied_embeddings, "a Qwen3.5 MoE weight file has its own lm_head"); let hidden = config.hidden_size; - let head_dim = config.head_dim; - let heads = config.num_q_heads; - let k_total = config.linear_k_heads * config.linear_k_dim; - let v_heads = config.linear_v_heads; - let v_total = v_heads * config.linear_v_dim; - let experts = config.num_experts; - let moe_inter = config.moe_intermediate_size; - let shared = config.shared_expert_inter; let dtype = matrix_dtype(config.weight_format, false); let embed = load_next(&mut r, "embed", config.vocab_size, hidden); let mut layers = Vec::new(); for l in 0..config.num_layers { - // The tensors come in file order: those of the attention or the Gated DeltaNet, then those - // of the experts. - let full = (l + 1) % config.full_attention_interval == 0; - let attn_norm = load_scales(&mut r, ".attn_norm", hidden, 0); - let qkv = if full { - load_matrix(&mut r, dtype, ".qkv", ".qkv.scale", 2 * heads * head_dim + 2 * config.num_kv_heads * head_dim, hidden) - } else { - empty_matrix() - }; - let q_norm = if full { - load_scales(&mut r, ".q_norm", head_dim, 0) - } else { - zero_scales(8) - }; - let k_norm = if full { - load_scales(&mut r, ".k_norm", head_dim, 0) - } else { - zero_scales(8) - }; - let attn_out = if full { - load_matrix(&mut r, dtype, ".attn_out", ".attn_out.scale", hidden, heads * head_dim) - } else { - empty_matrix() - }; - let linear_in = if full { - empty_matrix() - } else { - load_matrix(&mut r, dtype, ".linear_in", ".linear_in.scale", 2 * k_total + 2 * v_total + 2 * v_heads, hidden) - }; - let conv = if full { - zero_scales(8) - } else { - load_scales(&mut r, ".conv", 2 * k_total + v_total, config.conv_width) - }; - let neg_a = if full { - zero_scales(8) - } else { - load_scales(&mut r, ".neg_A", v_heads, 0) - }; - let dt_bias = if full { - zero_scales(8) - } else { - load_scales(&mut r, ".dt_bias", v_heads, 0) - }; - let linear_norm = if full { - zero_scales(8) - } else { - load_scales(&mut r, ".linear_norm", config.linear_v_dim, 0) - }; - let linear_out = if full { - empty_matrix() - } else { - load_matrix(&mut r, dtype, ".linear_out", ".linear_out.scale", hidden, v_total) - }; - let mlp_norm = load_scales(&mut r, ".mlp_norm", hidden, 0); - let router = load_next(&mut r, ".router", experts + 1, hidden); - let gate_up = load_matrix(&mut r, dtype, ".experts_gate_up", ".experts_gate_up.scale", experts * 2 * moe_inter, hidden); - let down = load_matrix(&mut r, dtype, ".experts_down", ".experts_down.scale", experts * hidden, moe_inter); - let shared_gate_up = load_matrix(&mut r, dtype, ".shared_gate_up", ".shared_gate_up.scale", 2 * shared, hidden); - let shared_down = load_matrix(&mut r, dtype, ".shared_down", ".shared_down.scale", hidden, shared); - layers.push(Qwen35Layer { - full_attention: full, - attn_norm: attn_norm, - qkv: qkv, - q_norm: q_norm, - k_norm: k_norm, - attn_out: attn_out, - linear_in: linear_in, - conv: conv, - neg_a: neg_a, - dt_bias: dt_bias, - linear_norm: linear_norm, - linear_out: linear_out, - mlp_norm: mlp_norm, - router: router, - gate_up: gate_up, - down: down, - shared_gate_up: shared_gate_up, - shared_down: shared_down, - }); + layers.push(load_qwen35_layer(&mut r, &config, dtype, (l + 1) % config.full_attention_interval == 0)); } let final_norm = load_scales(&mut r, "final_norm", hidden, 0); let lm_head = load_matrix(&mut r, matrix_dtype(config.weight_format, true), "lm_head", "lm_head.scale", config.vocab_size, hidden); + let mut mtp = Vec::new(); + if config.mtp_layers == 1 { + let embed_norm = load_scales(&mut r, "mtp.embed_norm", hidden, 0); + let hidden_norm = load_scales(&mut r, "mtp.hidden_norm", hidden, 0); + let fc = load_matrix(&mut r, dtype, "mtp.fc", "mtp.fc.scale", hidden, 2 * hidden); + let layer = load_qwen35_layer(&mut r, &config, dtype, true); + mtp.push(Mtp35 { + embed_norm: embed_norm, + hidden_norm: hidden_norm, + fc: fc, + layer: layer, + final_norm: load_scales(&mut r, "mtp.final_norm", hidden, 0), + }); + } assert(r.next == r.count, "the weight file has more tensors than the config needs"); close_weight_file(&r); return Qwen35Weights { - config: config, embed: embed, layers: layers, final_norm: final_norm, lm_head: lm_head + config: config, embed: embed, layers: layers, final_norm: final_norm, lm_head: lm_head, mtp: mtp + }; +} + +/// Loads the next layer of an arch 1 model, with full attention or a Gated DeltaNet. The tensors +/// come in file order: those of the attention or the Gated DeltaNet, then those of the experts. +fn load_qwen35_layer(r : &mut Reader, config : &Config, dtype : i64, full : bool) -> Qwen35Layer { + let hidden = config.hidden_size; + let head_dim = config.head_dim; + let heads = config.num_q_heads; + let k_total = config.linear_k_heads * config.linear_k_dim; + let v_heads = config.linear_v_heads; + let v_total = v_heads * config.linear_v_dim; + let experts = config.num_experts; + let moe_inter = config.moe_intermediate_size; + let shared = config.shared_expert_inter; + let attn_norm = load_scales(r, ".attn_norm", hidden, 0); + let qkv = if full { + load_matrix(r, dtype, ".qkv", ".qkv.scale", 2 * heads * head_dim + 2 * config.num_kv_heads * head_dim, hidden) + } else { + empty_matrix() + }; + let q_norm = if full { + load_scales(r, ".q_norm", head_dim, 0) + } else { + zero_scales(8) + }; + let k_norm = if full { + load_scales(r, ".k_norm", head_dim, 0) + } else { + zero_scales(8) + }; + let attn_out = if full { + load_matrix(r, dtype, ".attn_out", ".attn_out.scale", hidden, heads * head_dim) + } else { + empty_matrix() + }; + let linear_in = if full { + empty_matrix() + } else { + load_matrix(r, dtype, ".linear_in", ".linear_in.scale", 2 * k_total + 2 * v_total + 2 * v_heads, hidden) + }; + let conv = if full { + zero_scales(8) + } else { + load_scales(r, ".conv", 2 * k_total + v_total, config.conv_width) + }; + let neg_a = if full { + zero_scales(8) + } else { + load_scales(r, ".neg_A", v_heads, 0) + }; + let dt_bias = if full { + zero_scales(8) + } else { + load_scales(r, ".dt_bias", v_heads, 0) + }; + let linear_norm = if full { + zero_scales(8) + } else { + load_scales(r, ".linear_norm", config.linear_v_dim, 0) + }; + let linear_out = if full { + empty_matrix() + } else { + load_matrix(r, dtype, ".linear_out", ".linear_out.scale", hidden, v_total) + }; + let mlp_norm = load_scales(r, ".mlp_norm", hidden, 0); + let router = load_next(r, ".router", experts + 1, hidden); + let gate_up = load_matrix(r, dtype, ".experts_gate_up", ".experts_gate_up.scale", experts * 2 * moe_inter, hidden); + let down = load_matrix(r, dtype, ".experts_down", ".experts_down.scale", experts * hidden, moe_inter); + let shared_gate_up = load_matrix(r, dtype, ".shared_gate_up", ".shared_gate_up.scale", 2 * shared, hidden); + let shared_down = load_matrix(r, dtype, ".shared_down", ".shared_down.scale", hidden, shared); + return Qwen35Layer { + full_attention: full, + attn_norm: attn_norm, + qkv: qkv, + q_norm: q_norm, + k_norm: k_norm, + attn_out: attn_out, + linear_in: linear_in, + conv: conv, + neg_a: neg_a, + dt_bias: dt_bias, + linear_norm: linear_norm, + linear_out: linear_out, + mlp_norm: mlp_norm, + router: router, + gate_up: gate_up, + down: down, + shared_gate_up: shared_gate_up, + shared_down: shared_down, }; } diff --git a/tests/generate_qwen35.vx b/tests/generate_qwen35.vx index 334a6b2..a1102bc 100644 --- a/tests/generate_qwen35.vx +++ b/tests/generate_qwen35.vx @@ -11,6 +11,10 @@ // 109 and 99 after it, as it did after their first copy, so a round of 7 draft tokens runs. // - the Q4_0 file with --prompt-runs 3: a time for each run of the prompt, and the lines of the // steps of the file without it. +// - the Q4_0 file with the MTP layer (`--mtp`) with --mtp 3, against the file without the MTP +// layer and without --mtp: the lines of the steps must be the same, logits too. The prompt has +// 2,100 tokens, so the rows of the MTP layer for the prompt run in 2 chunks. The MTP layer of +// the tiny model has random weights, so its drafts are not those of the model. // // The products of a chunk round each Q4_0 weight, (code - 8) times its scale, to f16, as for the // Qwen3 models. So the Q4_0 files get 0.003, as in tests/prefill.vx, and the bf16 files 0.001. @@ -47,6 +51,14 @@ // RUN: grep step= %t-runs.vx > %t-runs.steps // RUN: diff %t-q4.steps %t-runs.steps // RUN: grep -c "time prompt_ms=" %t-runs.vx | FileCheck %s --check-prefix=RUNS +// RUN: python3 %S/../scripts/make_tiny_model.py --qwen35 --mtp --q4 --q6-lm-head --max-positions 2200 %t-mtp.vxw > /dev/null +// RUN: vxc %S/../src/main.vx --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx -- %t-long.vxw --tokens $(cat %t-long.ids) --steps 24 > %t-long24.vx +// RUN: vxc %S/../src/main.vx --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx -- %t-mtp.vxw --tokens $(cat %t-long.ids) --steps 24 --mtp 3 > %t-mtp.vx +// RUN: grep step= %t-long24.vx > %t-long24.steps +// RUN: grep step= %t-mtp.vx > %t-mtp.steps +// RUN: diff %t-long24.steps %t-mtp.steps +// RUN: grep -c step= %t-mtp.steps | FileCheck %s --check-prefix=MTP-STEPS +// RUN: grep rounds= %t-mtp.vx | FileCheck %s --check-prefix=MTP // // CHECK: 16 steps, same tokens, logits within 0.001 // Q4: 16 steps, same tokens, logits within 0.003 @@ -55,3 +67,5 @@ // STEPS: {{^}}32{{$}} // DRAFT: rounds=1 drafted=7 accepted=0; // RUNS: {{^}}3{{$}} +// MTP-STEPS: {{^}}24{{$}} +// MTP: rounds={{[0-9]+}} drafted={{[0-9]+}} accepted={{[0-9]+}}; From fecb2e399bffd30a704e99b61a2fe548205bdf64 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Sun, 22 Nov 2026 07:42:27 -0800 Subject: [PATCH 42/60] rounds: the attention of all positions of a round at once The full attention layers of `run_round35` ran 5 kernels for each position: a copy of its row of `proj`, the norms and RoPE, the 2 kernels of `gated_attention`, and a copy of its output. Now 3 kernels run for all n positions: `pf_gated_norm_rope_and_store` (the kernel of the prompt chunks, with the arithmetic of the kernel of one token) stores the k and v rows of all positions, then `gated_attention_parts_rows` and `gated_attention_merge_rows` do the attention of each position over the rows up to its own position. Each block of the new kernels has the arithmetic of the kernel of one token, with the parts that `gated_attention` takes at its position (32 or 64 for each head), so each position keeps its bits. tests/round35.vx: a round of 8 tokens after a prompt of 2,044 tokens, so its positions take 32 and 64 parts. With the parts of the first position for all positions, 903 logits differ. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- src/gated_attention.vx | 197 +++++++++++++++++++++++++++++++++++++++++ src/round35.vx | 37 +++----- tests/round35.vx | 16 +++- 3 files changed, 223 insertions(+), 27 deletions(-) diff --git a/src/gated_attention.vx b/src/gated_attention.vx index a6dd3ed..527f103 100644 --- a/src/gated_attention.vx +++ b/src/gated_attention.vx @@ -255,3 +255,200 @@ fn gated_attention_merge(y : &mut Tensor, part : &Tensor< } 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`. +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. +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/round35.vx b/src/round35.vx index c4dd934..cd72596 100644 --- a/src/round35.vx +++ b/src/round35.vx @@ -17,16 +17,18 @@ // update of the state again for the positions that the CPU keeps, and writes it. That costs one // more read of S for each round, about 2 MB for each layer. // -// The full attention layers run the kernels of one token for each position, in order, so each -// position sees the rows of the KV cache that the positions before it wrote. The KV cache keeps -// the rows of all n positions; the next round or step writes over the rows that the CPU does not -// keep, before any token reads them. +// The full attention layers first store the k and v rows of all n positions, then run the +// attention of all n positions at once. Position t reads the rows up to its own position, as the +// kernels of one token do, and gets their bits. The KV cache keeps the rows of all n positions; +// the next round or step writes over the rows that the CPU does not keep, before any token reads +// them. import core::num; import std::nn; import std::vec; import qwen::deltanet; import qwen::gated_attention; import qwen::model; +import qwen::prefill35; import qwen::products; import qwen::q6; import qwen::qwen35; @@ -44,6 +46,8 @@ struct Round35 { x : Tensor, xn : Tensor, y : Tensor, + q : Tensor, + parts : Tensor, add : Tensor, o : Tensor, router : Tensor, @@ -131,6 +135,8 @@ fn new_round35(c : &Config) -> Round35 { x: transfer(Tensor([n, c.hidden_size]), Memory::HBM), xn: transfer(Tensor([n, c.hidden_size]), Memory::HBM), y: transfer(Tensor([n, i32::max(c.num_q_heads * 256, vh * 128)]), Memory::HBM), + q: transfer(Tensor([n, c.num_q_heads, 256]), Memory::HBM), + parts: transfer(gated_attention_rows_scratch(n, c.num_q_heads), Memory::HBM), add: transfer(Tensor([n, c.hidden_size]), Memory::HBM), o: transfer(Tensor([n, vh, 128]), Memory::HBM), router: transfer(Tensor([n, c.num_experts + 1]), Memory::HBM), @@ -196,21 +202,6 @@ fn add_rows(x : &mut Tensor, a : &Tensor, y : &Tensor, t : i32, dim : i32) -> void { - spawn on(Topology::Device) { - for b in 0..(dim + 255) / 256 across blocks { - for l in 0..256 across lanes { - let i = b * 256 + l; - if i < dim { - x[t][i] = y[i]; - } - } - } - } - return; -} - /// y[i] = x[t][i], for i below dim. fn take_row(y : &mut Tensor, x : &Tensor, t : i32, dim : i32) -> void { spawn on(Topology::Device) { @@ -675,12 +666,8 @@ fn run_round35(w : &Qwen35Weights, s : &mut Qwen35State, r : &mut Round35, token rms_norm_f32_rows(&mut r.xn, &r.x, &layer.attn_norm, n, c.hidden_size, eps); if layer.full_attention { nn_matvec_q4_rows(&mut kept.proj, &layer.qkv.codes, &layer.qkv.group_scales, &r.xn, n, qkv_rows, c.hidden_size); - for t in 0..n { - take_row(&mut s.proj, &kept.proj, t, qkv_rows); - gated_norm_rope_and_store(&mut s.q, &mut ls.k, &mut ls.v, &s.proj, &layer.q_norm, &layer.k_norm, &s.cos, &s.sin, start + t, c.num_q_heads, c.num_kv_heads, c.rotary_dim, eps); - gated_attention(&mut s.y, &mut s.parts, &s.q, &ls.k, &ls.v, &s.proj, start + t, c.num_q_heads, c.num_kv_heads); - put_row(&mut r.y, &s.y, t, c.num_q_heads * 256); - } + pf_gated_norm_rope_and_store(&mut r.q, &mut ls.k, &mut ls.v, &kept.proj, &layer.q_norm, &layer.k_norm, &s.cos, &s.sin, start, n, c.num_q_heads, c.num_kv_heads, c.rotary_dim, eps); + gated_attention_rows(&mut r.y, &mut r.parts, &r.q, &ls.k, &ls.v, &kept.proj, start, n, c.num_q_heads, c.num_kv_heads); nn_matvec_q4_rows(&mut r.add, &layer.attn_out.codes, &layer.attn_out.group_scales, &r.y, n, c.hidden_size, c.num_q_heads * 256); } else { nn_matvec_q4_rows(&mut kept.proj, &layer.linear_in.codes, &layer.linear_in.group_scales, &r.xn, n, a_at + vh, c.hidden_size); diff --git a/tests/round35.vx b/tests/round35.vx index c402472..8598d5c 100644 --- a/tests/round35.vx +++ b/tests/round35.vx @@ -10,9 +10,11 @@ // `r` runs rounds of 6, 4, 2 and 5 tokens after a prompt, and keeps 3, 1, 2 and 5 of them with // `commit_round35`. State `b` decodes the kept tokens one at a time, and state `a`, a copy of `b` // before each round, decodes all the tokens of the round. The logits of each position of a round -// must be those of `a`, and the DeltaNet states after the commit those of `b`. +// must be those of `a`, and the DeltaNet states after the commit those of `b`. Then a round of 8 +// tokens after a prompt of 2,044 tokens: its positions go past 2,048, where the attention of one +// position takes 64 SIMD groups for each head in place of 32. // -// RUN: python3 %S/../scripts/make_tiny_model.py --qwen35 --q4 --q6-lm-head %t.vxw > /dev/null +// RUN: python3 %S/../scripts/make_tiny_model.py --qwen35 --q4 --q6-lm-head --max-positions 2200 %t.vxw > /dev/null // RUN: vxc %s --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx -- %t.vxw | FileCheck %s // // CHECK: {{^}}round of 6: logits 0 differ, tokens 0 differ{{$}} @@ -23,6 +25,7 @@ // CHECK: {{^}}keep 2: states 0 differ{{$}} // CHECK: {{^}}round of 5: logits 0 differ, tokens 0 differ{{$}} // CHECK: {{^}}keep 5: states 0 differ{{$}} +// CHECK: {{^}}round of 8: logits 0 differ, tokens 0 differ{{$}} import core::convert; import core::num; import std::nn; @@ -172,5 +175,14 @@ fn main(argc : i32, argv : *mut *mut i8) -> i32 { println!("keep {}: states {} differ", keeps[i], states_differ(&w, &r, &b)); pos = pos + keeps[i]; } + let long_seq = 2100; + let mut la = new_qwen35_state(&w.config, long_seq); + let mut lb = new_qwen35_state(&w.config, long_seq); + let mut lr = new_qwen35_state(&w.config, long_seq); + let long = some_tokens(3, 2044, vocab); + prefill_qwen35(&w, &mut lb, &long); + prefill_qwen35(&w, &mut lr, &long); + copy_states(&mut la, &lb); + check_round(&w, &mut lr, &mut round, &mut la, &some_tokens(29, 8, vocab), long.len()); return 0; } From 123478da082c7c2d6c07ba4cb9bf545f8bec850e Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Sun, 22 Nov 2026 09:14:27 -0800 Subject: [PATCH 43/60] rounds: lm_head of 4 positions in each block `matvec_q6_rows` does 2 vectors in each block, so a round of 3 or 4 positions takes the bits of each weight of lm_head twice, and the second pass costs about as much as the first. `matvec_q6_rows4` does 4 vectors in each block, and `run_round35` uses it for 3 or more positions. To keep 16 values of x for each vector in place of 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`, and each vector keeps its bits. tests/round.vx: `matvec_q6_rows4` against `matvec_q6` for 1, 5, 8, 13 and 16 vectors, bit for bit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- src/q6.vx | 260 +++++++++++++++++++++++++++++++++++++++++++++++++ src/round35.vx | 6 +- tests/round.vx | 19 +++- 3 files changed, 283 insertions(+), 2 deletions(-) diff --git a/src/q6.vx b/src/q6.vx index 92c369d..e321200 100644 --- a/src/q6.vx +++ b/src/q6.vx @@ -316,3 +316,263 @@ fn matvec_q6_rows(y : &mut Tensor, codes : &Tensor, codes : &Tensor, high : &Tensor, scales : &Tensor, x : &Tensor, n : i32, rows : i32, cols : i32) -> void { + assert(cols % 32 == 0 && rows % 8 == 0 && n >= 1 && y.extent(0) >= n && x.extent(0) >= n && y.extent(1) >= rows && x.extent(1) >= cols, "matvec_q6_rows4: cols must be a multiple of 32 and rows of 8, and y and x need n rows of rows and cols values"); + assert(codes.len() / rows >= cols / 8 && high.len() / rows >= cols / 16 && scales.len() / rows >= cols / 32, "matvec_q6_rows4: the matrix has too few words or scales for rows x cols"); + let words = cols / 8; + let hwords = cols / 16; + let groups = cols / 32; + spawn on(Topology::Device) { + for rb in 0..rows / 8 across blocks { + for pq in 0..(n + 3) / 4 across blocks { + let mut part = unsafe { + Tensor::uninit() + }; + for s in 0..1 across subgroups { + for l in 0..32 across lanes(32) { + let mut p0 = pq * 4; + if p0 >= n { + p0 = n - 1; + } + let mut p1 = pq * 4 + 1; + if p1 >= n { + p1 = n - 1; + } + let mut p2 = pq * 4 + 2; + if p2 >= n { + p2 = n - 1; + } + let mut p3 = pq * 4 + 3; + if p3 >= n { + p3 = n - 1; + } + let mut acc = unsafe { Tensor::uninit() }; + for j in 0..32 { + acc[j] = 0.0; + } + let mut i = l * 2; + while i < words { + let c = i * 8; + let mut xa = unsafe { Tensor::uninit() }; + for t in 0..16 { + xa[t] = x[p0][c + t]; + } + let suma = 32.0 * (xa[0] + xa[1] + xa[2] + xa[3] + xa[4] + xa[5] + xa[6] + xa[7] + xa[8] + xa[9] + xa[10] + xa[11] + xa[12] + xa[13] + xa[14] + xa[15]); + xa[1] = xa[1] * 0.0625; + xa[2] = xa[2] * 0.00390625; + xa[3] = xa[3] * 0.000244140625; + xa[4] = xa[4] * 0.0000152587890625; + xa[5] = xa[5] * 0.00000095367431640625; + xa[6] = xa[6] * 0.000000059604644775390625; + xa[7] = xa[7] * 0.0000000037252902984619140625; + xa[9] = xa[9] * 0.0625; + xa[10] = xa[10] * 0.00390625; + xa[11] = xa[11] * 0.000244140625; + xa[12] = xa[12] * 0.0000152587890625; + xa[13] = xa[13] * 0.00000095367431640625; + xa[14] = xa[14] * 0.000000059604644775390625; + xa[15] = xa[15] * 0.0000000037252902984619140625; + let mut xb = unsafe { Tensor::uninit() }; + for t in 0..16 { + xb[t] = x[p1][c + t]; + } + let sumb = 32.0 * (xb[0] + xb[1] + xb[2] + xb[3] + xb[4] + xb[5] + xb[6] + xb[7] + xb[8] + xb[9] + xb[10] + xb[11] + xb[12] + xb[13] + xb[14] + xb[15]); + xb[1] = xb[1] * 0.0625; + xb[2] = xb[2] * 0.00390625; + xb[3] = xb[3] * 0.000244140625; + xb[4] = xb[4] * 0.0000152587890625; + xb[5] = xb[5] * 0.00000095367431640625; + xb[6] = xb[6] * 0.000000059604644775390625; + xb[7] = xb[7] * 0.0000000037252902984619140625; + xb[9] = xb[9] * 0.0625; + xb[10] = xb[10] * 0.00390625; + xb[11] = xb[11] * 0.000244140625; + xb[12] = xb[12] * 0.0000152587890625; + xb[13] = xb[13] * 0.00000095367431640625; + xb[14] = xb[14] * 0.000000059604644775390625; + xb[15] = xb[15] * 0.0000000037252902984619140625; + let mut xc = unsafe { Tensor::uninit() }; + for t in 0..16 { + xc[t] = x[p2][c + t]; + } + let sumc = 32.0 * (xc[0] + xc[1] + xc[2] + xc[3] + xc[4] + xc[5] + xc[6] + xc[7] + xc[8] + xc[9] + xc[10] + xc[11] + xc[12] + xc[13] + xc[14] + xc[15]); + xc[1] = xc[1] * 0.0625; + xc[2] = xc[2] * 0.00390625; + xc[3] = xc[3] * 0.000244140625; + xc[4] = xc[4] * 0.0000152587890625; + xc[5] = xc[5] * 0.00000095367431640625; + xc[6] = xc[6] * 0.000000059604644775390625; + xc[7] = xc[7] * 0.0000000037252902984619140625; + xc[9] = xc[9] * 0.0625; + xc[10] = xc[10] * 0.00390625; + xc[11] = xc[11] * 0.000244140625; + xc[12] = xc[12] * 0.0000152587890625; + xc[13] = xc[13] * 0.00000095367431640625; + xc[14] = xc[14] * 0.000000059604644775390625; + xc[15] = xc[15] * 0.0000000037252902984619140625; + let mut xd = unsafe { Tensor::uninit() }; + for t in 0..16 { + xd[t] = x[p3][c + t]; + } + let sumd = 32.0 * (xd[0] + xd[1] + xd[2] + xd[3] + xd[4] + xd[5] + xd[6] + xd[7] + xd[8] + xd[9] + xd[10] + xd[11] + xd[12] + xd[13] + xd[14] + xd[15]); + xd[1] = xd[1] * 0.0625; + xd[2] = xd[2] * 0.00390625; + xd[3] = xd[3] * 0.000244140625; + xd[4] = xd[4] * 0.0000152587890625; + xd[5] = xd[5] * 0.00000095367431640625; + xd[6] = xd[6] * 0.000000059604644775390625; + xd[7] = xd[7] * 0.0000000037252902984619140625; + xd[9] = xd[9] * 0.0625; + xd[10] = xd[10] * 0.00390625; + xd[11] = xd[11] * 0.000244140625; + xd[12] = xd[12] * 0.0000152587890625; + xd[13] = xd[13] * 0.00000095367431640625; + xd[14] = xd[14] * 0.000000059604644775390625; + xd[15] = xd[15] * 0.0000000037252902984619140625; + for j in 0..8 { + let row = rb * 8 + j; + let at = row * words + i; + let w0 = codes[at]; + let w1 = codes[at + 1]; + let h = high[row * hwords + i / 2]; + let sc = scales[row * groups + i / 4] as f32; + let f0 = (w0 & 15u32) as f32; + let f1 = (w0 & 240u32) as f32; + let f2 = (w0 & 3840u32) as f32; + let f3 = (w0 & 61440u32) as f32; + let f4 = (w0 & 983040u32) as f32; + let f5 = (w0 & 15728640u32) as f32; + let f6 = (w0 & 251658240u32) as f32; + let f7 = (w0 & 4026531840u32) as f32; + let f8 = (w1 & 15u32) as f32; + let f9 = (w1 & 240u32) as f32; + let f10 = (w1 & 3840u32) as f32; + let f11 = (w1 & 61440u32) as f32; + let f12 = (w1 & 983040u32) as f32; + let f13 = (w1 & 15728640u32) as f32; + let f14 = (w1 & 251658240u32) as f32; + let f15 = (w1 & 4026531840u32) as f32; + let g0 = ((h & 3u32) as f32) * 16.0; + let g1 = ((h & 12u32) as f32) * 64.0; + let g2 = ((h & 48u32) as f32) * 256.0; + let g3 = ((h & 192u32) as f32) * 1024.0; + let g4 = ((h & 768u32) as f32) * 4096.0; + let g5 = ((h & 3072u32) as f32) * 16384.0; + let g6 = ((h & 12288u32) as f32) * 65536.0; + let g7 = ((h & 49152u32) as f32) * 262144.0; + let g8 = ((h & 196608u32) as f32) * 0.000244140625; + let g9 = ((h & 786432u32) as f32) * 0.0009765625; + let g10 = ((h & 3145728u32) as f32) * 0.00390625; + let g11 = ((h & 12582912u32) as f32) * 0.015625; + let g12 = ((h & 50331648u32) as f32) * 0.0625; + let g13 = ((h & 201326592u32) as f32) * 0.25; + let g14 = ((h & 805306368u32) as f32) * 1.0; + let g15 = ((h & 3221225472u32) as f32) * 4.0; + let lowa = f0 * xa[0] + f1 * xa[1] + f2 * xa[2] + f3 * xa[3] + f4 * xa[4] + f5 * xa[5] + f6 * xa[6] + f7 * xa[7] + f8 * xa[8] + f9 * xa[9] + f10 * xa[10] + f11 * xa[11] + f12 * xa[12] + f13 * xa[13] + f14 * xa[14] + f15 * xa[15]; + let topa = g0 * xa[0] + g1 * xa[1] + g2 * xa[2] + g3 * xa[3] + g4 * xa[4] + g5 * xa[5] + g6 * xa[6] + g7 * xa[7] + g8 * xa[8] + g9 * xa[9] + g10 * xa[10] + g11 * xa[11] + g12 * xa[12] + g13 * xa[13] + g14 * xa[14] + g15 * xa[15]; + acc[0 + j] = acc[0 + j] + (lowa + topa - suma) * sc; + let lowb = f0 * xb[0] + f1 * xb[1] + f2 * xb[2] + f3 * xb[3] + f4 * xb[4] + f5 * xb[5] + f6 * xb[6] + f7 * xb[7] + f8 * xb[8] + f9 * xb[9] + f10 * xb[10] + f11 * xb[11] + f12 * xb[12] + f13 * xb[13] + f14 * xb[14] + f15 * xb[15]; + let topb = g0 * xb[0] + g1 * xb[1] + g2 * xb[2] + g3 * xb[3] + g4 * xb[4] + g5 * xb[5] + g6 * xb[6] + g7 * xb[7] + g8 * xb[8] + g9 * xb[9] + g10 * xb[10] + g11 * xb[11] + g12 * xb[12] + g13 * xb[13] + g14 * xb[14] + g15 * xb[15]; + acc[8 + j] = acc[8 + j] + (lowb + topb - sumb) * sc; + let lowc = f0 * xc[0] + f1 * xc[1] + f2 * xc[2] + f3 * xc[3] + f4 * xc[4] + f5 * xc[5] + f6 * xc[6] + f7 * xc[7] + f8 * xc[8] + f9 * xc[9] + f10 * xc[10] + f11 * xc[11] + f12 * xc[12] + f13 * xc[13] + f14 * xc[14] + f15 * xc[15]; + let topc = g0 * xc[0] + g1 * xc[1] + g2 * xc[2] + g3 * xc[3] + g4 * xc[4] + g5 * xc[5] + g6 * xc[6] + g7 * xc[7] + g8 * xc[8] + g9 * xc[9] + g10 * xc[10] + g11 * xc[11] + g12 * xc[12] + g13 * xc[13] + g14 * xc[14] + g15 * xc[15]; + acc[16 + j] = acc[16 + j] + (lowc + topc - sumc) * sc; + let lowd = f0 * xd[0] + f1 * xd[1] + f2 * xd[2] + f3 * xd[3] + f4 * xd[4] + f5 * xd[5] + f6 * xd[6] + f7 * xd[7] + f8 * xd[8] + f9 * xd[9] + f10 * xd[10] + f11 * xd[11] + f12 * xd[12] + f13 * xd[13] + f14 * xd[14] + f15 * xd[15]; + let topd = g0 * xd[0] + g1 * xd[1] + g2 * xd[2] + g3 * xd[3] + g4 * xd[4] + g5 * xd[5] + g6 * xd[6] + g7 * xd[7] + g8 * xd[8] + g9 * xd[9] + g10 * xd[10] + g11 * xd[11] + g12 * xd[12] + g13 * xd[13] + g14 * xd[14] + g15 * xd[15]; + acc[24 + j] = acc[24 + j] + (lowd + topd - sumd) * sc; + } + i = i + 64; + } + for j in 0..8 { + part[0][j][l] = acc[0 + j]; + part[1][j][l] = acc[8 + j]; + part[2][j][l] = acc[16 + j]; + part[3][j][l] = acc[24 + j]; + } + } + let u0_0 = lanes::sum(&part[0][0], 32); + let u0_1 = lanes::sum(&part[0][1], 32); + let u0_2 = lanes::sum(&part[0][2], 32); + let u0_3 = lanes::sum(&part[0][3], 32); + let u0_4 = lanes::sum(&part[0][4], 32); + let u0_5 = lanes::sum(&part[0][5], 32); + let u0_6 = lanes::sum(&part[0][6], 32); + let u0_7 = lanes::sum(&part[0][7], 32); + let u1_0 = lanes::sum(&part[1][0], 32); + let u1_1 = lanes::sum(&part[1][1], 32); + let u1_2 = lanes::sum(&part[1][2], 32); + let u1_3 = lanes::sum(&part[1][3], 32); + let u1_4 = lanes::sum(&part[1][4], 32); + let u1_5 = lanes::sum(&part[1][5], 32); + let u1_6 = lanes::sum(&part[1][6], 32); + let u1_7 = lanes::sum(&part[1][7], 32); + let u2_0 = lanes::sum(&part[2][0], 32); + let u2_1 = lanes::sum(&part[2][1], 32); + let u2_2 = lanes::sum(&part[2][2], 32); + let u2_3 = lanes::sum(&part[2][3], 32); + let u2_4 = lanes::sum(&part[2][4], 32); + let u2_5 = lanes::sum(&part[2][5], 32); + let u2_6 = lanes::sum(&part[2][6], 32); + let u2_7 = lanes::sum(&part[2][7], 32); + let u3_0 = lanes::sum(&part[3][0], 32); + let u3_1 = lanes::sum(&part[3][1], 32); + let u3_2 = lanes::sum(&part[3][2], 32); + let u3_3 = lanes::sum(&part[3][3], 32); + let u3_4 = lanes::sum(&part[3][4], 32); + let u3_5 = lanes::sum(&part[3][5], 32); + let u3_6 = lanes::sum(&part[3][6], 32); + let u3_7 = lanes::sum(&part[3][7], 32); + if pq * 4 + 0 < n { + y[pq * 4 + 0][rb * 8 + 0] = u0_0; + y[pq * 4 + 0][rb * 8 + 1] = u0_1; + y[pq * 4 + 0][rb * 8 + 2] = u0_2; + y[pq * 4 + 0][rb * 8 + 3] = u0_3; + y[pq * 4 + 0][rb * 8 + 4] = u0_4; + y[pq * 4 + 0][rb * 8 + 5] = u0_5; + y[pq * 4 + 0][rb * 8 + 6] = u0_6; + y[pq * 4 + 0][rb * 8 + 7] = u0_7; + } + if pq * 4 + 1 < n { + y[pq * 4 + 1][rb * 8 + 0] = u1_0; + y[pq * 4 + 1][rb * 8 + 1] = u1_1; + y[pq * 4 + 1][rb * 8 + 2] = u1_2; + y[pq * 4 + 1][rb * 8 + 3] = u1_3; + y[pq * 4 + 1][rb * 8 + 4] = u1_4; + y[pq * 4 + 1][rb * 8 + 5] = u1_5; + y[pq * 4 + 1][rb * 8 + 6] = u1_6; + y[pq * 4 + 1][rb * 8 + 7] = u1_7; + } + if pq * 4 + 2 < n { + y[pq * 4 + 2][rb * 8 + 0] = u2_0; + y[pq * 4 + 2][rb * 8 + 1] = u2_1; + y[pq * 4 + 2][rb * 8 + 2] = u2_2; + y[pq * 4 + 2][rb * 8 + 3] = u2_3; + y[pq * 4 + 2][rb * 8 + 4] = u2_4; + y[pq * 4 + 2][rb * 8 + 5] = u2_5; + y[pq * 4 + 2][rb * 8 + 6] = u2_6; + y[pq * 4 + 2][rb * 8 + 7] = u2_7; + } + if pq * 4 + 3 < n { + y[pq * 4 + 3][rb * 8 + 0] = u3_0; + y[pq * 4 + 3][rb * 8 + 1] = u3_1; + y[pq * 4 + 3][rb * 8 + 2] = u3_2; + y[pq * 4 + 3][rb * 8 + 3] = u3_3; + y[pq * 4 + 3][rb * 8 + 4] = u3_4; + y[pq * 4 + 3][rb * 8 + 5] = u3_5; + y[pq * 4 + 3][rb * 8 + 6] = u3_6; + y[pq * 4 + 3][rb * 8 + 7] = u3_7; + } + } + } + } + } + return; +} diff --git a/src/round35.vx b/src/round35.vx index cd72596..3315863 100644 --- a/src/round35.vx +++ b/src/round35.vx @@ -689,7 +689,11 @@ fn run_round35(w : &Qwen35Weights, s : &mut Qwen35State, r : &mut Round35, token l = l + 1; } rms_norm_f32_rows(&mut r.xn, &r.x, &w.final_norm, n, c.hidden_size, eps); - matvec_q6_rows(&mut r.logits, &w.lm_head.codes, &w.lm_head.high, &w.lm_head.group_scales, &r.xn, n, c.vocab_size, c.hidden_size); + if n >= 3 { + matvec_q6_rows4(&mut r.logits, &w.lm_head.codes, &w.lm_head.high, &w.lm_head.group_scales, &r.xn, n, c.vocab_size, c.hidden_size); + } else { + matvec_q6_rows(&mut r.logits, &w.lm_head.codes, &w.lm_head.high, &w.lm_head.group_scales, &r.xn, n, c.vocab_size, c.hidden_size); + } nn_argmax_rows(&mut r.next, &r.logits, n, c.vocab_size); return; } diff --git a/tests/round.vx b/tests/round.vx index dd91c6e..653871d 100644 --- a/tests/round.vx +++ b/tests/round.vx @@ -10,7 +10,8 @@ // value of a round must equal the value of the kernel of one token bit for bit. The rounds start // at position 0, in the first 32 positions, after 1,000 positions, and across position 2,048, // where `vec_attention` goes from 32 to 64 SIMD groups. Rounds of more than 8 positions run their -// attention in pieces of at most 4. Then `matvec_q6_rows` against `matvec_q6`. +// attention in pieces of at most 4. Then `matvec_q6_rows` and +// `matvec_q6_rows4` against `matvec_q6`. // // RUN: vxc %s --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx | FileCheck %s // @@ -29,10 +30,15 @@ // CHECK: {{^}}rope start 2035 n 16: 0 differ{{$}} // CHECK: {{^}}attention start 2035 n 16: 0 differ{{$}} // CHECK: {{^}}q6 n 1: 0 differ{{$}} +// CHECK: {{^}}q6 rows4 n 1: 0 differ{{$}} // CHECK: {{^}}q6 n 5: 0 differ{{$}} +// CHECK: {{^}}q6 rows4 n 5: 0 differ{{$}} // CHECK: {{^}}q6 n 8: 0 differ{{$}} +// CHECK: {{^}}q6 rows4 n 8: 0 differ{{$}} // CHECK: {{^}}q6 n 13: 0 differ{{$}} +// CHECK: {{^}}q6 rows4 n 13: 0 differ{{$}} // CHECK: {{^}}q6 n 16: 0 differ{{$}} +// CHECK: {{^}}q6 rows4 n 16: 0 differ{{$}} import core::convert; import std::nn; import std::vec; @@ -264,6 +270,17 @@ fn check_q6(s : &mut i64, n : i32) -> void { } } println!("q6 n {}: {} differ", n, count); + matvec_q6_rows4(&mut yn, &dc, &dh, &ds, &x, n, rows, cols); + let h4 = transfer(&yn, Memory::CPU_DRAM); + let mut count4 = 0; + for p in 0..n { + for r in 0..rows { + if h4[p][r].to_bits() != one[p * rows + r].to_bits() { + count4 = count4 + 1; + } + } + } + println!("q6 rows4 n {}: {} differ", n, count4); return; } From a9ae80945aeb3a5b1c7fd407081c65a620d6597a Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:13:11 -0800 Subject: [PATCH 44/60] rounds: lm_head of the rows that can be the greedy token A round of 3 or 4 positions spent about 10 ms in lm_head, and a round of 8 about 20 ms, for the arithmetic of the 6-bit weights. A round needs only the greedy token of each position, and its logit. For 2 or more positions, `run_round35` now runs three kernels: - `lm_rough_q6`: rough logits a for up to 8 positions at once, with f16 weights and inputs on the simdgroup matrices. Its time is about that of one position. - `lm_pick_threshold`: for each position, M = the largest a - B, where B is a bound of |a - e| from the norms of x and of the rows (src/q6.vx gives the terms of the bound). - `matvec_q6_rows4_pick`: the exact logits e (those of `matvec_q6`) of each row that does not have a + B < M; the other rows get the lowest f32 and cannot be the greedy token. A block with no such row reads no weights. The norms of the rows come from `lm_q6_norms` in the first round. The greedy tokens, and their logits, stay those of the plain steps bit for bit; the other logits of a round are no longer exact. `Round35.pick` false gives all the logits exactly, as before. tests/round35.vx: each round runs again with the pick, and its greedy tokens and their logits must be those of the plain steps. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- src/q6.vx | 602 +++++++++++++++++++++++++++++++++++++++++++++++ src/round35.vx | 28 ++- tests/round35.vx | 38 ++- 3 files changed, 658 insertions(+), 10 deletions(-) diff --git a/src/q6.vx b/src/q6.vx index e321200..bab2e9f 100644 --- a/src/q6.vx +++ b/src/q6.vx @@ -576,3 +576,605 @@ fn matvec_q6_rows4(y : &mut Tensor, codes : &Tensor, an : &mut Tensor, codes : &Tensor, high : &Tensor, scales : &Tensor, rows : i32, cols : i32) -> void { + assert(cols % 32 == 0 && wn.len() >= rows && an.len() >= rows, "lm_q6_norms: cols must be a multiple of 32, and wn and an need rows values"); + let words = cols / 8; + let hwords = cols / 16; + let groups = cols / 32; + spawn on(Topology::Device) { + for r in 0..rows across blocks { + let mut pw = unsafe { Tensor::uninit() }; + let mut pa = unsafe { Tensor::uninit() }; + for l in 0..32 across lanes(32) { + let mut sw : f32 = 0.0; + let mut sa : f32 = 0.0; + let mut i = l * 2; + while i < words { + let w0 = codes[r * words + i]; + let w1 = codes[r * words + i + 1]; + let h = high[r * hwords + i / 2]; + let sc = scales[r * groups + i / 4] as f32; + for t in 0..16 { + let mut lo = (w0 >> ((t * 4) as u32)) & 15u32; + if t >= 8 { + lo = (w1 >> (((t - 8) * 4) as u32)) & 15u32; + } + let q = (lo + 16u32 * ((h >> ((t * 2) as u32)) & 3u32)) as f32; + let v = (q - 32.0) * sc; + let u = (q + 32.0) * sc; + sw = sw + v * v; + sa = sa + u * u; + } + i = i + 64; + } + pw[l] = sw; + pa[l] = sa; + } + let s = lanes::sum(&pw, 32); + let s2 = lanes::sum(&pa, 32); + wn[r] = s.sqrt(); + an[r] = s2.sqrt(); + } + } + return; +} + +/// The rough logits a of the bound above, for x[0] to x[n - 1]: a[p][r] is about (row r) . x[p]. +/// A block takes 64 rows and 8 vectors (rows p of a past n - 1 get the products of zeros), and +/// subgroup sg makes rows sg * 16 to + 15. For each 32 columns, each lane writes 16 weights +/// (q - 32) * scale as f16 to shared memory, and the sums stay in the simdgroup matrices. +fn lm_rough_q6(a : &mut Tensor, codes : &Tensor, high : &Tensor, scales : &Tensor, x : &Tensor, n : i32, rows : i32, cols : i32) -> void { + assert(cols % 32 == 0 && rows % 64 == 0 && n >= 1 && a.extent(0) >= ((n + 7) / 8) * 8 && a.extent(1) >= rows && x.extent(0) >= n && x.extent(1) >= cols, "lm_rough_q6: cols must be a multiple of 32 and rows of 64, a needs n rows rounded up to 8, and x n rows"); + let words = cols / 8; + let hwords = cols / 16; + let groups = cols / 32; + spawn on(Topology::Device) { + for rb in 0..rows / 64 across blocks { + for pt in 0..(n + 7) / 8 across blocks { + let mut sw = unsafe { Tensor::uninit() }; + let mut sx = unsafe { Tensor::uninit() }; + let mut acc = unsafe { Tensor::uninit() }; + for sg in 0..4 across subgroups { + lanes::fill(&mut acc[sg], 0.0); + } + for g in 0..groups { + for sg in 0..4 across subgroups { + for l in 0..32 across lanes(32) { + let rl = l % 16; + let half = l / 16; + let row = rb * 64 + sg * 16 + rl; + let at = row * words + g * 4 + half * 2; + let w0 = codes[at]; + let w1 = codes[at + 1]; + let h = high[row * hwords + g * 2 + half]; + let sc = scales[row * groups + g]; + sw[sg][half * 16 + 0][rl] = ((((w0 & 15u32) + ((h << 4u32) & 48u32)) as i32 - 32) as f16) * sc; + sw[sg][half * 16 + 1][rl] = (((((w0 >> 4u32) & 15u32) + ((h << 2u32) & 48u32)) as i32 - 32) as f16) * sc; + sw[sg][half * 16 + 2][rl] = (((((w0 >> 8u32) & 15u32) + ((h >> 0u32) & 48u32)) as i32 - 32) as f16) * sc; + sw[sg][half * 16 + 3][rl] = (((((w0 >> 12u32) & 15u32) + ((h >> 2u32) & 48u32)) as i32 - 32) as f16) * sc; + sw[sg][half * 16 + 4][rl] = (((((w0 >> 16u32) & 15u32) + ((h >> 4u32) & 48u32)) as i32 - 32) as f16) * sc; + sw[sg][half * 16 + 5][rl] = (((((w0 >> 20u32) & 15u32) + ((h >> 6u32) & 48u32)) as i32 - 32) as f16) * sc; + sw[sg][half * 16 + 6][rl] = (((((w0 >> 24u32) & 15u32) + ((h >> 8u32) & 48u32)) as i32 - 32) as f16) * sc; + sw[sg][half * 16 + 7][rl] = (((((w0 >> 28u32) & 15u32) + ((h >> 10u32) & 48u32)) as i32 - 32) as f16) * sc; + sw[sg][half * 16 + 8][rl] = ((((w1 & 15u32) + ((h >> 12u32) & 48u32)) as i32 - 32) as f16) * sc; + sw[sg][half * 16 + 9][rl] = (((((w1 >> 4u32) & 15u32) + ((h >> 14u32) & 48u32)) as i32 - 32) as f16) * sc; + sw[sg][half * 16 + 10][rl] = (((((w1 >> 8u32) & 15u32) + ((h >> 16u32) & 48u32)) as i32 - 32) as f16) * sc; + sw[sg][half * 16 + 11][rl] = (((((w1 >> 12u32) & 15u32) + ((h >> 18u32) & 48u32)) as i32 - 32) as f16) * sc; + sw[sg][half * 16 + 12][rl] = (((((w1 >> 16u32) & 15u32) + ((h >> 20u32) & 48u32)) as i32 - 32) as f16) * sc; + sw[sg][half * 16 + 13][rl] = (((((w1 >> 20u32) & 15u32) + ((h >> 22u32) & 48u32)) as i32 - 32) as f16) * sc; + sw[sg][half * 16 + 14][rl] = (((((w1 >> 24u32) & 15u32) + ((h >> 24u32) & 48u32)) as i32 - 32) as f16) * sc; + sw[sg][half * 16 + 15][rl] = (((((w1 >> 28u32) & 15u32) + ((h >> 26u32) & 48u32)) as i32 - 32) as f16) * sc; + let p = pt * 8 + sg * 2 + l / 16; + let k = g * 32 + (l % 16) * 2; + let mut v0 : f32 = 0.0; + let mut v1 : f32 = 0.0; + if p < n { + v0 = x[p][k]; + v1 = x[p][k + 1]; + } + sx[0][sg * 2 + l / 16][(l % 16) * 2] = v0 as f16; + sx[0][sg * 2 + l / 16][(l % 16) * 2 + 1] = v1 as f16; + } + } + for sg in 0..4 across subgroups { + acc[sg] = acc[sg] + (sx[0] as f32) @ (sw[sg] as f32); + } + } + for sg in 0..4 across subgroups { + lanes::copy(a, &acc[sg], [pt * 8, rb * 64 + sg * 16]); + } + } + } + } + return; +} + +/// thr[p] = (M, |x[p]|, |x[p] - f16(x[p])|) for p below n, with M of the bound above. +fn lm_pick_threshold(thr : &mut Tensor, a : &Tensor, wn : &Tensor, an : &Tensor, x : &Tensor, n : i32, rows : i32, cols : i32) -> void { + assert(n >= 1 && thr.extent(0) >= n && thr.extent(1) >= 3 && a.extent(0) >= n && a.extent(1) >= rows && x.extent(0) >= n && x.extent(1) >= cols && wn.len() >= rows && an.len() >= rows, "lm_pick_threshold: thr needs n rows of 3 values, a and x n rows, and wn and an rows values"); + spawn on(Topology::Device) { + for p in 0..n across blocks { + let mut px = unsafe { Tensor::uninit() }; + let mut pd = unsafe { Tensor::uninit() }; + let mut pm = unsafe { Tensor::uninit() }; + for l in 0..1024 across lanes { + let mut sx : f32 = 0.0; + let mut sd : f32 = 0.0; + let mut i = l; + while i < cols { + let v = x[p][i]; + let d = v - ((v as f16) as f32); + sx = sx + v * v; + sd = sd + d * d; + i = i + 1024; + } + px[l] = sx; + pd[l] = sd; + } + let s = lanes::sum(&px, 1024); + let s2 = lanes::sum(&pd, 1024); + let xs = s.sqrt(); + let ds = s2.sqrt(); + for l in 0..1024 across lanes { + let mut m : f32 = -340000000000000000000000000000000000000.0; + let mut r = l; + while r < rows { + let v = a[p][r] - (1.25 * (wn[r] * (0.001 * xs + 1.01 * ds) + 0.00001 * an[r] * xs + 0.000002 * xs)); + if v > m { + m = v; + } + r = r + 1024; + } + pm[l] = m; + } + let mut m = lanes::max(&pm, 1024); + if !(xs < 60000.0) { + m = -340000000000000000000000000000000000000.0; + } + thr[p][0] = m; + thr[p][1] = xs; + thr[p][2] = ds; + } + } + return; +} + +/// `matvec_q6_rows4` for the rows that can be the greedy token of each vector, after +/// `lm_rough_q6` (a) and `lm_pick_threshold` (thr): y[p][r] is the y of `matvec_q6` for x[p] bit for +/// bit when !(a[p][r] + B < M), and the lowest f32 otherwise. +fn matvec_q6_rows4_pick(y : &mut Tensor, codes : &Tensor, high : &Tensor, scales : &Tensor, x : &Tensor, a : &Tensor, wn : &Tensor, an : &Tensor, thr : &Tensor, n : i32, rows : i32, cols : i32) -> void { + assert(a.extent(0) >= n && a.extent(1) >= rows && thr.extent(0) >= n && wn.len() >= rows && an.len() >= rows, "matvec_q6_rows4_pick: a and thr need n rows, and wn and an rows values"); + assert(cols % 32 == 0 && rows % 8 == 0 && n >= 1 && y.extent(0) >= n && x.extent(0) >= n && y.extent(1) >= rows && x.extent(1) >= cols, "matvec_q6_rows4_pick: cols must be a multiple of 32 and rows of 8, and y and x need n rows of rows and cols values"); + assert(codes.len() / rows >= cols / 8 && high.len() / rows >= cols / 16 && scales.len() / rows >= cols / 32, "matvec_q6_rows4_pick: the matrix has too few words or scales for rows x cols"); + let words = cols / 8; + let hwords = cols / 16; + let groups = cols / 32; + spawn on(Topology::Device) { + for rb in 0..rows / 8 across blocks { + for pq in 0..(n + 3) / 4 across blocks { + let mut part = unsafe { + Tensor::uninit() + }; + let mut flag = unsafe { Tensor::uninit() }; + for s in 0..1 across subgroups { + // Lane l: row rb * 8 + l / 4 for vector pq * 4 + l % 4 (the last vector again past n - 1). + for l in 0..32 across lanes(32) { + let mut p = pq * 4 + l % 4; + if p >= n { + p = n - 1; + } + let row = rb * 8 + l / 4; + let xs = thr[p][1]; + let ds = thr[p][2]; + let mut f : f32 = 0.0; + if !(a[p][row] + 1.25 * (wn[row] * (0.001 * xs + 1.01 * ds) + 0.00001 * an[row] * xs + 0.000002 * xs) < thr[p][0]) { + f = 1.0; + } + flag[l] = f; + } + // A block with no row to pick reads no weights. + let live = lanes::max(&flag, 32); + let mut end = 0; + if live > 0.5 { + end = words; + } + for l in 0..32 across lanes(32) { + let mut p0 = pq * 4; + if p0 >= n { + p0 = n - 1; + } + let mut p1 = pq * 4 + 1; + if p1 >= n { + p1 = n - 1; + } + let mut p2 = pq * 4 + 2; + if p2 >= n { + p2 = n - 1; + } + let mut p3 = pq * 4 + 3; + if p3 >= n { + p3 = n - 1; + } + let mut acc = unsafe { Tensor::uninit() }; + for j in 0..32 { + acc[j] = 0.0; + } + let mut i = l * 2; + while i < end { + let c = i * 8; + let mut xa = unsafe { Tensor::uninit() }; + for t in 0..16 { + xa[t] = x[p0][c + t]; + } + let suma = 32.0 * (xa[0] + xa[1] + xa[2] + xa[3] + xa[4] + xa[5] + xa[6] + xa[7] + xa[8] + xa[9] + xa[10] + xa[11] + xa[12] + xa[13] + xa[14] + xa[15]); + xa[1] = xa[1] * 0.0625; + xa[2] = xa[2] * 0.00390625; + xa[3] = xa[3] * 0.000244140625; + xa[4] = xa[4] * 0.0000152587890625; + xa[5] = xa[5] * 0.00000095367431640625; + xa[6] = xa[6] * 0.000000059604644775390625; + xa[7] = xa[7] * 0.0000000037252902984619140625; + xa[9] = xa[9] * 0.0625; + xa[10] = xa[10] * 0.00390625; + xa[11] = xa[11] * 0.000244140625; + xa[12] = xa[12] * 0.0000152587890625; + xa[13] = xa[13] * 0.00000095367431640625; + xa[14] = xa[14] * 0.000000059604644775390625; + xa[15] = xa[15] * 0.0000000037252902984619140625; + let mut xb = unsafe { Tensor::uninit() }; + for t in 0..16 { + xb[t] = x[p1][c + t]; + } + let sumb = 32.0 * (xb[0] + xb[1] + xb[2] + xb[3] + xb[4] + xb[5] + xb[6] + xb[7] + xb[8] + xb[9] + xb[10] + xb[11] + xb[12] + xb[13] + xb[14] + xb[15]); + xb[1] = xb[1] * 0.0625; + xb[2] = xb[2] * 0.00390625; + xb[3] = xb[3] * 0.000244140625; + xb[4] = xb[4] * 0.0000152587890625; + xb[5] = xb[5] * 0.00000095367431640625; + xb[6] = xb[6] * 0.000000059604644775390625; + xb[7] = xb[7] * 0.0000000037252902984619140625; + xb[9] = xb[9] * 0.0625; + xb[10] = xb[10] * 0.00390625; + xb[11] = xb[11] * 0.000244140625; + xb[12] = xb[12] * 0.0000152587890625; + xb[13] = xb[13] * 0.00000095367431640625; + xb[14] = xb[14] * 0.000000059604644775390625; + xb[15] = xb[15] * 0.0000000037252902984619140625; + let mut xc = unsafe { Tensor::uninit() }; + for t in 0..16 { + xc[t] = x[p2][c + t]; + } + let sumc = 32.0 * (xc[0] + xc[1] + xc[2] + xc[3] + xc[4] + xc[5] + xc[6] + xc[7] + xc[8] + xc[9] + xc[10] + xc[11] + xc[12] + xc[13] + xc[14] + xc[15]); + xc[1] = xc[1] * 0.0625; + xc[2] = xc[2] * 0.00390625; + xc[3] = xc[3] * 0.000244140625; + xc[4] = xc[4] * 0.0000152587890625; + xc[5] = xc[5] * 0.00000095367431640625; + xc[6] = xc[6] * 0.000000059604644775390625; + xc[7] = xc[7] * 0.0000000037252902984619140625; + xc[9] = xc[9] * 0.0625; + xc[10] = xc[10] * 0.00390625; + xc[11] = xc[11] * 0.000244140625; + xc[12] = xc[12] * 0.0000152587890625; + xc[13] = xc[13] * 0.00000095367431640625; + xc[14] = xc[14] * 0.000000059604644775390625; + xc[15] = xc[15] * 0.0000000037252902984619140625; + let mut xd = unsafe { Tensor::uninit() }; + for t in 0..16 { + xd[t] = x[p3][c + t]; + } + let sumd = 32.0 * (xd[0] + xd[1] + xd[2] + xd[3] + xd[4] + xd[5] + xd[6] + xd[7] + xd[8] + xd[9] + xd[10] + xd[11] + xd[12] + xd[13] + xd[14] + xd[15]); + xd[1] = xd[1] * 0.0625; + xd[2] = xd[2] * 0.00390625; + xd[3] = xd[3] * 0.000244140625; + xd[4] = xd[4] * 0.0000152587890625; + xd[5] = xd[5] * 0.00000095367431640625; + xd[6] = xd[6] * 0.000000059604644775390625; + xd[7] = xd[7] * 0.0000000037252902984619140625; + xd[9] = xd[9] * 0.0625; + xd[10] = xd[10] * 0.00390625; + xd[11] = xd[11] * 0.000244140625; + xd[12] = xd[12] * 0.0000152587890625; + xd[13] = xd[13] * 0.00000095367431640625; + xd[14] = xd[14] * 0.000000059604644775390625; + xd[15] = xd[15] * 0.0000000037252902984619140625; + for j in 0..8 { + let row = rb * 8 + j; + let at = row * words + i; + let w0 = codes[at]; + let w1 = codes[at + 1]; + let h = high[row * hwords + i / 2]; + let sc = scales[row * groups + i / 4] as f32; + let f0 = (w0 & 15u32) as f32; + let f1 = (w0 & 240u32) as f32; + let f2 = (w0 & 3840u32) as f32; + let f3 = (w0 & 61440u32) as f32; + let f4 = (w0 & 983040u32) as f32; + let f5 = (w0 & 15728640u32) as f32; + let f6 = (w0 & 251658240u32) as f32; + let f7 = (w0 & 4026531840u32) as f32; + let f8 = (w1 & 15u32) as f32; + let f9 = (w1 & 240u32) as f32; + let f10 = (w1 & 3840u32) as f32; + let f11 = (w1 & 61440u32) as f32; + let f12 = (w1 & 983040u32) as f32; + let f13 = (w1 & 15728640u32) as f32; + let f14 = (w1 & 251658240u32) as f32; + let f15 = (w1 & 4026531840u32) as f32; + let g0 = ((h & 3u32) as f32) * 16.0; + let g1 = ((h & 12u32) as f32) * 64.0; + let g2 = ((h & 48u32) as f32) * 256.0; + let g3 = ((h & 192u32) as f32) * 1024.0; + let g4 = ((h & 768u32) as f32) * 4096.0; + let g5 = ((h & 3072u32) as f32) * 16384.0; + let g6 = ((h & 12288u32) as f32) * 65536.0; + let g7 = ((h & 49152u32) as f32) * 262144.0; + let g8 = ((h & 196608u32) as f32) * 0.000244140625; + let g9 = ((h & 786432u32) as f32) * 0.0009765625; + let g10 = ((h & 3145728u32) as f32) * 0.00390625; + let g11 = ((h & 12582912u32) as f32) * 0.015625; + let g12 = ((h & 50331648u32) as f32) * 0.0625; + let g13 = ((h & 201326592u32) as f32) * 0.25; + let g14 = ((h & 805306368u32) as f32) * 1.0; + let g15 = ((h & 3221225472u32) as f32) * 4.0; + let lowa = f0 * xa[0] + f1 * xa[1] + f2 * xa[2] + f3 * xa[3] + f4 * xa[4] + f5 * xa[5] + f6 * xa[6] + f7 * xa[7] + f8 * xa[8] + f9 * xa[9] + f10 * xa[10] + f11 * xa[11] + f12 * xa[12] + f13 * xa[13] + f14 * xa[14] + f15 * xa[15]; + let topa = g0 * xa[0] + g1 * xa[1] + g2 * xa[2] + g3 * xa[3] + g4 * xa[4] + g5 * xa[5] + g6 * xa[6] + g7 * xa[7] + g8 * xa[8] + g9 * xa[9] + g10 * xa[10] + g11 * xa[11] + g12 * xa[12] + g13 * xa[13] + g14 * xa[14] + g15 * xa[15]; + acc[0 + j] = acc[0 + j] + (lowa + topa - suma) * sc; + let lowb = f0 * xb[0] + f1 * xb[1] + f2 * xb[2] + f3 * xb[3] + f4 * xb[4] + f5 * xb[5] + f6 * xb[6] + f7 * xb[7] + f8 * xb[8] + f9 * xb[9] + f10 * xb[10] + f11 * xb[11] + f12 * xb[12] + f13 * xb[13] + f14 * xb[14] + f15 * xb[15]; + let topb = g0 * xb[0] + g1 * xb[1] + g2 * xb[2] + g3 * xb[3] + g4 * xb[4] + g5 * xb[5] + g6 * xb[6] + g7 * xb[7] + g8 * xb[8] + g9 * xb[9] + g10 * xb[10] + g11 * xb[11] + g12 * xb[12] + g13 * xb[13] + g14 * xb[14] + g15 * xb[15]; + acc[8 + j] = acc[8 + j] + (lowb + topb - sumb) * sc; + let lowc = f0 * xc[0] + f1 * xc[1] + f2 * xc[2] + f3 * xc[3] + f4 * xc[4] + f5 * xc[5] + f6 * xc[6] + f7 * xc[7] + f8 * xc[8] + f9 * xc[9] + f10 * xc[10] + f11 * xc[11] + f12 * xc[12] + f13 * xc[13] + f14 * xc[14] + f15 * xc[15]; + let topc = g0 * xc[0] + g1 * xc[1] + g2 * xc[2] + g3 * xc[3] + g4 * xc[4] + g5 * xc[5] + g6 * xc[6] + g7 * xc[7] + g8 * xc[8] + g9 * xc[9] + g10 * xc[10] + g11 * xc[11] + g12 * xc[12] + g13 * xc[13] + g14 * xc[14] + g15 * xc[15]; + acc[16 + j] = acc[16 + j] + (lowc + topc - sumc) * sc; + let lowd = f0 * xd[0] + f1 * xd[1] + f2 * xd[2] + f3 * xd[3] + f4 * xd[4] + f5 * xd[5] + f6 * xd[6] + f7 * xd[7] + f8 * xd[8] + f9 * xd[9] + f10 * xd[10] + f11 * xd[11] + f12 * xd[12] + f13 * xd[13] + f14 * xd[14] + f15 * xd[15]; + let topd = g0 * xd[0] + g1 * xd[1] + g2 * xd[2] + g3 * xd[3] + g4 * xd[4] + g5 * xd[5] + g6 * xd[6] + g7 * xd[7] + g8 * xd[8] + g9 * xd[9] + g10 * xd[10] + g11 * xd[11] + g12 * xd[12] + g13 * xd[13] + g14 * xd[14] + g15 * xd[15]; + acc[24 + j] = acc[24 + j] + (lowd + topd - sumd) * sc; + } + i = i + 64; + } + for j in 0..8 { + part[0][j][l] = acc[0 + j]; + part[1][j][l] = acc[8 + j]; + part[2][j][l] = acc[16 + j]; + part[3][j][l] = acc[24 + j]; + } + } + let u0_0 = lanes::sum(&part[0][0], 32); + let u0_1 = lanes::sum(&part[0][1], 32); + let u0_2 = lanes::sum(&part[0][2], 32); + let u0_3 = lanes::sum(&part[0][3], 32); + let u0_4 = lanes::sum(&part[0][4], 32); + let u0_5 = lanes::sum(&part[0][5], 32); + let u0_6 = lanes::sum(&part[0][6], 32); + let u0_7 = lanes::sum(&part[0][7], 32); + let u1_0 = lanes::sum(&part[1][0], 32); + let u1_1 = lanes::sum(&part[1][1], 32); + let u1_2 = lanes::sum(&part[1][2], 32); + let u1_3 = lanes::sum(&part[1][3], 32); + let u1_4 = lanes::sum(&part[1][4], 32); + let u1_5 = lanes::sum(&part[1][5], 32); + let u1_6 = lanes::sum(&part[1][6], 32); + let u1_7 = lanes::sum(&part[1][7], 32); + let u2_0 = lanes::sum(&part[2][0], 32); + let u2_1 = lanes::sum(&part[2][1], 32); + let u2_2 = lanes::sum(&part[2][2], 32); + let u2_3 = lanes::sum(&part[2][3], 32); + let u2_4 = lanes::sum(&part[2][4], 32); + let u2_5 = lanes::sum(&part[2][5], 32); + let u2_6 = lanes::sum(&part[2][6], 32); + let u2_7 = lanes::sum(&part[2][7], 32); + let u3_0 = lanes::sum(&part[3][0], 32); + let u3_1 = lanes::sum(&part[3][1], 32); + let u3_2 = lanes::sum(&part[3][2], 32); + let u3_3 = lanes::sum(&part[3][3], 32); + let u3_4 = lanes::sum(&part[3][4], 32); + let u3_5 = lanes::sum(&part[3][5], 32); + let u3_6 = lanes::sum(&part[3][6], 32); + let u3_7 = lanes::sum(&part[3][7], 32); + if pq * 4 + 0 < n { + let mut v0_0 : f32 = -340000000000000000000000000000000000000.0; + if flag[0] > 0.5 { + v0_0 = u0_0; + } + y[pq * 4 + 0][rb * 8 + 0] = v0_0; + let mut v0_1 : f32 = -340000000000000000000000000000000000000.0; + if flag[4] > 0.5 { + v0_1 = u0_1; + } + y[pq * 4 + 0][rb * 8 + 1] = v0_1; + let mut v0_2 : f32 = -340000000000000000000000000000000000000.0; + if flag[8] > 0.5 { + v0_2 = u0_2; + } + y[pq * 4 + 0][rb * 8 + 2] = v0_2; + let mut v0_3 : f32 = -340000000000000000000000000000000000000.0; + if flag[12] > 0.5 { + v0_3 = u0_3; + } + y[pq * 4 + 0][rb * 8 + 3] = v0_3; + let mut v0_4 : f32 = -340000000000000000000000000000000000000.0; + if flag[16] > 0.5 { + v0_4 = u0_4; + } + y[pq * 4 + 0][rb * 8 + 4] = v0_4; + let mut v0_5 : f32 = -340000000000000000000000000000000000000.0; + if flag[20] > 0.5 { + v0_5 = u0_5; + } + y[pq * 4 + 0][rb * 8 + 5] = v0_5; + let mut v0_6 : f32 = -340000000000000000000000000000000000000.0; + if flag[24] > 0.5 { + v0_6 = u0_6; + } + y[pq * 4 + 0][rb * 8 + 6] = v0_6; + let mut v0_7 : f32 = -340000000000000000000000000000000000000.0; + if flag[28] > 0.5 { + v0_7 = u0_7; + } + y[pq * 4 + 0][rb * 8 + 7] = v0_7; + } + if pq * 4 + 1 < n { + let mut v1_0 : f32 = -340000000000000000000000000000000000000.0; + if flag[1] > 0.5 { + v1_0 = u1_0; + } + y[pq * 4 + 1][rb * 8 + 0] = v1_0; + let mut v1_1 : f32 = -340000000000000000000000000000000000000.0; + if flag[5] > 0.5 { + v1_1 = u1_1; + } + y[pq * 4 + 1][rb * 8 + 1] = v1_1; + let mut v1_2 : f32 = -340000000000000000000000000000000000000.0; + if flag[9] > 0.5 { + v1_2 = u1_2; + } + y[pq * 4 + 1][rb * 8 + 2] = v1_2; + let mut v1_3 : f32 = -340000000000000000000000000000000000000.0; + if flag[13] > 0.5 { + v1_3 = u1_3; + } + y[pq * 4 + 1][rb * 8 + 3] = v1_3; + let mut v1_4 : f32 = -340000000000000000000000000000000000000.0; + if flag[17] > 0.5 { + v1_4 = u1_4; + } + y[pq * 4 + 1][rb * 8 + 4] = v1_4; + let mut v1_5 : f32 = -340000000000000000000000000000000000000.0; + if flag[21] > 0.5 { + v1_5 = u1_5; + } + y[pq * 4 + 1][rb * 8 + 5] = v1_5; + let mut v1_6 : f32 = -340000000000000000000000000000000000000.0; + if flag[25] > 0.5 { + v1_6 = u1_6; + } + y[pq * 4 + 1][rb * 8 + 6] = v1_6; + let mut v1_7 : f32 = -340000000000000000000000000000000000000.0; + if flag[29] > 0.5 { + v1_7 = u1_7; + } + y[pq * 4 + 1][rb * 8 + 7] = v1_7; + } + if pq * 4 + 2 < n { + let mut v2_0 : f32 = -340000000000000000000000000000000000000.0; + if flag[2] > 0.5 { + v2_0 = u2_0; + } + y[pq * 4 + 2][rb * 8 + 0] = v2_0; + let mut v2_1 : f32 = -340000000000000000000000000000000000000.0; + if flag[6] > 0.5 { + v2_1 = u2_1; + } + y[pq * 4 + 2][rb * 8 + 1] = v2_1; + let mut v2_2 : f32 = -340000000000000000000000000000000000000.0; + if flag[10] > 0.5 { + v2_2 = u2_2; + } + y[pq * 4 + 2][rb * 8 + 2] = v2_2; + let mut v2_3 : f32 = -340000000000000000000000000000000000000.0; + if flag[14] > 0.5 { + v2_3 = u2_3; + } + y[pq * 4 + 2][rb * 8 + 3] = v2_3; + let mut v2_4 : f32 = -340000000000000000000000000000000000000.0; + if flag[18] > 0.5 { + v2_4 = u2_4; + } + y[pq * 4 + 2][rb * 8 + 4] = v2_4; + let mut v2_5 : f32 = -340000000000000000000000000000000000000.0; + if flag[22] > 0.5 { + v2_5 = u2_5; + } + y[pq * 4 + 2][rb * 8 + 5] = v2_5; + let mut v2_6 : f32 = -340000000000000000000000000000000000000.0; + if flag[26] > 0.5 { + v2_6 = u2_6; + } + y[pq * 4 + 2][rb * 8 + 6] = v2_6; + let mut v2_7 : f32 = -340000000000000000000000000000000000000.0; + if flag[30] > 0.5 { + v2_7 = u2_7; + } + y[pq * 4 + 2][rb * 8 + 7] = v2_7; + } + if pq * 4 + 3 < n { + let mut v3_0 : f32 = -340000000000000000000000000000000000000.0; + if flag[3] > 0.5 { + v3_0 = u3_0; + } + y[pq * 4 + 3][rb * 8 + 0] = v3_0; + let mut v3_1 : f32 = -340000000000000000000000000000000000000.0; + if flag[7] > 0.5 { + v3_1 = u3_1; + } + y[pq * 4 + 3][rb * 8 + 1] = v3_1; + let mut v3_2 : f32 = -340000000000000000000000000000000000000.0; + if flag[11] > 0.5 { + v3_2 = u3_2; + } + y[pq * 4 + 3][rb * 8 + 2] = v3_2; + let mut v3_3 : f32 = -340000000000000000000000000000000000000.0; + if flag[15] > 0.5 { + v3_3 = u3_3; + } + y[pq * 4 + 3][rb * 8 + 3] = v3_3; + let mut v3_4 : f32 = -340000000000000000000000000000000000000.0; + if flag[19] > 0.5 { + v3_4 = u3_4; + } + y[pq * 4 + 3][rb * 8 + 4] = v3_4; + let mut v3_5 : f32 = -340000000000000000000000000000000000000.0; + if flag[23] > 0.5 { + v3_5 = u3_5; + } + y[pq * 4 + 3][rb * 8 + 5] = v3_5; + let mut v3_6 : f32 = -340000000000000000000000000000000000000.0; + if flag[27] > 0.5 { + v3_6 = u3_6; + } + y[pq * 4 + 3][rb * 8 + 6] = v3_6; + let mut v3_7 : f32 = -340000000000000000000000000000000000000.0; + if flag[31] > 0.5 { + v3_7 = u3_7; + } + y[pq * 4 + 3][rb * 8 + 7] = v3_7; + } + } + } + } + } + return; +} diff --git a/src/round35.vx b/src/round35.vx index 3315863..f25cc3f 100644 --- a/src/round35.vx +++ b/src/round35.vx @@ -60,6 +60,15 @@ struct Round35 { logits : Tensor, next : Tensor, kept : Vec, + // The lm_head of 2 or more positions (src/q6.vx): the rough logits, the norms of the rows of + // lm_head (from the first round that uses them), and the threshold of each position. With `pick` + // false, each round computes all the logits exactly, as for 1 position. + rough : Tensor, + wn : Tensor, + an : Tensor, + thr : Tensor, + norms_ready : bool, + pick : bool, } /// What a round keeps of one layer for `commit_round35`. A full attention layer keeps only `proj`, @@ -149,6 +158,12 @@ fn new_round35(c : &Config) -> Round35 { logits: transfer(Tensor([n, c.vocab_size]), Memory::HBM), next: transfer(Tensor([n]), Memory::HBM), kept: kept, + rough: transfer(Tensor([((n + 7) / 8) * 8, c.vocab_size]), Memory::HBM), + wn: transfer(Tensor([c.vocab_size]), Memory::HBM), + an: transfer(Tensor([c.vocab_size]), Memory::HBM), + thr: transfer(Tensor([n, 4]), Memory::HBM), + norms_ready: false, + pick: true, }; } @@ -689,7 +704,18 @@ fn run_round35(w : &Qwen35Weights, s : &mut Qwen35State, r : &mut Round35, token l = l + 1; } rms_norm_f32_rows(&mut r.xn, &r.x, &w.final_norm, n, c.hidden_size, eps); - if n >= 3 { + let lm = &w.lm_head; + if r.pick && n >= 2 && c.vocab_size % 64 == 0 { + // Only the rows that can be the greedy token get their exact logits; the others get the lowest + // f32, so the greedy tokens, and their logits, are those of all the rows. + if !r.norms_ready { + lm_q6_norms(&mut r.wn, &mut r.an, &lm.codes, &lm.high, &lm.group_scales, c.vocab_size, c.hidden_size); + r.norms_ready = true; + } + lm_rough_q6(&mut r.rough, &lm.codes, &lm.high, &lm.group_scales, &r.xn, n, c.vocab_size, c.hidden_size); + lm_pick_threshold(&mut r.thr, &r.rough, &r.wn, &r.an, &r.xn, n, c.vocab_size, c.hidden_size); + matvec_q6_rows4_pick(&mut r.logits, &lm.codes, &lm.high, &lm.group_scales, &r.xn, &r.rough, &r.wn, &r.an, &r.thr, n, c.vocab_size, c.hidden_size); + } else if n >= 3 { matvec_q6_rows4(&mut r.logits, &w.lm_head.codes, &w.lm_head.high, &w.lm_head.group_scales, &r.xn, n, c.vocab_size, c.hidden_size); } else { matvec_q6_rows(&mut r.logits, &w.lm_head.codes, &w.lm_head.high, &w.lm_head.group_scales, &r.xn, n, c.vocab_size, c.hidden_size); diff --git a/tests/round35.vx b/tests/round35.vx index 8598d5c..9cccac6 100644 --- a/tests/round35.vx +++ b/tests/round35.vx @@ -10,22 +10,24 @@ // `r` runs rounds of 6, 4, 2 and 5 tokens after a prompt, and keeps 3, 1, 2 and 5 of them with // `commit_round35`. State `b` decodes the kept tokens one at a time, and state `a`, a copy of `b` // before each round, decodes all the tokens of the round. The logits of each position of a round -// must be those of `a`, and the DeltaNet states after the commit those of `b`. Then a round of 8 -// tokens after a prompt of 2,044 tokens: its positions go past 2,048, where the attention of one -// position takes 64 SIMD groups for each head in place of 32. +// must be those of `a`, and the DeltaNet states after the commit those of `b`. Each round runs +// twice: with all the logits exact, and with the pick of the rows of lm_head (src/q6.vx), where +// the greedy tokens and their logits must be those of `a`. Then a round of 8 tokens after a +// prompt of 2,044 tokens: its positions go past 2,048, where the attention of one position takes +// 64 SIMD groups for each head in place of 32. // // RUN: python3 %S/../scripts/make_tiny_model.py --qwen35 --q4 --q6-lm-head --max-positions 2200 %t.vxw > /dev/null // RUN: vxc %s --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx -- %t.vxw | FileCheck %s // -// CHECK: {{^}}round of 6: logits 0 differ, tokens 0 differ{{$}} +// CHECK: {{^}}round of 6: logits 0 differ, tokens 0 differ, picked 0 differ{{$}} // CHECK: {{^}}keep 3: states 0 differ{{$}} -// CHECK: {{^}}round of 4: logits 0 differ, tokens 0 differ{{$}} +// CHECK: {{^}}round of 4: logits 0 differ, tokens 0 differ, picked 0 differ{{$}} // CHECK: {{^}}keep 1: states 0 differ{{$}} -// CHECK: {{^}}round of 2: logits 0 differ, tokens 0 differ{{$}} +// CHECK: {{^}}round of 2: logits 0 differ, tokens 0 differ, picked 0 differ{{$}} // CHECK: {{^}}keep 2: states 0 differ{{$}} -// CHECK: {{^}}round of 5: logits 0 differ, tokens 0 differ{{$}} +// CHECK: {{^}}round of 5: logits 0 differ, tokens 0 differ, picked 0 differ{{$}} // CHECK: {{^}}keep 5: states 0 differ{{$}} -// CHECK: {{^}}round of 8: logits 0 differ, tokens 0 differ{{$}} +// CHECK: {{^}}round of 8: logits 0 differ, tokens 0 differ, picked 0 differ{{$}} import core::convert; import core::num; import std::nn; @@ -94,6 +96,7 @@ fn states_differ(w : &Qwen35Weights, a : &Qwen35State, b : &Qwen35State) -> i32 fn check_round(w : &Qwen35Weights, rs : &mut Qwen35State, round : &mut Round35, a : &mut Qwen35State, tokens : &Vec, pos : i32) -> void { let n = tokens.len(); let want = decode(w, a, tokens, pos); + round.pick = false; run_round35(w, rs, round, tokens, pos, n); let got = transfer(&round.logits, Memory::CPU_DRAM); let next = transfer(&round.next, Memory::CPU_DRAM); @@ -114,7 +117,24 @@ fn check_round(w : &Qwen35Weights, rs : &mut Qwen35State, round : &mut Round35, tokens_differ = tokens_differ + 1; } } - println!("round of {}: logits {} differ, tokens {} differ", n, differ, tokens_differ); + // The same round with the pick of the rows of lm_head: the greedy tokens and their logits. + round.pick = true; + run_round35(w, rs, round, tokens, pos, n); + let got2 = transfer(&round.logits, Memory::CPU_DRAM); + let next2 = transfer(&round.next, Memory::CPU_DRAM); + let mut picked_differ = 0; + for t in 0..n { + let mut best = 0; + for i in 0..vocab { + if want[t * vocab + i] > want[t * vocab + best] { + best = i; + } + } + if next2[t] != best || got2[t][best].to_bits() != want[t * vocab + best].to_bits() { + picked_differ = picked_differ + 1; + } + } + println!("round of {}: logits {} differ, tokens {} differ, picked {} differ", n, differ, tokens_differ, picked_differ); return; } From 9cf9895820fd79ed4fe2277fc0af37d14fd7ca7d Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:40:45 -0800 Subject: [PATCH 45/60] docs/optimizations.md: entry 16, drafts from the MTP layer The entry gives the problem and the change. The numbers come after a run that follows the benchmarking policy. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- docs/optimizations.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/docs/optimizations.md b/docs/optimizations.md index a181788..bf8bbcc 100644 --- a/docs/optimizations.md +++ b/docs/optimizations.md @@ -317,6 +317,30 @@ 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. +### 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. + +**Result.** The numbers come after a run that follows the benchmarking policy. + ## 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, From a87d35c5115fdd5c9a332da78bec5733c46e2d24 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:40:45 -0800 Subject: [PATCH 46/60] docs/optimizations.md: entry 17, the attention and lm_head of a round The entry gives the problem and the change, and "What did not help" gets the router of 4 positions in each block. The numbers come after a run that follows the benchmarking policy. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- docs/optimizations.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/docs/optimizations.md b/docs/optimizations.md index a181788..19b7efc 100644 --- a/docs/optimizations.md +++ b/docs/optimizations.md @@ -317,6 +317,31 @@ 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. +### 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 numbers come after a run that follows the benchmarking policy. + ## 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, @@ -343,6 +368,9 @@ The text is the same as without drafts in all 24 pairs of these runs. - **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 From 4c02a06c9c5472edec5b011361a9271b3f60a258 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:40:54 -0800 Subject: [PATCH 47/60] docs/optimizations.md: entry 18, the lm_head of a round The entry gives the problem and the change. The numbers come after a run that follows the benchmarking policy. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- docs/optimizations.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/docs/optimizations.md b/docs/optimizations.md index 19b7efc..8d253f0 100644 --- a/docs/optimizations.md +++ b/docs/optimizations.md @@ -342,6 +342,33 @@ Each position keeps the bits of a plain step (`tests/round35.vx`, `tests/round.v **Result.** The numbers come after a run that follows the benchmarking policy. +### 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 numbers come after a run that follows the benchmarking policy. + ## 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, From 849480530a45399d1b441875d81232721b15f496 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Sun, 22 Nov 2026 08:01:51 -0800 Subject: [PATCH 48/60] qwen app: the MTP rows after a round in one pass After a round that keeps j drafts, the MTP layer ran j rows, one at a time, with the true h of the model, and the next round then ran the row of its first draft. These j + 1 rows have all their inputs after the round: row i takes r.xn[i] and r.next[i], the token that the round gives after position start + i. `mtp35_rows` now runs them in one pass with the kernels of the round (`nn_matvec_q4_rows`, the attention of all positions, and the experts of each row), and the last row gives the first draft of the next round. The kernels of the round have the bits of the kernels of one token, so the drafts do not change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- src/main.vx | 27 +++++++++++++++++---------- src/mtp35.vx | 52 +++++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 68 insertions(+), 11 deletions(-) diff --git a/src/main.vx b/src/main.vx index 70b096c..dee0bfa 100644 --- a/src/main.vx +++ b/src/main.vx @@ -608,12 +608,18 @@ fn generate_with_mtp35(w : &Qwen35Weights, s : &mut Qwen35State, m : &mut Mtp35S // 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..max + 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; @@ -643,8 +649,12 @@ fn generate_with_mtp35(w : &Qwen35Weights, s : &mut Qwen35State, m : &mut Mtp35S going = show(t, eos, text_mode, step, token, logit); } else { // Draft j + 1, from row pos - 1 + j of the MTP layer, goes to slots[j]. - m.token = upload_token(token); - for j in 0..k { + if !first_draft { + m.token = upload_token(token); + mtp35_step(w, s, m, pos - 1, true, vocab); + } + 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); } @@ -681,15 +691,12 @@ fn generate_with_mtp35(w : &Qwen35Weights, s : &mut Qwen35State, m : &mut Mtp35S } } // 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 - 1 then run with the true h of positions pos to pos + j - 1 - // and the kept drafts; h of position pos + j is the input of the next round. + // 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); - for i in 0..j { - take_row(&mut m.h, &r.xn, i, c.hidden_size); - m.token = upload_token(draft[i]); - mtp35_step(w, s, m, pos + i, false, vocab); - } - take_row(&mut m.h, &r.xn, j, c.hidden_size); + mtp35_rows(w, s, &mut r, m, pos, j + 1, vocab); + first_draft = true; pos = pos + j + 1; } } diff --git a/src/mtp35.vx b/src/mtp35.vx index d51f233..6e72e0d 100644 --- a/src/mtp35.vx +++ b/src/mtp35.vx @@ -26,16 +26,21 @@ import qwen::prefill; import qwen::prefill35; import qwen::products; import qwen::qwen35; +import qwen::round; +import qwen::round35; import qwen::weights; /// The state of the MTP layer: its KV cache, and `token` and `h`, the inputs of the next row. -/// `cat` holds the two norms of a row, the embedding first, for `fc`. +/// `cat` holds the two norms of a row, the embedding first, for `fc`. `cat_rows` and `proj` are +/// for the rows of `mtp35_rows`. struct Mtp35State { k : Tensor, v : Tensor, token : Tensor, h : Tensor, cat : Tensor, + cat_rows : Tensor, + proj : Tensor, } /// The MTP state for the `max_seq` positions of `s`. @@ -48,6 +53,8 @@ fn new_mtp35_state(c : &Config, max_seq : i32) -> Mtp35State { token: transfer(Tensor([1]), Memory::HBM), h: transfer(Tensor([c.hidden_size]), Memory::HBM), cat: transfer(Tensor([2 * c.hidden_size]), Memory::HBM), + cat_rows: transfer(Tensor([ROUND_MAX, 2 * c.hidden_size]), Memory::HBM), + proj: transfer(Tensor([ROUND_MAX, (2 * c.num_q_heads + 2 * c.num_kv_heads) * 256]), Memory::HBM), }; } @@ -59,6 +66,8 @@ fn new_mtp35_state_none() -> Mtp35State { token: transfer(Tensor([1]), Memory::HBM), h: transfer(Tensor([1]), Memory::HBM), cat: transfer(Tensor([1]), Memory::HBM), + cat_rows: transfer(Tensor([1, 1]), Memory::HBM), + proj: transfer(Tensor([1, 1]), Memory::HBM), }; } @@ -187,6 +196,47 @@ fn mtp35_step(w : &Qwen35Weights, s : &mut Qwen35State, m : &mut Mtp35State, pos return; } +/// Rows start to start + n - 1 of the MTP layer after a round at `start` that keeps n tokens, then +/// the draft of the last row, with the bits of `mtp35_step` for each row in turn. Row i takes h +/// of position start + i, r.xn[i], and r.next[i], the token that the round gives after it. The +/// rows use the kernels and the tensors of the round, so they come after `commit_round35`. After +/// them, m.token and m.h are the inputs of the next draft. +fn mtp35_rows(w : &Qwen35Weights, s : &mut Qwen35State, r : &mut Round35, m : &mut Mtp35State, start : i32, n : i32, vocab : i32) -> void { + let c = &w.config; + let eps = c.rms_norm_eps as f32; + let hidden = c.hidden_size; + let qkv_rows = (2 * c.num_q_heads + 2 * c.num_kv_heads) * 256; + assert(w.mtp.len() == 1 && n >= 1 && n <= ROUND_MAX && start + n <= s.max_seq, "mtp35_rows: the model needs an MTP layer, and the rows must fit in the KV cache"); + assert(vocab >= 8 && vocab % 8 == 0 && vocab <= c.vocab_size, "mtp35_rows: vocab must be a multiple of 8, up to the vocabulary of the model"); + let mtp = &w.mtp[0]; + let layer = &mtp.layer; + assert(mtp.fc.dtype == U4 && layer.qkv.dtype == U4 && layer.attn_out.dtype == U4 && layer.gate_up.dtype == U4, "mtp35_rows: the MTP layer must be Q4_0"); + pf35_rms_norm_at(&mut m.cat_rows, hidden, &r.xn, &mtp.hidden_norm, n, hidden, eps); + nn_embed_rows(&mut r.x, &w.embed, &r.next, n, hidden); + pf35_rms_norm_at(&mut m.cat_rows, 0, &r.x, &mtp.embed_norm, n, hidden, eps); + nn_matvec_q4_rows(&mut r.x, &mtp.fc.codes, &mtp.fc.group_scales, &m.cat_rows, n, hidden, 2 * hidden); + rms_norm_f32_rows(&mut r.xn, &r.x, &layer.attn_norm, n, hidden, eps); + nn_matvec_q4_rows(&mut m.proj, &layer.qkv.codes, &layer.qkv.group_scales, &r.xn, n, qkv_rows, hidden); + pf_gated_norm_rope_and_store(&mut r.q, &mut m.k, &mut m.v, &m.proj, &layer.q_norm, &layer.k_norm, &s.cos, &s.sin, start, n, c.num_q_heads, c.num_kv_heads, c.rotary_dim, eps); + gated_attention_rows(&mut r.y, &mut r.parts, &r.q, &m.k, &m.v, &m.proj, start, n, c.num_q_heads, c.num_kv_heads); + nn_matvec_q4_rows(&mut r.add, &layer.attn_out.codes, &layer.attn_out.group_scales, &r.y, n, hidden, c.num_q_heads * 256); + add_rows(&mut r.x, &r.add, n, hidden); + rms_norm_f32_rows(&mut r.xn, &r.x, &layer.mlp_norm, n, hidden, eps); + let k = c.experts_per_token; + nn_matvec_rows(&mut r.router, &layer.router, &r.xn, n, c.num_experts + 1, hidden); + nn_top_k_rows(&mut r.ids, &mut r.weights, &r.router, n, c.num_experts, k); + shared_gate_rows(&mut r.shared_weight, &r.router, n, c.num_experts); + moe_swiglu_q4_blocks_rows(&mut r.mlp, &layer.gate_up.codes, &layer.gate_up.group_scales, &r.ids, &r.xn, n, k, c.moe_intermediate_size, hidden, c.num_experts); + moe_down_q4_add_blocks_rows(&mut r.x, &layer.down.codes, &layer.down.group_scales, &r.ids, &r.weights, &r.mlp, n, k, hidden, c.moe_intermediate_size, c.num_experts); + moe_swiglu_q4_blocks_rows(&mut r.shared_mlp, &layer.shared_gate_up.codes, &layer.shared_gate_up.group_scales, &r.shared_ids, &r.xn, n, 1, c.shared_expert_inter, hidden, 1); + moe_down_q4_add_blocks_rows(&mut r.x, &layer.shared_down.codes, &layer.shared_down.group_scales, &r.shared_ids, &r.shared_weight, &r.shared_mlp, n, 1, hidden, c.shared_expert_inter, 1); + rms_norm_f32_rows(&mut r.xn, &r.x, &mtp.final_norm, n, hidden, eps); + take_row(&mut m.h, &r.xn, n - 1, hidden); + matvec(&mut s.logits, &w.lm_head, &m.h, vocab, hidden); + nn_argmax(&mut m.token, &s.logits, vocab); + return; +} + /// Rows start to start + n - 1 of the MTP layer, after `pf35_chunk` ran positions start to /// start + n - 1 of the prompt: the hidden states of the model are in p.x, and `next_tokens` has /// the token after each, prompt[start + 1] to prompt[start + n]. `cat` is [rows of p.x, 2 * From 931b96e471c8b8a5fc628bdb2dc887c5d5682cc7 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:14:16 -0800 Subject: [PATCH 49/60] qwen app: a second length of MTP drafts (--mtp K,L) With --mtp K,L, a round drafts L tokens while the running mean of the kept drafts is at least MTP_LONGER_SHARE (0.95), K tokens while it is at least MTP_LONG_SHARE (0.85), and 1 token otherwise. A third number, --mtp K,L,P, sets the first share to P percent. --mtp K is as before. tests/generate_qwen35.vx: --mtp 3,5,0 drafts 5 tokens in each round, and gives the steps of plain decoding. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- src/main.vx | 38 +++++++++++++++++++++++++++----------- tests/generate_qwen35.vx | 6 ++++++ 2 files changed, 33 insertions(+), 11 deletions(-) diff --git a/src/main.vx b/src/main.vx index dee0bfa..de78f53 100644 --- a/src/main.vx +++ b/src/main.vx @@ -547,6 +547,9 @@ fn generate_with_drafts35(w : &Qwen35Weights, s : &mut Qwen35State, t : &Tokeniz /// (`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; + /// 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. @@ -574,10 +577,12 @@ fn upload_token(token : i32) -> Tensor { /// 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(w : &Qwen35Weights, s : &mut Qwen35State, m : &mut Mtp35State, t : &Tokenizer, eos : i32, text_mode : bool, prompt : &Vec, first : i32, steps : i32, max : i32, vocab : i32, start : &mut Instant) -> i32 { +fn generate_with_mtp35(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, 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"); + let most = i32::max(max, long); let c = &w.config; let mut r = new_round35(c); let mut slots = Vec::new(); @@ -611,7 +616,7 @@ fn generate_with_mtp35(w : &Qwen35Weights, s : &mut Qwen35State, m : &mut Mtp35S // 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..max + 2 { + 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); @@ -628,7 +633,9 @@ fn generate_with_mtp35(w : &Qwen35Weights, s : &mut Qwen35State, m : &mut Mtp35S let mut kept : f64 = MTP_LONG_SHARE; while going && step + 1 < steps { let room = steps - step - 1; - let want = if kept >= MTP_LONG_SHARE { + let want = if long > max && kept >= long_share { + long + } else if kept >= MTP_LONG_SHARE { max } else { 1 @@ -708,7 +715,7 @@ fn generate_with_mtp35(w : &Qwen35Weights, s : &mut Qwen35State, m : &mut Mtp35S /// `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(path : *const i8, t : &Tokenizer, text_mode : bool, chat : bool, ignore_eos : bool, prompt : &Vec, steps : i32, draft : i32, mtp : i32, mtp_vocab : i32, runs : i32) -> i32 { +fn run_qwen35(path : *const i8, t : &Tokenizer, text_mode : bool, chat : bool, ignore_eos : bool, prompt : &Vec, steps : i32, draft : i32, mtp : i32, mtp_long : i32, mtp_share : f64, mtp_vocab : i32, runs : i32) -> i32 { let w = load_qwen35_weights(path); let eos = if ignore_eos { -1 @@ -809,7 +816,7 @@ fn run_qwen35(path : *const i8, t : &Tokenizer, text_mode : bool, chat : bool, i } else { i32::min(MTP_VOCAB, w.config.vocab_size) }; - decoded = generate_with_mtp35(&w, &mut s, &mut m, t, eos, text_mode, prompt, tokens[0], steps, mtp, vocab, &mut start); + decoded = generate_with_mtp35(&w, &mut s, &mut m, t, eos, text_mode, prompt, tokens[0], steps, mtp, mtp_long, mtp_share, vocab, &mut start); } for step in 0..steps { if draft > 0 || mtp > 0 { @@ -890,17 +897,26 @@ fn main(argc : i32, argv : *mut *mut i8) -> i32 { 1 }; assert(runs >= 1, "--prompt-runs must be at least 1"); - let mtp = if o.has_mtp { - parse_numbers(o.mtp)[0] - } else { - 0 - }; + 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(o.weights, &t, text_mode, o.chat, o.ignore_eos, &prompt, steps, draft, mtp, mtp_vocab, runs); + return run_qwen35(o.weights, &t, text_mode, o.chat, o.ignore_eos, &prompt, steps, draft, 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(o.weights); diff --git a/tests/generate_qwen35.vx b/tests/generate_qwen35.vx index 937351e..9aa6352 100644 --- a/tests/generate_qwen35.vx +++ b/tests/generate_qwen35.vx @@ -16,6 +16,8 @@ // layer and without --mtp: the lines of the steps must be the same, logits too. The prompt has // 2,100 tokens, so the rows of the MTP layer for the prompt run in 2 chunks. The MTP layer of // the tiny model has random weights, so its drafts are not those of the model. +// - the same with --mtp 3,5,0: the second length of drafts (5) from a kept share of 0%, so each +// round drafts 5 tokens and checks 6 positions. // // The products of a chunk round each Q4_0 weight, (code - 8) times its scale, to f16, as for the // Qwen3 models. So the Q4_0 files get 0.003, as in tests/prefill.vx, and the bf16 files 0.001. @@ -60,6 +62,10 @@ // RUN: diff %t-long24.steps %t-mtp.steps // RUN: grep -c step= %t-mtp.steps | FileCheck %s --check-prefix=MTP-STEPS // RUN: grep rounds= %t-mtp.vx | FileCheck %s --check-prefix=MTP +// RUN: vxc %S/../src/main.vx --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx -- %t-mtp.vxw --tokens $(cat %t-long.ids) --steps 24 --mtp 3,5,0 > %t-mtp5.vx +// RUN: grep step= %t-mtp5.vx > %t-mtp5.steps +// RUN: diff %t-long24.steps %t-mtp5.steps +// RUN: grep rounds= %t-mtp5.vx | FileCheck %s --check-prefix=MTP // // CHECK: 16 steps, same tokens, logits within 0.001 // Q4: 16 steps, same tokens, logits within 0.003 From 9ac308b418f963c335e84257b0e7f2628578ead2 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:11:12 -0800 Subject: [PATCH 50/60] docs/optimizations.md: entry 16, the MTP rows in one pass and --mtp K,L Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- docs/optimizations.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/optimizations.md b/docs/optimizations.md index a19afd6..7e637d5 100644 --- a/docs/optimizations.md +++ b/docs/optimizations.md @@ -353,7 +353,12 @@ logits for position p + 2. llama.cpp uses this layer for its drafts. `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. +- 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.** The numbers come after a run that follows the benchmarking policy. From 0c773e43319adb46a4eac6798f137b6514957292 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:38:00 -0800 Subject: [PATCH 51/60] qwen app: drafts from the context in --mtp rounds (--draft D[,M] with --mtp) With --mtp and --draft D, a round first looks for the longest match in the context. When the match has at least M tokens (default 12), the round takes up to D drafts from the tokens after the match. Otherwise the round takes MTP drafts as before. Only MTP rounds change the kept-share average. The MTP rows still run after every round, so the next MTP draft is ready. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- src/main.vx | 98 +++++++++++++++++++++++++++++++--------- tests/generate_qwen35.vx | 10 ++++ 2 files changed, 86 insertions(+), 22 deletions(-) diff --git a/src/main.vx b/src/main.vx index de78f53..e310c2b 100644 --- a/src/main.vx +++ b/src/main.vx @@ -550,6 +550,10 @@ 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. +const MTP_CONTEXT_MATCH : i32 = 12; + /// 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. @@ -577,12 +581,13 @@ fn upload_token(token : i32) -> Tensor { /// 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(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, vocab : i32, start : &mut Instant) -> i32 { +fn generate_with_mtp35(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"); - let most = i32::max(max, long); + 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(); @@ -592,6 +597,11 @@ fn generate_with_mtp35(w : &Qwen35Weights, s : &mut Qwen35State, m : &mut Mtp35S }); } 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); @@ -606,6 +616,7 @@ fn generate_with_mtp35(w : &Qwen35Weights, s : &mut Qwen35State, m : &mut Mtp35S 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(t, eos, text_mode, step, token, read_logit(&s.logits, token)); @@ -631,6 +642,9 @@ fn generate_with_mtp35(w : &Qwen35Weights, s : &mut Qwen35State, m : &mut Mtp35S 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 { @@ -640,13 +654,29 @@ fn generate_with_mtp35(w : &Qwen35Weights, s : &mut Qwen35State, m : &mut Mtp35S } else { 1 }; - let k = i32::min(want, room - 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; @@ -656,18 +686,25 @@ fn generate_with_mtp35(w : &Qwen35Weights, s : &mut Qwen35State, m : &mut Mtp35S going = show(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); } - 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); - } let mut draft = Vec::new(); - for j in 0..k { - draft.push(read_token(&slots[j].next)); + 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); @@ -678,10 +715,15 @@ fn generate_with_mtp35(w : &Qwen35Weights, s : &mut Qwen35State, m : &mut Mtp35S 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 { @@ -692,8 +734,12 @@ fn generate_with_mtp35(w : &Qwen35Weights, s : &mut Qwen35State, m : &mut Mtp35S if more { accepted = accepted + 1; j = j + 1; - kept = kept * 0.9 + 0.1; - } else if j < k { + 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; } } @@ -707,6 +753,9 @@ fn generate_with_mtp35(w : &Qwen35Weights, s : &mut Qwen35State, m : &mut Mtp35S 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; } @@ -715,7 +764,7 @@ fn generate_with_mtp35(w : &Qwen35Weights, s : &mut Qwen35State, m : &mut Mtp35S /// `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(path : *const i8, t : &Tokenizer, text_mode : bool, chat : bool, ignore_eos : bool, prompt : &Vec, steps : i32, draft : i32, mtp : i32, mtp_long : i32, mtp_share : f64, mtp_vocab : i32, runs : i32) -> i32 { +fn run_qwen35(path : *const i8, 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(path); let eos = if ignore_eos { -1 @@ -806,8 +855,9 @@ fn run_qwen35(path : *const i8, t : &Tokenizer, text_mode : bool, chat : bool, i } let mut start = Instant::now(); let mut decoded = 0; - assert(draft == 0 || mtp == 0, "give --draft or --mtp, not both"); - if draft > 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(&w, &mut s, t, eos, text_mode, prompt, tokens[0], steps, draft, &mut start); } if mtp > 0 { @@ -816,7 +866,7 @@ fn run_qwen35(path : *const i8, t : &Tokenizer, text_mode : bool, chat : bool, i } else { i32::min(MTP_VOCAB, w.config.vocab_size) }; - decoded = generate_with_mtp35(&w, &mut s, &mut m, t, eos, text_mode, prompt, tokens[0], steps, mtp, mtp_long, mtp_share, vocab, &mut start); + decoded = generate_with_mtp35(&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 { @@ -886,11 +936,15 @@ fn main(argc : i32, argv : *mut *mut i8) -> i32 { assert(steps > 0, "--steps must be at least 1"); if weight_file_arch(o.weights) == 1 { - let draft = if o.has_draft { - parse_numbers(o.draft)[0] - } else { - 0 - }; + 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 { @@ -916,7 +970,7 @@ fn main(argc : i32, argv : *mut *mut i8) -> i32 { } else { 0 }; - return run_qwen35(o.weights, &t, text_mode, o.chat, o.ignore_eos, &prompt, steps, draft, mtp, mtp_long, mtp_share, mtp_vocab, runs); + return run_qwen35(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(o.weights); diff --git a/tests/generate_qwen35.vx b/tests/generate_qwen35.vx index 9aa6352..6d54f53 100644 --- a/tests/generate_qwen35.vx +++ b/tests/generate_qwen35.vx @@ -18,6 +18,9 @@ // the tiny model has random weights, so its drafts are not those of the model. // - the same with --mtp 3,5,0: the second length of drafts (5) from a kept share of 0%, so each // round drafts 5 tokens and checks 6 positions. +// - the Q4_0 file with the MTP layer with --mtp 3 --draft 7,2, after the prompt of the --draft +// test: a round drafts 7 tokens from the context, the other rounds draft from the MTP layer, and +// the steps are those of the file without the MTP layer and without drafts. // // The products of a chunk round each Q4_0 weight, (code - 8) times its scale, to f16, as for the // Qwen3 models. So the Q4_0 files get 0.003, as in tests/prefill.vx, and the bf16 files 0.001. @@ -66,6 +69,12 @@ // RUN: grep step= %t-mtp5.vx > %t-mtp5.steps // RUN: diff %t-long24.steps %t-mtp5.steps // RUN: grep rounds= %t-mtp5.vx | FileCheck %s --check-prefix=MTP +// RUN: vxc %S/../src/main.vx --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx -- %t-long.vxw --tokens 31,41,59,26,53,58,97,93,23,84,109,99,62,64,33,83,27,31,41,59,26,53,58,97,93,23,84 --steps 32 > %t-long-plain.vx +// RUN: vxc %S/../src/main.vx --package qwen=%S/../src --host default --machine $VX_FLEET/m4-uma.vx -- %t-mtp.vxw --tokens 31,41,59,26,53,58,97,93,23,84,109,99,62,64,33,83,27,31,41,59,26,53,58,97,93,23,84 --steps 32 --mtp 3 --draft 7,2 > %t-mtp-context.vx +// RUN: grep step= %t-long-plain.vx > %t-long-plain.steps +// RUN: grep step= %t-mtp-context.vx > %t-mtp-context.steps +// RUN: diff %t-long-plain.steps %t-mtp-context.steps +// RUN: grep context_drafts: %t-mtp-context.vx | FileCheck %s --check-prefix=MTP-CONTEXT // // CHECK: 16 steps, same tokens, logits within 0.001 // Q4: 16 steps, same tokens, logits within 0.003 @@ -76,3 +85,4 @@ // RUNS: {{^}}3{{$}} // MTP-STEPS: {{^}}24{{$}} // MTP: rounds={{[0-9]+}} drafted={{[0-9]+}} accepted={{[0-9]+}}; +// MTP-CONTEXT: context_drafts: rounds=1 drafted=7 kept=0; From b7d48d6fff2b62afb239932248c84c43f157b033 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:04:48 -0800 Subject: [PATCH 52/60] qwen app: drafts from the context in --mtp rounds need a match of 16 A shorter match often gives drafts that the round does not keep, and such a round costs more than the MTP round that it replaces. On the tuning prompts, matches of 12 made complete1 and write2 slower, and matches of 16 found only the repeats of the edit prompts. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- src/main.vx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main.vx b/src/main.vx index e310c2b..d6bd8de 100644 --- a/src/main.vx +++ b/src/main.vx @@ -551,8 +551,10 @@ const MTP_LONG_SHARE : f64 = 0.85; 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. -const MTP_CONTEXT_MATCH : i32 = 12; +/// 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 From f33743dd7f1a94ffef0edb0afda6107a5d6bfb5b Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:08:10 -0800 Subject: [PATCH 53/60] docs: entry 19 and the README, drafts from the context with --mtp Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- README.md | 4 ++++ docs/optimizations.md | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/README.md b/README.md index 46a107f..8906158 100644 --- a/README.md +++ b/README.md @@ -118,6 +118,10 @@ pip install -r requirements.txt 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 diff --git a/docs/optimizations.md b/docs/optimizations.md index 7043204..241a334 100644 --- a/docs/optimizations.md +++ b/docs/optimizations.md @@ -414,6 +414,27 @@ not read them. **Result.** The numbers come after a run that follows the benchmarking policy. +### 19. Drafts from the context in the rounds of the MTP drafts + +**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.** The numbers come after a run that follows the benchmarking policy. + ## 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, From 730f1b70d1f9665259c63e890ad63a4f401bb506 Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:08:40 -0800 Subject: [PATCH 54/60] docs/optimizations.md: the PR number of entry 19 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014U9gTxfQzAEpmg4WJhYQqw --- docs/optimizations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/optimizations.md b/docs/optimizations.md index 241a334..d344d32 100644 --- a/docs/optimizations.md +++ b/docs/optimizations.md @@ -414,7 +414,7 @@ not read them. **Result.** The numbers come after a run that follows the benchmarking policy. -### 19. Drafts from the context in the rounds of the MTP drafts +### 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 From 4b92449d0f2f224bf6e131f116c670f140ee83ce Mon Sep 17 00:00:00 2001 From: Aditya <1894981+hiraditya@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:19:20 -0800 Subject: [PATCH 55/60] Give each function the level that its callers need, for the private functions of Vx In Vx after v0.0.5, a function with no level is private to its file. pkg makes it visible to the files of its package (qwen, the files in src/), and pub to every file. So this gives 64 functions pub and 53 pkg, each the narrowest level that its callers need. src/main.vx, tests/ and decode/ are not in the package qwen, so a function that they call is pub. The C functions strlen and write, which two files declare, are pkg. Vx now also needs unsafe around an mlir! block, so the 21 blocks of attention, prefill, prefill35, round and simd are inside unsafe { }. core::ptr now has a pub write_bytes, which clashed with the private write_bytes of tokenizer.vx in tests/tokenize.vx. The tokenizer's function is now pub print_bytes. tests/tokenize.vx compares C strings with string_length of std::string, not with the pkg strlen of the package. With the vxc of Vx PR #3975 (main d3ed6cf0b and root.args), the 114 RUN lines of tests/ and the 43 Python tests of scripts/ pass. VX_VERSION stays v0.0.5 until a Vx release has these rules. --- src/attention.vx | 20 ++++++++-------- src/deltanet.vx | 8 +++---- src/gated_attention.vx | 10 ++++---- src/model.vx | 14 +++++------ src/mtp35.vx | 14 +++++------ src/prefill.vx | 54 +++++++++++++++++++++--------------------- src/prefill35.vx | 26 ++++++++++---------- src/products.vx | 8 +++---- src/q6.vx | 14 +++++------ src/qwen35.vx | 10 ++++---- src/round.vx | 42 ++++++++++++++++---------------- src/round35.vx | 20 ++++++++-------- src/session.vx | 4 ++-- src/simd.vx | 30 +++++++++++------------ src/speculate.vx | 14 +++++------ src/tokenizer.vx | 26 ++++++++++---------- src/weights.vx | 10 ++++---- tests/tokenize.vx | 9 +++---- 18 files changed, 167 insertions(+), 166 deletions(-) diff --git a/src/attention.vx b/src/attention.vx index a926ab6..8285ee6 100644 --- a/src/attention.vx +++ b/src/attention.vx @@ -24,7 +24,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); @@ -51,7 +51,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); @@ -70,7 +70,7 @@ 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]); } @@ -85,7 +85,7 @@ fn vec_attention_parts(part : &mut Tensor, q : &Ten 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])]) { + let _d = unsafe { 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 @@ -162,7 +162,7 @@ fn vec_attention_parts(part : &mut Tensor, q : &Ten memref.store %st#1, %part[%hi, %wi, %c129] : memref } macro.yield %h : i32 - }; + } }; } } } @@ -175,7 +175,7 @@ fn vec_attention_parts(part : &mut Tensor, q : &Ten 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])]) { + let _d = unsafe { 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 @@ -282,7 +282,7 @@ fn vec_attention_merge(out : &mut Tensor, part : &Tens } } macro.yield %h : i32 - }; + } }; } } return; @@ -291,7 +291,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 { @@ -794,7 +794,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); @@ -834,7 +834,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 index 75310eb..fb86675 100644 --- a/src/deltanet.vx +++ b/src/deltanet.vx @@ -39,7 +39,7 @@ struct DeltaNetScratch { o : Tensor, } -fn deltanet_scratch(k_heads : i32, v_heads : i32) -> DeltaNetScratch { +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), @@ -64,11 +64,11 @@ fn dn_zeros(a : i32, b : i32, c : i32) -> Tensor { } /// The state of one layer at the start: zero. -fn deltanet_conv_state(k_heads : i32, v_heads : i32) -> Tensor { +pub 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 { +pub fn deltanet_state(v_heads : i32) -> Tensor { return dn_zeros(v_heads, 128, 128); } @@ -76,7 +76,7 @@ fn deltanet_state(v_heads : i32) -> Tensor { /// (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 { +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]"); diff --git a/src/gated_attention.vx b/src/gated_attention.vx index 527f103..77a95ad 100644 --- a/src/gated_attention.vx +++ b/src/gated_attention.vx @@ -25,7 +25,7 @@ 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 { +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"); @@ -80,7 +80,7 @@ fn gated_norm_rope_and_store(q_out : &mut Tensor, k_ca /// 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 { +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"); @@ -96,7 +96,7 @@ fn gated_attention(y : &mut Tensor, part : &mut Tensor Tensor { +pub fn gated_attention_scratch(q_heads : i32) -> Tensor { return Tensor([q_heads, 64, 260]); } @@ -262,7 +262,7 @@ fn gated_attention_merge(y : &mut Tensor, part : &Tensor< /// 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`. -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 { +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"); @@ -273,7 +273,7 @@ fn gated_attention_rows(y : &mut Tensor, part : &mut T } /// The scratch space of `gated_attention_rows` for up to n positions, on the CPU. -fn gated_attention_rows_scratch(n : i32, q_heads : i32) -> Tensor { +pkg fn gated_attention_rows_scratch(n : i32, q_heads : i32) -> Tensor { return Tensor([n, q_heads, 64, 260]); } 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