Skip to content

qdot: Q4_K's one-column kernel, tile and row lanes get AVX-512 VNNI bodies, picked at run time and bit-identical to the AVX2 ones - #86

Merged
midagedev merged 9 commits into
midagedev:mainfrom
juliankang4:qdot-avx512-q4k
Oct 14, 2026
Merged

midagedev merged 9 commits into
midagedev:mainfrom
juliankang4:qdot-avx512-q4k

Conversation

@juliankang4

@juliankang4 juliankang4 commented Oct 12, 2026 •

Copy link
Copy Markdown
Collaborator

What and why

Q4_K's two host kernels against Q8_2_X4 columns, the tile behind dot_row and dot_row_cols and the row lanes behind
dot_lanes_cols, get AVX-512 VNNI bodies that write the AVX2 kernels' bits and are picked at run time on a CPU with
AVX-512 F, BW and VNNI. On one Zen 5 desktop (Ryzen 9 9950X), prefill on Qwen3.6-35B-A3B Q4_K_M is 5.9 % (± 0.8)
faster at 474 prompt tokens and 6.2 % (± 0.7) at 3,681 than with BLOOMERY_QDOT_AVX512=0 in the same binary, and
decode shows no difference I could measure. This is step 2 of #81 for Q4_K only; step 1 and the other types stay open,
so there is no Closes line.

How it works

The two bodies:

  • dot_q4k_q82x4_tile_avx512::<C> is the tile behind dot_row_cols (C = 2..8). At C = 1 it is also dot_row's Q4_K
    kernel, which decode uses.
  • dot_lanes_avx512::<C> is the row-lane dot behind dot_lanes_cols, which a prompt batch's host experts use.
    pack_lanes keeps its AVX2 body in both arms.

With the lever at 0, every out-of-line AVX2 kernel and every tile::<C> is main's machine code. The AVX2 lanes
inline into dot_lanes_cols, which differs from main's as a whole (under "Machine code").

Bits

The integer sums move from maddubs and madd to vpdpbusd. Q4_K codes are at most 15 and the activation
codes lie in [-128, 127], so neither instruction saturates and both give the exact sum. The float side keeps the
AVX2 kernels' products and fused adds in each lane, in their order: fma(my, mins), then the two sub-block halves,
then hsum_float_8. In the tile, a zmm holds sub-block t beside sub-block 4 + t, and a 4x4 transpose per 128-bit
lane puts the sums in the lanes of the AVX2 kernel's sumi_0 and sumi_1. In the row lanes, a zmm carries two
columns (column 2p in the low half, 2p + 1 in the high half; an odd C pairs its last column with itself), and each
half does what one ymm does in dot_lanes_avx2.

Selection

qdot::q4k_avx512() decides once per process. It is true when the CPU has AVX-512 F, BW and VNNI on top of what
has_features asks for, and BLOOMERY_QDOT_AVX512 is unset or 1. 0 keeps the AVX2 bodies in the same binary,
which is how the numbers below were taken. The maintainer chose to keep the default on, the in-place read and the
lever's name, and to revisit the default if another CPU reports a slowdown.

Any other value panics with the lever's name. q4k_avx512() is one function on every architecture: it reads and
checks the lever first, and only then asks the CPU. Off x86_64 no AVX-512 body is compiled, so its answer there is
false, but a bad value still panics.

The panic comes while the host tier is built, before the server listens. model::ops::host_stack_runs calls
q4k_avx512() first for each Q4_K stack, before it asks whether qdot has a kernel for the type, so an x86_64 CPU
without AVX2 also gets the lever's name. Every family's HostLayer::build runs that check on its routed stacks at
load. The first call reads the lever; later calls get the cached answer. The new test
host_layer_build_refuses_a_qdot_lever_value_by_name holds this (under "Lever value at load").

Two cases stay outside the load check. A host tier with no Q4_K stack never reads the lever, and none of its kernels
depend on it. The CPU engine (bloomery-decode) builds no host tier and reads the lever at its first Q4_K dot: every
Q4_K dot_row asks q4k_avx512(), also where it runs the scalar mirror (off x86_64, or on an x86_64 CPU without
AVX2). The new test dot_row_refuses_a_qdot_lever_value_by_name holds this. I did not run bloomery-decode with a
refused value, so how it ends after that panic is not checked.

The release build stays x86-64-v3: the new bodies carry their own #[target_feature], so the release binary has
them and picks them at run time. tools/release/build.sh refuses an instruction past x86-64-v3 outside the
functions it lists as runtime-dispatched, and since cff55213 it reads each instruction's encoding, so AVX-512 at any
vector width counts. Its DISPATCHED pattern now also names qdot::dot_q4k_q82x4_tile_avx512::<C> and
qdot::dot_lanes_avx512::<C>, under a dated PIN(2026-10-12) comment that names the CPU check every caller passes
first (AVX-512 F, BW and VNNI beside the AVX2 kernels' AVX2, FMA and F16C). The check and its FAIL-first are under
"Static checks".

The lever's registry row places the read in crates/qdot/src/lib.rs under the round isa-owner
(tools/levers-direct.txt). The AVX-512 gate in crates/qdot/tests/qdot.rs also reads the lever, to know which body
q4k_avx512() must pick, so the list's line for that file names it too. When the step 1 owner lands, q4k_avx512 can
become a row of its per-type table, and the lever can stay as that owner's override or go. I did not try to build the
owner here.

Where each entry picks its body

Each entry asks q4k_avx512() once per call, before it reaches any AVX2 code:

  • dot_row has a guard arm ahead of its Q4_K arm, and a Q4_K arm of its own for a CPU without AVX2, which asks
    q4k_avx512() and runs the scalar mirror. Reading the selector once at the top of dot_row would do the same, but
    at x86-64-v3 it made the compiler inline the AVX2 Q4_K kernel into dot_row; the extra arm leaves every kernel
    as it was (under "Machine code").
  • dot_row_cols picks before its column-count match and calls tile_q4k_avx512::<C>. One local macro maps the
    column count to C for both tiles. tile::<C>, which inlines the AVX2 tiles of Q4_K, Q5_K and the other tiled
    types, is main's machine code.
  • dot_lanes_cols computes a LaneKind (Q45K, Q4KAvx512 or Q6K) once, and lanes::<C> matches on it.

Commits

Nine commits on main 33fb317b. The six after the maintainer's answer the third review, one contract each:

  • f566d8ba: the AVX-512 bodies, the lever and the release check.
  • 2e31d011 and 0f4d36e6, the maintainer's: the first two reviews folded in (one unsafe block per operation, the
    selector assertion, and the test layout under "Bit checks").
  • ef6e0c45 (qdot): the three shared helpers in the Q4_K and Q5_K kernels and the two AVX-512 bodies, which also lose
    their extra block level, and the re-pinned unsafe count. The output bits do not change.
  • 2fb45954 (qdot): dot_row_cols picks the AVX-512 tile before tile::<C>, which is main's code again, and
    dot_lanes_cols picks a LaneKind once a call.
  • 4052f514 (qdot tests): one owner for Q4_K's synthetic rows, q4k_synthetic_rows().
  • d9119c85 (qdot, model): the behaviour change. A refused lever value stops every Q4_K dot_row on every
    architecture and the host tier's load, with the two refusal tests, the row in tools/defaults-twins.tsv and the
    lever's line in tools/levers-direct.txt.
  • e4412d01 (release): the dated PIN above the AVX-512 entries of DISPATCHED.
  • 0094a925 (docs): the docs the change makes stale (under "Docs").

The branch was rebased from main f1a3e9e4 onto 33fb317b, because cff55213 rewrote the host-code check in
tools/release/build.sh. The first commit's two changes there, the new DISPATCHED entry and the qdot clause in the
comment above the scan, now sit in the new check unchanged. Every other commit's diff is the same as before, and each
commit keeps its author. Before the rebase, the three commits already on this PR were 43e75820 and the maintainer's
ad7a4cb9 and 9cc1a203, and this branch's head was f8e32756. crates/qdot is the same tree at each commit
before and after.

qdot's line in tools/unsafe-ratchet.txt goes from 141 blocks and 77 fns on main to 172 and 80 (the count is under
"Code shape").

The earlier builds that "What I ran" cites are not part of this PR: 38af59aa, 5cc0a477, 435b51ac, 013f098e,
5df92e10, b0ff0ac9, 8e816da5, fbf33c06 (this branch's head before the split above, with the same code apart
from the review's fixes) and f8e32756 (the head before the rebase). Each is on the fork as a branch named
qdot-avx512-q4k-measured-<hash>, so the hashes resolve.

Docs

These lines said the host kernels are AVX2 only. They now say Q4_K's switch to AVX-512 VNNI on a CPU that has it:

  • README.md:219 ("CPU experts at memory speed")
  • docs/performance.md:70 (the same item)
  • tools/release/README.release.md:3-4, and its requirements line now adds that AVX-512 is optional.

AGENTS.md:3-4 ("AVX2 kernels for the CPU expert tier") and AGENTS.md:128 (crates/qdot/ fused quantized dot kernels, AVX2) say the same. I left AGENTS.md to the maintainer, since it is the project's working contract.

What I ran into

The choice inside tile

An earlier version of this branch (435b51ac) put the guard arm inside tile::<C>. That changed the register
allocation of the whole function, so the AVX2 arms got slower too. tile::<4> went from 249 stack stores and 346
stack loads to 276 and 363, and at k = 512 its AVX2 arm ran 4.3 % (-7.7..-3.5) slower than main's in tile4-l2 and
2.4 % (-2.6..-2.4) slower in tile8-l2, in all 4 rounds. With the choice moved out of tile::<C>, that function is
main's again (under "Machine code"), and the comparison is under "Main and this branch, AVX2 arm".

64-byte loads

The first tile body loaded each block's 128 code bytes, and each column's two 128-byte groups, as 64-byte loads. At a
144-byte block pitch most of those loads split a cache line. In a single-core L2 loop that cost little, but at
k = 512 (Qwen3.6's down projection) with 16 threads streaming from DRAM that body read clearly less than AVX2, and
decode on the model below ran slower than with AVX2. Loading 32 bytes at a time, as the AVX2 kernels do, and joining
halves with vinserti64x4 brought that case to -0.2 % (-0.7..+0.2) against AVX2 (dot1-dram-T16 under "Kernel
rates"). A comment at the loads says why they are 32 bytes. If an Intel part prefers the 64-byte form, that would show
up in its numbers.

Code shape

  • No second copy. The AVX-512 bodies are ISA twins of their AVX2 kernels, like the scalar mirrors, and their
    float steps keep the AVX2 order, which is what keeps the bits. AGENTS.md:185-186 says not to split a
    #[target_feature] kernel body into helpers, and that a helper touching _mm* intrinsics is
    #[inline(always)] or carries the attribute itself. The setup the Q4_K and Q5_K bodies repeated is now three
    helpers that carry #[target_feature(enable = "avx2")] and #[inline]: q82x4_dy_my
    (crates/qdot/src/lib.rs:3848) gives a column's dy and my, and q45k_scales_ps and q45k_mins_ps
    (:3876 and :3888, safe fns) give a block's eight scales and eight mins as f32. Each kernel still multiplies
    them by d and -dmin itself, at the point where main's kernel does. An earlier single helper that returned
    both products reordered the instructions of the AVX2 kernels, so I split it. All three inline into every caller
    at x86-64-v3 and znver3 (no symbol of theirs is left in the qdot library at either target); I did not check
    plain x86-64.
  • Model code holds only architecture facts. No per-architecture file changes. crates/model/src/ops.rs gains the
    lever's load check in host_stack_runs, and crates/model/src/moe.rs gains its test.
  • Dead code is gone. lanes now takes a LaneKind in place of a q6 flag, and nothing is left unused.
  • No silent failure. A lever value other than 0 or 1 panics by name on every architecture: at load when
    the host tier holds a Q4_K stack, and at the first Q4_K dot_row otherwise, the scalar arm included (under
    "Selection"). A CPU without AVX-512 VNNI runs the AVX2 bodies, as before.
  • Comments state what is true now. The tile clause's PIN(2026-10-14) in crates/qdot/tests/qdot.rs now
    says where its rows come from.
  • No relaxed gate. tools/unsafe-ratchet.txt re-pins qdot from 141 blocks and 77 fns to 172 and 80 with a
    PIN(2026-10-14): line. The new code holds one unsafe operation per block (R1), each with its own SAFETY line:
    the tile (7 blocks) and the row lanes (12) as two unsafe fns, the dot_row arm and tile_q4k_avx512 that call
    the tile (2), q82x4_dy_my (one unsafe fn of 8 blocks, one per pointer offset and load), and one load block in
    each of q45k_scales_ps and q45k_mins_ps. No block pairs two groups, two arrays, or a pointer offset with its
    load. The AVX2 kernels whose setup now calls the helpers keep main's whole-body unsafe {}
    (crates/qdot/src/lib.rs:3904, 4599, 4813, 5204, 5409; main has the same shape, for example
    dot_q4k_q82x4_avx2 at main's lib.rs:3759). Splitting those is a refactor of every AVX2 kernel, which this PR
    does not take on.
  • cargo fmt and cargo clippy are clean on what I touched; the lint count did not go up (41, the ratchet).

Duplication found or removed (path:line), or "none": removed, and one found. The per-column dy and my setup of
dot_q4k_q82x4_avx2, dot_q5k_q82x4_avx2, dot_q45k_q82x4_tile_avx2, dot_lanes_avx2 and the two new bodies is
now q82x4_dy_my (crates/qdot/src/lib.rs:3918, 4614, 4831, 5008, 5422, 5538). The per-block scale and min loads of
dot_q4k_q82x4_avx2, dot_q5k_q82x4_avx2, dot_q45k_q82x4_tile_avx2, the AVX-512 tile and pack_lanes_avx2 are now
q45k_scales_ps and q45k_mins_ps (crates/qdot/src/lib.rs:3914, 3921, 4610, 4617, 4825, 4836, 4975, 4976, 5227, 5228). The scalar mirrors keep their scalar form of all three. Q4_K's synthetic rows, which the tile clause and the
AVX-512 clause both read, have one owner, q4k_synthetic_rows() (crates/qdot/tests/qdot.rs:5740), the all-0xFF
rows at k = 4096 included. In dot_row_cols, one local macro maps the column count for both tiles. Found, not
changed: Q6_K's three kernels keep the same dy decode as q82x4_dy_my's first half (crates/qdot/src/lib.rs:4203, 4342, 5693). A dy-only helper for them is outside this PR: this PR does not change the Q6_K kernels, and moving their hot-path dy decode needs its own bit check and timing.

What I ran

Base 33fb317b, head 0094a925. Most of the checks below ran at f8e32756, the head before the rebase onto
33fb317b (under "Commits"), and each section says which head it ran at. At the new head I ran again what the rebase
can reach: the release check with its FAIL-first, the bit-printing program in both arms and on the new main, the
qdot default set in both arms, the server's qdot machine code against f8e32756's, just contrib-check --tier t0,
gate-levers, the unsafe ratchet and the x86_64 lint at every commit, and just mac-static 33fb317b. Everything
x86_64 ran on the Zen 5 desktop under "Hardware", with the CPU governor at performance for every timed run.

The timed runs used earlier builds. Their qdot kernels compile to the same machine code as the head's, and dot_row
differs:

  • 38af59aa (on main 5c98cc70): the kernel table, the AVX2 arm against main, the first model window.
  • 5cc0a477 (on main a7ed8b58): the second model window, beside that earlier version 435b51ac (under "The choice
    inside tile").

The step-by-step comparison is under "Machine code". The main commits from 5c98cc70 to f1a3e9e4 touch neither
qdot nor what it links. Main 33fb317b changes crates/gguf, which qdot links, and the server's qdot functions stay
the same machine code across the rebase (under "Machine code").

Bit checks

cargo test --release -p bloomery-qdot --test qdot -- --include-ignored (what just gate-qdot runs on the box),
repository flags, once per arm, at f8e32756:

BLOOMERY_QDOT_AVX512=1: test result: FAILED. 42 passed; 41 failed
BLOOMERY_QDOT_AVX512=0: test result: FAILED. 42 passed; 41 failed

BLOOMERY_BOX_LOCAL=1 just gate-qdot gives the same lines, in both arms and at BLOOMERY_TIER=fixture. The 41
failures are the same in both arms. Each stops on an input it cannot read: 15 on a model shard under /models (the
DeepSeek-V4, V4.1 and Qwen3.8 files; the open fails with "No such file or directory") and 26 on a reference dump under
$BLOOMERY_DATA/ref (the read fails with PermissionDenied), which the maintainers' just build-ref and
just dump-ref produce. Neither input is readable on this machine. The Q4_K ones among them, hw_q4k_dot_row_matches_scalar_and_predicts, hw_q4k_tile_matches_dot_row,
hw_lanes_match_dot_row_v41 and hw_scalar_fallback_bit_identical_to_avx2, are the ones a maintainer's run checks on
real weights. The default model file, /models/small/DeepSeek-V2-Lite-Chat.Q3_K_M.gguf, is there, so the 41 are
main's 42 failures from an earlier run on this machine minus hw_q5f1_tile_matches_dot_row, which needs only that
file. The default set (cargo test --release -p bloomery-qdot) passes 27 in both arms, at f8e32756 and again at
0094a925.

The three model-free tests that reach the new bodies pass in both arms at f8e32756:

  • hw_q4k_avx512_matches_avx2_synthetic (new) first asserts that q4k_avx512() is true exactly when the CPU has
    AVX-512 F, BW and VNNI and the lever is unset or 1. Then, for seeded Q4_K rows at k = 256, 512, 768, 2048, 2304
    and 4096, plus all-0xFF rows at k = 4096 (all from q4k_synthetic_rows()), against 11 columns:
    dot_row must equal dot_row_avx2 and the scalar mirror, and the row lanes must equal dot_row. It owns Q4_K's
    synthetic lane clause and prints which body ran:

    Q4_K AVX-512 VNNI: seeded rows (k = 256), 16 rows x 11 columns: dot_row = dot_row_avx2 = scalar, 352 lane calls = dot_row, bit-identical
    
  • hw_lanes_match_dot_row_synthetic (existing) keeps the lane clause for Q5_K and Q6_K.

  • f16_scales_bit_identical_kernel_vs_mirror (existing, in the default set) now also holds dot_row to the AVX2
    kernel over every f16 scale that is not NaN (63,490 of the 65,536 patterns), so Q4_K's subnormal, infinite and zero
    scales go through the AVX-512 body too. Where both results are NaN, the test only checks that both are NaN, not
    their payload bits.

hw_q4k_tile_matches_dot_row (existing) now holds the tile to dot_row on the rows of q4k_synthetic_rows() before
it opens its model file. That part passes on this box. The test then opens the model file
(crates/qdot/tests/qdot.rs:4384) and stops at :4394, where reading the reference dump q4k-x4-ik-dot.txt
fails with PermissionDenied.

A small program outside the tree also printed the bits of every output of dot_row, dot_row_cols (C = 1..8) and
pack_lanes with dot_lanes_cols, for seeded Q4_K and Q5_K rows at k = 256, 512 and 2048: 876 lines. The output is
byte for byte the same for main 5c98cc70, main 33fb317b, and f8e32756 and 0094a925 each with the lever at 1
and at 0 (md5 1f2cf765ffc2d78e92a63e41b8bcb9f2).

FAIL-first at f8e32756: eight mutants of crates/qdot/src/lib.rs, one at a time, the crate rebuilt, each run once
with the lever unset (the AVX-512 arm on this CPU). The unchanged code ran its clauses in both arms (above); the
mutants did not run at 0. Seven turn an assertion red, and the file's md5 was checked to come back after:

Mutant Red
the tile's two sub-block fmas swapped hw_q4k_avx512_matches_avx2_synthetic, f16_scales_bit_identical_kernel_vs_mirror
sub-block 1 paired with block 0's activations hw_q4k_avx512_matches_avx2_synthetic, f16_scales_bit_identical_kernel_vs_mirror
a row-lane half reading the other half's activations hw_q4k_avx512_matches_avx2_synthetic
q82x4_dy_my taking the second group's sums from the first group hw_q4k_avx512_matches_avx2_synthetic, f16_scales_bit_identical_kernel_vs_mirror
q45k_mins_ps reading the scales' bytes hw_q4k_avx512_matches_avx2_synthetic, f16_scales_bit_identical_kernel_vs_mirror
q4k_avx512 false on every CPU hw_q4k_avx512_matches_avx2_synthetic (left: false, right: true)
dot_row's AVX2 Q4_K arm not asking q4k_avx512() dot_row_refuses_a_qdot_lever_value_by_name
dot_row's Q4_K arm for a CPU without AVX2 not asking q4k_avx512() none: on this CPU that arm does not run

The tile's synthetic part in hw_q4k_tile_matches_dot_row compares the tile with dot_row, which runs the same body
at C = 1, so a mutant of that body changes both sides alike and that part stays green; the comparison with the AVX2
kernel and the scalar mirror catches it. With the selector off, every comparison runs AVX2 against AVX2 and passes,
so the first assertion is what catches it. The last mutant needs a CPU without AVX2 to turn red here; its aarch64
counterpart is under "aarch64".

The maintainers' box is Zen 3, so gate-qdot there runs the AVX2 arm only. For the AVX-512 arm, the bit check is
these tests on a CPU that has it.

Lever value at load

host_layer_build_refuses_a_qdot_lever_value_by_name (crates/model/src/moe.rs:3282, a plain #[test]) runs its
own test binary again with BLOOMERY_QDOT_AVX512=2, because q4k_avx512 keeps its first answer in a OnceLock. In
that process it builds a Q4_K host layer through HostLayer::build, the load's own check, and asserts that the build
panics and that the panic names the lever. Its shape follows the_split_reads_no_environment in crates/placement.
It runs on every architecture. On x86_64 at f8e32756 (cargo test -p bloomery-model --lib -- --exact moe::tests::host_layer_build_refuses_a_qdot_lever_value_by_name --nocapture):

test moe::tests::host_layer_build_refuses_a_qdot_lever_value_by_name ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 290 filtered out; finished in 0.00s

The child checks that the panic contains BLOOMERY_QDOT_AVX512="2", from q4k_avx512's message
BLOOMERY_QDOT_AVX512="2": takes 0 or 1. FAIL-first: with the q4k_avx512() call taken out of host_stack_runs,
the build succeeds and the test fails (a refused lever value must stop the build: Ok(()), 0 passed; 1 failed).
With the call back, it passes. It also passes with BLOOMERY_QDOT_AVX512=0 set for the whole run, because the child
sets its own value. The aarch64 runs are under "aarch64".

dot_row_refuses_a_qdot_lever_value_by_name (crates/qdot/tests/qdot.rs:6010, a plain #[test] on every
architecture) does the same for dot_row: in a fresh process with BLOOMERY_QDOT_AVX512=2, a Q4_K dot_row must
panic and the panic must name the lever. On x86_64 at f8e32756 it passes, also with BLOOMERY_QDOT_AVX512=0 set for the whole
run, and turns red when dot_row's AVX2 Q4_K arm stops asking q4k_avx512() (the table above). The aarch64 run is
under "aarch64".

The same refusal on a real load:
BLOOMERY_CARD_BUDGET=4G BLOOMERY_QDOT_AVX512=yes bloomery-serve --hf lmstudio-community/Qwen3.6-35B-A3B-GGUF:Q4_K_M --place a --ctx 8192 --parallel 1 --host 127.0.0.1 --port 8093.

Before the load check (a server build of the first head of this PR):

load host_tier type=q4_K k=2048 path=fused
load host_tier type=q6_K k=512 path=fused
load host_tier type=q4_K k=512 path=fused
load arch=qwen35moe resident_bytes=2376544800 cache=f16 ctx=8192 slots=1 slot_ctx=8192 layers=40 ubatch=512 graph_nodes=800 in 4.7 s
bloomery-serve-qwen3: arch=qwen35moe ctx=8192 slots=1 slot_ctx=8192 listening on http://127.0.0.1:8093
thread 'bloomery-pool-10' (2112566) panicked at crates/qdot/src/lib.rs:273:24:
BLOOMERY_QDOT_AVX512="yes": takes 0 or 1
(the same panic on the other pool workers)

The request got {"error":{"code":500,"message":"engine: the engine thread ended mid-call","type":"server_error"}},
and the server exited with code 70.

After (a server build of 38af59aa, built at x86-64-v3 into target/portable):

load host_tier r8=off (no sidecar at ...)
thread 'engine' (1504086) panicked at crates/qdot/src/lib.rs:283:24:
BLOOMERY_QDOT_AVX512="yes": takes 0 or 1
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
bloomery-serve: the engine thread ended during the load

The server never listened and exited with code 1.

aarch64

On a DGX Spark (GB10), in a CUDA 13.3.1 dev container (cargo test, debug profile), at f8e32756. The tree was
git archive f8e32756, checked file by file against its md5 list (1,703 files, no difference). I did not run these
again after the rebase: it does not change crates/qdot, and main's changes to crates/model leave
HostLayer::build and host_stack_runs, which the load test runs, as they were.

cargo test -p bloomery-qdot --test qdot -- --exact dot_row_refuses_a_qdot_lever_value_by_name
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 65 filtered out
cargo test -p bloomery-model --lib -- --exact moe::tests::host_layer_build_refuses_a_qdot_lever_value_by_name
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 288 filtered out
cargo test -p bloomery-qdot --test qdot
test result: ok. 24 passed; 0 failed; 42 ignored; 0 measured; 0 filtered out

Both refusal tests also pass with BLOOMERY_QDOT_AVX512=0 set for the whole run.

FAIL-first, each on a copy of that tree with one change:

  • With the three lines of the aarch64 dot_row's q4k_avx512() ask taken out, the dot_row refusal test fails
    with a refused lever value must stop dot_row: Ok(-572683.25). This is the aarch64 counterpart of the last mutant
    in the table above.
  • With the q4k_avx512() call taken out of host_stack_runs, the load test fails with
    a refused lever value must stop the build: Ok(()).

Model text

After the timed requests of the first model window, each of the 16 servers (4 per arm, arms under "Model") answered
two greedy requests (192 tokens at most, thinking off): a 25-token question, whose decode goes through dot_row, and a
4,421-token excerpt of crates/qdot/src/lib.rs with "Summarize what the code above does.", whose prompt goes through
the row lanes. All 16 servers gave the same two answers, byte for byte.

Static checks

On an aarch64 Mac, at 0094a925: just mac-static 33fb317b ends with mac-static: ok (no rustfmt diff, lint 41 =
the ratchet, 27 shapes run with 0 red, every check-* at rc 0). The x86_64 lint (just mac-lint) gives 41 warnings,
the ratchet, at each of the nine commits, and tools/check-unsafe.sh passes at each (qdot's count is at its pin each time). At f8e32756, just mac-test
gives 1140 passed, 1 failed and 177 ignored. The one failure, bloomery-refset's
arch::draft::tests::a_plain_target_with_no_draft_beside_is_the_family_path, fails the same way on main on this Mac,
and this branch does not touch crates/refset. crates/qdot and crates/model are not among the crates mac-test
runs on the Mac (their tests need Linux), so on the Mac the qdot and model tests are checked with cargo clippy --tests for x86_64-unknown-linux-gnu and aarch64-unknown-linux-gnu but not run.

On the x86_64 machine, at 0094a925: just contrib-check --tier t0: DONE tier=t0 total=78 red=0.
BLOOMERY_BOX_LOCAL=1 just gate-levers: 40 passed; 0 failed. At f8e32756: BLOOMERY_BOX_LOCAL=1 just gate-ops
passes its 291 library tests, and its 8 model tests stop because they cannot read the reference manifest
($BLOOMERY_DATA/ref/MANIFEST.tsv, PermissionDenied). gate-union passes 4 of 7, and the other 3 stop on the missing DeepSeek-V4.1
shards. The same counts come at BLOOMERY_TIER=fixture.

The release check, at 0094a925, on the x86-64-v3 server build (objdump from GNU Binutils 2.46):
tools/release/build.sh --self-test gives release: self-test ok (12 cases), and
tools/release/build.sh --check target/portable/release gives release: checks passed on target/portable/release.
FAIL-first, each with one change to build.sh, against the same binary:

  • With lanes taken out of the new DISPATCHED entry, the check fails and names the four instances of
    qdot::dot_lanes_avx512, for example 116 qdot::dot_lanes_avx512::<4>, first at 1a6d604: vmovaps -0x18d7b8e(%rip),%zmm1.
  • With the tile taken out, it names the eight instances qdot::dot_q4k_q82x4_tile_avx512::<1> to <8>.
  • With the whole entry taken out, it names those twelve and no other function.
  • With the PIN(2026-10-12) comment taken out, the check passes. Nothing reads that comment, so it is there for
    review, not for the check.

Machine code

I diffed the disassembly function by function (objdump -d --no-show-raw-insn -C). The comparison keeps every
instruction and operand and drops addresses and the numbering of anonymous symbols. A branch inside a function
compares as its offset from the function's start, a call or branch elsewhere as its target symbol, and a load of a
constant as the bytes it reads. A lea, or a load whose width the operand does not show, compares as its target
symbol. A lea to an anonymous symbol, or past the end of the named symbol it lands in, compares as "anonymous", so a
panic location or exception table that moved does not count as a difference.

Against main, at 38af59aa. In the kernel bench under "Kernel rates" (-C target-cpu=x86-64-v3, where the AVX2
tiles and lanes inline into their dispatchers), 31 of the 53 qdot functions are the same as main's and 22 differ:

  • The same: among them dot_q4k_q82x4_avx2, dot_q5k_q82x4_avx2, tile::<2> to tile::<8>, pack_group in both
    forms and pack_lanes.
  • New: 18 functions, the two AVX-512 bodies (12 instances), tile_q4k_avx512::<4> to <8> and q4k_avx512.
  • Changed: the three entries that now ask q4k_avx512() (dot_row, dot_row_cols, dot_lanes_cols), and
    quantize_col_check, whose one difference is the GOT slot of an indirect call.

The server binary shows the same: 39 qdot functions the same, 21 different, and every AVX2 kernel and every
tile::<C> among the same. dot_lanes_cols inlines dot_lanes_avx2::<C>, so it differs from main's as a whole. To
compare the AVX2 lanes and tiles alone, I built the bench once more from both trees with #[inline(never)] on
dot_lanes_avx2 and dot_q45k_q82x4_tile_avx2 (a throwaway edit, not in this branch). dot_lanes_avx2::<1> to <4>
and all 14 instances of dot_q45k_q82x4_tile_avx2 are then the same as main's.

From 38af59aa to the head, the same comparison on each step (bench and server built at x86-64-v3 on the Zen 5
box; 60 qdot functions in the server):

From To What changed Bench (53 qdot fns) Server
38af59aa 5cc0a477 rebased on a newer main; the same qdot, gguf and threads source not compared (it links only those three) 56 the same; 4 and host_stack_runs differ (the per-function listing of this step was not saved)
5cc0a477 013f098e one unsafe operation per block in the new code (R1), the helpers' own #[target_feature], the lever's registry row 53 the same 60 the same, host_stack_runs the same
013f098e 5df92e10 each pointer offset in its own unsafe block; the docs in their own commit 53 the same 60 the same, host_stack_runs the same
5df92e10 b0ff0ac9 moved onto the maintainer's two review commits on main f1a3e9e4; the same crates/qdot/src 53 the same 56 the same; check_row, dot_lanes_cols, dot_row_cols, quantize_col_check and host_stack_runs differ only in the GOT slot of one indirect call
b0ff0ac9 8e816da5 (= fbf33c06's code) q4k_avx512() on every architecture 52 the same; dot_row 197 instructions, now 207 59 the same; dot_row as in the bench; host_stack_runs the same
fbf33c06 f8e32756 the review's fixes 53 the same 60 the same (dot_row_cols, every tile::<C> and every tile_q4k_avx512::<C> among them); host_stack_runs 151 instructions, now 160 (it asks q4k_avx512() first)
f8e32756 0094a925 (head) rebased onto main 33fb317b; the same crates/qdot not rebuilt 49 the same; the other 11, and host_stack_runs, differ only in the address of a GOT slot, which the comparison here sets to one name (it does not compare the callee behind the slot), and non_finite_activation also in the bytes after the 4-byte constant it loads, which that load does not read

Before the rebase, for the step from fbf33c06 to f8e32756 and for each of this branch's own commits, I also built
the qdot library alone on the Mac (cargo build --release -p bloomery-qdot --lib --target x86_64-unknown-linux-gnu,
at -C target-cpu=x86-64-v3 and at znver3) and compared it the same way. The table names the commits by their
hashes after the rebase; crates/qdot is the same tree at each. The results are the same at both targets:

Step What differs in the qdot library
0f4d36e6 to ef6e0c45 (helpers) Every AVX2 kernel and every tile::<C> is the same. With #[inline(never)] on dot_lanes_avx2 and dot_q45k_q82x4_tile_avx2 (the throwaway edit above), those two are the same too, and the same as main's. The two AVX-512 bodies change: the tile's instructions are reordered and renamed at the same counts, and the row lanes lose a few. Both are then the same as the head's, which ran the bit checks above. dot_lanes_cols inlines the AVX2 lanes. At x86-64-v3 that inlined copy compiles to a different instruction mix than at 0f4d36e6; at znver3, and at both targets with the lanes kept out of line, only stack moves and padding differ. The head's dot_lanes_cols is the timed builds' code (the table above).
ef6e0c45 to 2fb45954 (tile dispatch) tile::<2> to <8> become the same as main's. dot_row_cols and dot_lanes_cols change, and tile_q4k_avx512::<4> to <8> are new. Nothing else changes.
2fb45954 to d9119c85 (lever refusal) dot_row (197 instructions, now 205) and q4k_avx512's OnceLock initializer, which now checks the lever before it asks the CPU. Nothing else changes.
fbf33c06 to f8e32756 Nothing: the disassembly is the same, line for line, so the local macro in dot_row_cols gives the code of the two matches it replaced.

The other three commits do not touch crates/qdot/src. At the head, every AVX2 kernel, every tile::<C>, and with
#[inline(never)] every dot_lanes_avx2 and dot_q45k_q82x4_tile_avx2 instance is the same as main f1a3e9e4's
at both targets. The functions that differ from main are dot_row, dot_row_cols and dot_lanes_cols, beside the new
ones; main's library also holds two Zip::new instances that 0f4d36e6 already lacks.
host_stack_runs is in crates/model, so this check does not cover it; the server comparison in the table above
does.

Main and this branch, AVX2 arm

The kernel bench under "Kernel rates", built from main and from this branch (38af59aa), ran its l2 cases as
QB_K=<k> BLOOMERY_QDOT_AVX512=<0|1> qdot-isa-bench 5 1.0 l2 at k = 2048 and 512: 4 rounds, the order of the four
runs rotated each round. Main has no lever, so its two runs are an A/A pair. M dots/s (rows/s for pack-l2), median
of the 4 run medians; the ratios are the median of the 4 per-round ratios, with their range:

k case main 38af59aa, lever 0 38af59aa 0 / main main A/A
2048 dot1-l2 29.94 29.89 -0.2 % (-0.3..+0.1) +0.0 % (-0.3..+0.2)
2048 tile2-l2 34.57 34.72 +0.4 % (+0.4..+0.5) -0.2 % (-1.0..+0.0)
2048 tile4-l2 38.19 38.21 +0.2 % (-0.6..+0.7) -0.2 % (-0.6..+0.6)
2048 tile8-l2 39.55 39.90 +0.5 % (-0.0..+2.0) +0.9 % (-0.8..+1.7)
2048 lanes8-l2 65.56 65.27 -0.3 % (-0.7..-0.1) -0.4 % (-1.1..-0.2)
2048 pack-l2 49.51 49.41 -0.4 % (-4.8..+0.4) -0.3 % (-3.6..+0.8)
2048 lanes8dot-l2 70.94 70.89 -0.1 % (-2.0..+1.3) -0.4 % (-1.1..+1.1)
512 dot1-l2 81.53 80.29 -1.6 % (-2.9..+0.5) -0.0 % (-0.4..+1.3)
512 tile2-l2 95.26 95.03 -0.2 % (-0.7..+0.8) -0.1 % (-0.5..+0.6)
512 tile4-l2 104.39 104.69 +0.3 % (-0.3..+0.9) -0.1 % (-0.6..+0.7)
512 tile8-l2 109.41 109.72 +0.3 % (+0.2..+0.3) +0.2 % (-0.0..+0.4)
512 lanes8-l2 209.53 211.71 +1.1 % (+0.3..+2.3) +0.5 % (-0.6..+3.6)
512 pack-l2 178.79 179.64 +0.6 % (-1.7..+1.5) +0.1 % (-1.4..+0.7)
512 lanes8dot-l2 246.04 242.14 -1.4 % (-1.7..-1.0) -1.0 % (-1.0..+0.9)

The tiles are within -0.2 % to +0.5 % of main, where the guard arm inside tile::<C> had cost 4.3 % and 2.4 %.
At k = 512, dot1-l2 reads -1.6 % (-2.9..+0.5) and lanes8dot-l2 -1.4 % (-1.7..-1.0), against an A/A of
-1.0 % (-1.0..+0.9) for the latter. dot_row's AVX2 kernel is main's machine code, so I read the first as the
entry's extra guard or the bench's spread; lanes8dot-l2 runs dot_lanes_cols, which inlines main's
dot_lanes_avx2 beside the new arm, and I could not bring it closer to main than this. On the model, the lever-0 arm
against main reads -0.3 % (± 0.6) and -0.4 % (± 0.4) in prefill (under "Model"), under the 1 % that two binaries
can resolve.

Kernel rates

A small program outside the tree (source at the end) calls qdot's public entries (dot_row,
dot_row_cols, pack_lanes, dot_lanes_cols) on synthetic Q4_K rows and quantized columns. It is built with
RUSTFLAGS="-C target-cpu=x86-64-v3" cargo build --release like the release, against this branch's crates/qdot and
crates/gguf, and run as QB_K=<k> BLOOMERY_QDOT_AVX512=<0|1> qdot-isa-bench 5 1.0: 4 rounds, arm order flipped each
round, 5 reps per case and run, each rep at least 1 s (l2 cases) or 2 s (dram cases). The table gives the median of
the 4 run medians, with the range of the per-round ratios:

Case k = 2048: AVX-512 AVX2 change k = 512: AVX-512 AVX2 change
dot1-l2: dot_row, 1 thread, M dots/s 32.4 29.6 +9.4 % (+9.0..+10.2) 78.1 79.7 -2.1 % (-3.4..-1.0)
tile2-l2: dot_row_cols, C = 2, M dots/s 41.8 34.4 +21.3 % (+21.0..+22.5) 103.6 94.6 +9.5 % (+9.1..+9.7)
tile4-l2: C = 4 46.0 37.9 +21.4 % (+21.0..+21.7) 112.6 104.0 +8.3 % (+8.3..+8.6)
tile8-l2: C = 8 47.7 39.5 +21.0 % (+19.0..+22.4) 114.6 108.5 +5.6 % (+5.2..+6.3)
lanes8-l2: pack_lanes + dot_lanes_cols, 8 columns, M dots/s 77.3 65.0 +18.9 % (+17.4..+20.0) 230.4 208.9 +10.3 % (+9.5..+11.7)
pack-l2: pack_lanes alone, M rows/s 48.8 48.8 +0.0 % (-0.9..+1.1) 179.7 177.7 +1.1 % (+0.5..+1.8)
lanes8dot-l2: dot_lanes_cols on groups packed once, M dots/s 89.8 71.2 +26.0 % (+24.8..+27.6) 279.4 242.2 +15.4 % (+14.5..+17.3)
dot1-dram-T1: dot_row, 1 thread, GB/s 34.35 32.28 +6.4 % (+5.5..+9.8) 21.95 22.06 -0.5 % (-1.0..-0.0)
dot1-dram-T16: 16 threads, GB/s 76.12 76.40 -0.4 % (-0.6..-0.1) 79.13 79.27 -0.2 % (-0.7..+0.2)
lanes8-dram-T16: pack + 8 columns, GB/s 69.48 68.40 +1.6 % (+0.6..+2.1) 65.45 61.66 +6.1 % (+4.3..+7.2)
lanes64-dram-T16: pack + 64 columns, GB/s 16.39 13.72 +19.5 % (+19.3..+19.9) 12.55 11.53 +8.8 % (+8.4..+9.2)

l2: 448 rows (504 KiB at k = 2048) dotted over and over on one thread. lanes8dot-l2 keeps all 56 groups packed,
1.1 MiB at k = 2048, a little more than the core's 1 MiB L2. dram: 2.3 GB of rows at k = 2048 (0.58 GB at k = 512)
split over T threads. lanes64 dots each packed group with 8 runs of 8 columns, as a prompt batch does. I can add the
program under crates/qdot/src/bin if the maintainer wants it in the tree.

The AVX-512 arm is slower in every round in three cases, all the one-column kernel: dot1-l2 at k = 512 (-2.1 %,
-3.4..-1.0), dot1-dram-T1 at k = 512 (-0.5 %, -1.0..-0.0) and dot1-dram-T16 at k = 2048 (-0.4 %, -0.6..-0.1). At
k = 512 a row is two super-blocks, so the setup of each call weighs more, and with 16 threads the leg is bound by
DRAM. Decode on the model, which runs this kernel, shows no difference.

dot_row with q4k_avx512() on every architecture: its new arm for a CPU without AVX2 moved dot_row's register
allocation, so the kernel bench of 8e816da5 (fbf33c06's code) ran again beside that of b0ff0ac9, built just
before that change, with the same l2 cases in both arms, k = 2048 and 512, 4 rounds and the run order rotated each
round. For dot1-l2, 8e816da5 against b0ff0ac9 (median of the per-round ratios, with their range): lever 1 reads
+0.1 % (-2.8..+1.2) at k = 2048 and -0.6 % (-0.7..-0.5) at k = 512; lever 0 reads -0.1 % (-3.2..+0.4) and +0.7 %
(+0.5..+1.3). The other 24 cases run the same machine code in both benches and read from -1.1 % to +1.1 %, so the
change to dot_row stays inside what two binaries resolve here. At k = 512 the two arms each moved the same way in
all 4 rounds (lever 1 slower, lever 0 faster). The dram cases and the model did not run again for this change.

Against the earlier version 435b51ac, in the second model window: its kernel bench and 5cc0a477's, AVX-512 arm,
4 rounds, order flipped each round. Two binaries, so read these as a guide. Most cases are within 1.5 %. tile2-l2 at
k = 512 is 6.3 % faster. dot1-l2 is 3.2 % slower at k = 2048 and 2.4 % at k = 512, and lanes8-dram-T16 at k = 512
2.8 % slower. pack-l2 at k = 2048 is 4.1 % slower: pack_lanes runs AVX2 in both arms and is main's machine code
here (pack-l2 reads -0.4 % and +0.6 % against main above), so the earlier version's packing was faster than main's, and
I gave that up to keep main's AVX2 code. On the model, prefill in the same window is 0.5 % (± 0.5) and 0.7 % (± 0.4)
faster at 5cc0a477 than at 435b51ac.

Model

Qwen3.6-35B-A3B Q4_K_M (lmstudio-community/Qwen3.6-35B-A3B-GGUF:Q4_K_M, 21,166,757,728 bytes),
bloomery-serve built at x86-64-v3 into target/portable as tools/release/build.sh does, run as
BLOOMERY_CARD_BUDGET=4G BLOOMERY_QDOT_AVX512=<0|1> bloomery-serve --hf lmstudio-community/Qwen3.6-35B-A3B-GGUF:Q4_K_M --place a --ctx 8192 --parallel 1
with the default worker pool (16 threads, the physical cores). The 4 GB card budget is there to
put the routed experts on the host: the plan line reads host_experts=10108 card_experts=132. The host tier loads
q4_K k=2048 (gate and up) and q4_K and q6_K at k = 512 (down), all fused. Decode reaches qdot through dot_row,
and a prompt through the row lanes.

Per arm and round, a fresh server got one warm-up and then 3 requests per prompt size on /v1/chat/completions, 128
tokens out, greedy, thinking off. The short prompt asks for a story; the two longer ones ask for a summary of 2,000 and
16,000 characters of Python source. A per-request nonce at the start keeps the prefix cache from reusing a prompt.
4 rounds, the arm order rotated each round. Every server of a window printed the same plan line and the same host tier
lines.

Two windows. The first ran four arms: main's server twice (an A/A pair; main does not know the lever, so it is unset),
and this branch's server (38af59aa) with the lever at 1 and at 0. The second ran this branch's server
(5cc0a477) and the earlier version 435b51ac, each at 1 and at 0.

tok/s from the server's timings in the second window, median of the 12 requests (range in brackets):

Prompt prefill, lever 1 prefill, lever 0 decode, lever 1 decode, lever 0
34 tokens 267.7 [252.2..270.1] 267.8 [264.4..270.3] 89.9 [84.0..90.7] 89.5 [86.5..90.6]
474 tokens 1004.9 [959.7..1009.6] 948.9 [937.2..954.3] 90.4 [89.9..90.7] 90.0 [85.7..90.5]
3,681 tokens 1026.9 [1020.5..1033.3] 967.3 [960.2..972.1] 89.2 [87.9..90.0] 89.0 [88.3..89.7]

The ratios are the mean of the 4 per-round ratios with its 95 % interval (t, 3 degrees of freedom). Second window:

Prompt prefill, 5cc0a477 1 / 0 435b51ac 1 / 0 5cc0a477 / 435b51ac, at 1 at 0 decode, 5cc0a477 1 / 0
34 tokens -0.2 % ± 1.1 +0.7 % ± 0.6 -0.5 % ± 0.8 +0.4 % ± 0.8 +0.4 % ± 2.5
474 tokens +5.9 % ± 0.8 +5.7 % ± 0.8 +0.5 % ± 0.5 +0.4 % ± 0.7 +0.8 % ± 1.4
3,681 tokens +6.2 % ± 0.7 +6.2 % ± 0.4 +0.7 % ± 0.4 +0.6 % ± 0.2 +0.2 % ± 2.0

First window:

Prompt prefill, 38af59aa 1 / 0 38af59aa 0 / main 38af59aa 1 / main main A/A decode, 38af59aa 1 / 0
34 tokens +0.9 % ± 1.7 -0.9 % ± 1.7 -0.0 % ± 0.6 -0.4 % ± 0.7 +0.3 % ± 2.6
474 tokens +4.6 % ± 0.4 -0.3 % ± 0.6 +4.3 % ± 0.6 +0.2 % ± 0.4 -0.0 % ± 1.6
3,681 tokens +4.9 % ± 0.7 -0.4 % ± 0.4 +4.4 % ± 0.5 +0.2 % ± 0.6 +1.6 % ± 4.4

The same code's prefill ratio, lever 1 against 0, read +4.6 % and +4.9 % in the first window and +5.9 % and +6.2 % in
the second, further apart than their intervals. The lever-1 arm moved between the windows (994 and 1013 tok/s in the
first, 1005 and 1027 in the second) while the lever-0 arm stayed near 949 and 967. In the second window 435b51ac
read +5.7 % and +6.2 %, as it did when it was measured first, and 5cc0a477 read slightly above it, so I take the lower
first-window ratio to belong to that window, not to the code. Decode shows no difference in either window. The lever-0
arm against main, -0.3 % and -0.4 % in prefill, is under the 1 % that two binaries can resolve.

My reading, not measured here: decode's one-column leg is held by DRAM (dot1-dram-T16 above), and the host's dot
products are only part of a prompt's wall.

Hardware

  • CPU: AMD Ryzen 9 9950X (Zen 5), 16 cores, 32 threads, AVX-512 F, BW, VL and VNNI, boost on, governor performance
    for the timed runs.

  • RAM: 2 x 32 GB DDR5 at 6000 MT/s, 2 channels.

  • GPU: the card holds the model's dense part; the change is on the CPU. nvidia-smi:

    | NVIDIA-SMI 595.99.02              Driver Version: 595.99.02      CUDA Version: 13.2     |
    |   0  NVIDIA GeForce RTX 5090        Off |   00000000:01:00.0 Off |                  N/A |
    

    nvidia-smi --query-gpu=name,driver_version,clocks.max.sm --format=csv,noheader:
    NVIDIA GeForce RTX 5090, 595.99.02, 3090 MHz.

  • Linux 7.0.0-38-generic, rustc 1.100.0-nightly (e457a7b0d 2026-08-27).

These numbers come from one Zen 5 desktop with two memory channels. Numbers from Zen 4 or an Intel AVX-512 server
would show where the gain starts and stops, and BLOOMERY_QDOT_AVX512=0 gives the AVX2 side from the same binary.

The kernel bench program (Cargo.toml and src/main.rs)
[package]
name = "qdot-isa-bench"
version = "0.1.0"
edition = "2024"
publish = false

[dependencies]
bloomery-qdot = { path = "<bloomery>/crates/qdot" }
bloomery-gguf = { path = "<bloomery>/crates/gguf" }
//! Q4_K kernel rates for one process's qdot arm (BLOOMERY_QDOT_AVX512 decides it).
//! Usage: qdot-isa-bench <reps> <secs-per-rep>. Prints one line per case with the median and range of reps.
use std::time::Instant;

use gguf::GgmlType;

const TY: GgmlType = GgmlType::Q4_K;
const ROW_BYTES_PER_SB: usize = 144;

fn fill(n: usize, seed: u64) -> Vec<u8> {
    let mut s = seed | 1;
    let mut v = vec![0u8; n];
    for c in v.chunks_mut(8) {
        s ^= s >> 12;
        s ^= s << 25;
        s ^= s >> 27;
        let x = s.wrapping_mul(0x2545F4914F6CDD1D).to_le_bytes();
        c.copy_from_slice(&x[..c.len()]);
    }
    // Every block's f16 d and dmin finite and normal (exponent 12..15).
    for b in v.chunks_exact_mut(ROW_BYTES_PER_SB) {
        b[1] = (b[1] & 0x83) | 0x30;
        b[3] = (b[3] & 0x83) | 0x30;
    }
    v
}

fn cols(k: usize, n: usize) -> Vec<Vec<u8>> {
    (0..n)
        .map(|j| {
            let x: Vec<f32> = (0..k).map(|i| (((i * 7 + j * 13) % 61) as f32 - 30.0) * 0.07).collect();
            let mut a = vec![0u8; qdot::col_bytes(TY, k)];
            qdot::quantize_col(TY, &x, &mut a);
            a
        })
        .collect()
}

/// Runs `pass` (returns units done) repeatedly for `secs`, returns units per second.
fn rate(secs: f64, mut pass: impl FnMut() -> u64) -> f64 {
    pass();
    let t = Instant::now();
    let mut units = 0u64;
    while t.elapsed().as_secs_f64() < secs {
        units += pass();
    }
    units as f64 / t.elapsed().as_secs_f64()
}

fn report(arm: &str, case: &str, unit: &str, reps: usize, mut one: impl FnMut() -> f64) {
    let mut v: Vec<f64> = (0..reps).map(|_| one()).collect();
    v.sort_by(|a, b| a.partial_cmp(b).unwrap());
    println!(
        "arm={arm} case={case} unit={unit} median={:.4e} min={:.4e} max={:.4e} reps={reps}",
        v[reps / 2],
        v[0],
        v[reps - 1]
    );
}

fn main() {
    let a: Vec<String> = std::env::args().collect();
    let reps: usize = a.get(1).map_or(5, |s| s.parse().unwrap());
    let secs: f64 = a.get(2).map_or(1.0, |s| s.parse().unwrap());
    let arm = if qdot::q4k_avx512() { "avx512" } else { "avx2" };
    let k: usize = std::env::var("QB_K").map_or(2048, |v| v.parse().unwrap());
    let rb = k / 256 * ROW_BYTES_PER_SB;
    let ac = cols(k, 8);
    let mut sink = 0.0f32;

    // L2-resident rows: 448 rows (504 KiB) dotted again and again.
    let l2rows = 448;
    let w = fill(l2rows * rb, 1);
    report(arm, "dot1-l2", "row_dots/s", reps, || {
        rate(secs, || {
            for r in w.chunks_exact(rb) {
                sink += qdot::dot_row(TY, r, &ac[0], k).unwrap();
            }
            l2rows as u64
        })
    });
    for c in [2usize, 4, 8] {
        let cs: Vec<&[u8]> = ac[..c].iter().map(|v| v.as_slice()).collect();
        let mut out = vec![0.0f32; c];
        report(arm, &format!("tile{c}-l2"), "row_col_dots/s", reps, || {
            rate(secs, || {
                for r in w.chunks_exact(rb) {
                    qdot::dot_row_cols(TY, r, &cs, k, &mut out).unwrap();
                    sink += out[0];
                }
                (l2rows * c) as u64
            })
        });
    }
    let g = qdot::LANE_ROWS;
    let mut packed = vec![0u8; qdot::lane_pack_bytes(k)];
    let cs: Vec<&[u8]> = ac.iter().map(|v| v.as_slice()).collect();
    let mut lo = vec![[0.0f32; 8]; 8];
    report(arm, "lanes8-l2", "row_col_dots/s", reps, || {
        rate(secs, || {
            for grp in w.chunks_exact(g * rb) {
                qdot::pack_lanes(TY, grp, &[], k, &mut packed).unwrap();
                qdot::dot_lanes_cols(TY, &packed, &cs, k, &mut lo).unwrap();
                sink += lo[0][0];
            }
            (l2rows * 8) as u64
        })
    });

    // The two halves of lanes8-l2 apart: the pack alone (AVX2 in both arms), and the dot over groups packed once.
    report(arm, "pack-l2", "rows/s", reps, || {
        rate(secs, || {
            for grp in w.chunks_exact(g * rb) {
                qdot::pack_lanes(TY, grp, &[], k, &mut packed).unwrap();
                sink += f32::from(packed[0]);
            }
            l2rows as u64
        })
    });
    let plen = qdot::lane_pack_bytes(k);
    let mut all = vec![0u8; l2rows / g * plen];
    for (grp, p) in w.chunks_exact(g * rb).zip(all.chunks_exact_mut(plen)) {
        qdot::pack_lanes(TY, grp, &[], k, p).unwrap();
    }
    report(arm, "lanes8dot-l2", "row_col_dots/s", reps, || {
        rate(secs, || {
            for p in all.chunks_exact(plen) {
                qdot::dot_lanes_cols(TY, p, &cs, k, &mut lo).unwrap();
                sink += lo[0][0];
            }
            (l2rows * 8) as u64
        })
    });

    if a.get(3).is_some_and(|m| m == "l2") {
        std::hint::black_box(sink);
        return;
    }
    // DRAM streaming: 2.3 GB of rows split over T threads, one column (decode's one-column leg).
    let big_rows = 2_000_000;
    let big = fill(big_rows * rb, 2);
    for t in [1usize, 16] {
        report(arm, &format!("dot1-dram-T{t}"), "GB/s", reps, || {
            let per = big_rows / t;
            let st = Instant::now();
            let mut passes = 0;
            while st.elapsed().as_secs_f64() < secs * 2.0 || passes == 0 {
                std::thread::scope(|s| {
                    for i in 0..t {
                        let part = &big[i * per * rb..(i + 1) * per * rb];
                        let col = &ac[0];
                        s.spawn(move || {
                            let mut acc = 0.0f32;
                            for r in part.chunks_exact(rb) {
                                acc += qdot::dot_row(TY, r, col, k).unwrap();
                            }
                            std::hint::black_box(acc);
                        });
                    }
                });
                passes += 1;
            }
            (passes * per * t * rb) as f64 / st.elapsed().as_secs_f64() / 1e9
        });
    }
    // DRAM streaming through the row lanes, T = 16: each group packed once, then dotted with `runs` runs of
    // 8 columns (8: a group read once a run; 64: a prompt batch whose experts see 64 columns).
    for runs in [1usize, 8] {
        let t = 16;
        report(arm, &format!("lanes{}-dram-T{t}", 8 * runs), "GB/s", reps, || {
            let groups = big_rows / g;
            let per = groups / t;
            let st = Instant::now();
            let mut passes = 0;
            while st.elapsed().as_secs_f64() < secs * 2.0 || passes == 0 {
                std::thread::scope(|s| {
                    for i in 0..t {
                        let part = &big[i * per * g * rb..(i + 1) * per * g * rb];
                        let cs = &cs;
                        s.spawn(move || {
                            let mut packed = vec![0u8; qdot::lane_pack_bytes(k)];
                            let mut lo = vec![[0.0f32; 8]; 8];
                            let mut acc = 0.0f32;
                            for grp in part.chunks_exact(g * rb) {
                                qdot::pack_lanes(TY, grp, &[], k, &mut packed).unwrap();
                                for _ in 0..runs {
                                    qdot::dot_lanes_cols(TY, &packed, cs, k, &mut lo).unwrap();
                                    acc += lo[0][0];
                                }
                            }
                            std::hint::black_box(acc);
                        });
                    }
                });
                passes += 1;
            }
            (passes * per * t * g * rb) as f64 / st.elapsed().as_secs_f64() / 1e9
        });
    }
    std::hint::black_box(sink);
}

AI help

AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.

@midagedev

Copy link
Copy Markdown
Owner

Thank you. Bit-identical bodies picked at run time, with an off switch in the same binary, are the shape we want for #81. It touches qdot, the lever registry and the release build, so we review it after tonight's train lands, and it joins the next one. We will run the qdot and kernel gates on our side and keep your commits.

@midagedev

Copy link
Copy Markdown
Owner

좋은 CPU가 있으시군요 부럽습니다!!

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: CLEAN: I built no failure path through the three new AVX-512 bodies that the code or the tests do not block.

Non-blocking

⚠ A bad BLOOMERY_QDOT_AVX512 value panics at the first Q4_K dot, not at load: crates/qdot/src/lib.rs:266. q4k_avx512() is lazy and nothing outside qdot calls it at start. With BLOOMERY_QDOT_AVX512=yes the server loads, then panics in a pool worker on the first host Q4_K request. The row says Phase::Load (registry.rs:986). Fix direction: call qdot::q4k_avx512() once where the host tier is built.

⚠ Default is on for CPUs nobody measured: registry.rs:981. The release binary reaches every AVX-512 VNNI CPU: Zen 4 (256-bit datapath), Ice Lake and Sapphire Rapids (clock license). The PR measures Zen 5 only. Question: ship opt-in until a second CPU reports? The change is Unset::Is("0") and None => false.

⚠ The PR says AGENTS.md bans splitting these bodies. The rule allows an #[inline(always)] helper (AGENTS.md:331). The dy/my setup now exists in four bodies (lib.rs:4832, lib.rs:5386 and the two AVX2 twins). One helper keeps the bits and the speed. Check with the A/B.

Also 2 minor: hw_q4k_avx512_matches_avx2_synthetic re-runs assert_tile_matches and assert_lanes_match on the row sets of hw_lanes_match_dot_row_synthetic; the dot_row_avx2 doc sentence (lib.rs:556) is hard to read.

Checked

  • Duplicates: 5 new items checked, dryer 0 pairs.
  • Complexity: crapper did not run. By reading, growth is even (one arm each).
  • Silent failure: 4 sites followed. The lever value panics by name; the odd C case stays in range.
  • Tests: mutation check done. Planting 0x00FF for the d8 mask, .min(C) or the c % 2 half turns an assertion red.
  • Gates: unsafe-ratchet 130/73 → 134/75 with a dated PIN; the count matches.
  • Escape catalog: no match.

Notes

  • tools/levers-direct.txt says lever lines only shrink and this PR adds one. The author asks for a decision.
  • AGENTS.md:3-4 and AGENTS.md:269 still say AVX2 only for the host kernels.

midagedev added a commit that referenced this pull request Oct 13, 2026
…t a failed run

crapper prints "No source files to analyze" and exits 0 on a test file, writing no snapshot; the diagnostics read
that as a failure and dropped the whole complexity section (PR #86, crates/qdot/tests/qdot.rs).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added host Host crates: qdot, threads, engram, engram-lab, runtime, sampler, levers, decision, vision, refset tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo labels Oct 13, 2026

Copy link
Copy Markdown
Owner

측정과 설명 감사합니다. 세 가지 결정입니다.

  • 기본값: 켜 둔 채로 가겠습니다. 비트가 같고, 다른 CPU에서 느려진다는 보고가 나오면 그때 조정하겠습니다.
  • in-place read와 레버 이름: 지금 방식 그대로 괜찮습니다.
  • 부탁 두 가지: main 위로 리베이스해 주세요. 그리고 Shingler가 짚은 대로 qdot::q4k_avx512()를 호스트 tier를 만들 때 한 번 호출해서, 잘못된 BLOOMERY_QDOT_AVX512 값이 첫 요청이 아니라 로드 시점에 거부되게 해 주세요.

이 댓글은 @midagedev를 위해 bloomery AI 어시스턴트가 작성했습니다.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: MUST_FIX: The Q4_K lane gate is duplicated, the AVX-512 gate misses disabled dispatch, and the new kernels violate R1's unsafe-scope rule.

Must fix

1. Give the Q4_K synthetic lane clause one owner (kind B)

crates/qdot/tests/qdot.rs:6039 repeats the clause at crates/qdot/tests/qdot.rs:5952. Both call assert_lanes_match with identical Q4_K 0xFF rows at k = 4096 and identical lane_columns, through the same dispatch. The extra AVX2 comparison does not remove the repeated lane clause. AGENTS.md requires one test per contract.
One owner avoids maintaining two gates when this contract changes. Keep Q4_K in the new gate, which also covers k = 512 and 768. Replace the existing gate's first doc line and type loop with:

/// Row-lane clause on synthetic rows: for Q5_K and Q6_K, groups of
    // PIN(2026-10-13): Q4_K's clause moved to hw_q4k_avx512_matches_avx2_synthetic.
    for ty in [GgmlType::Q5_K, GgmlType::Q6_K] {

2. Assert that enabled dispatch selects AVX-512 (kind B)

crates/qdot/tests/qdot.rs:5985 only checks that an unsupported CPU cannot select AVX-512. Replacing crates/qdot/src/lib.rs:283's selector expression with false passes this assertion; subsequent comparisons exercise AVX2 and stay green. On a supported CPU with the lever enabled, the gate misses a selector regression that bypasses the new kernels.
Add the assertion now so the gate detects this mutant. Replace lines 5985–5988 with:

    let wanted = std::env::var_os("BLOOMERY_QDOT_AVX512").is_none_or(|v| v == "1");
    assert_eq!(qdot::q4k_avx512(), isa && wanted);

3. Narrow the new kernels' unsafe scopes (kind B, R1)

crates/qdot/src/lib.rs:4919 and crates/qdot/src/lib.rs:5520 wrap entire kernel bodies in unsafe. R1 forbids this and requires one operation per block with its local SAFETY proof. check-unsafe.sh counts blocks; it does not enforce scope.
Localize the proofs before these bodies grow. Remove the outer blocks and wrap each unsafe operation inside the existing target-feature bodies. For example, replace the pointer offset at line 4972 with:

                // SAFETY: i < nb; the column holds 2 * nb Q8_2_X4 groups.
                let g0 = unsafe { col.add((2 * i) * Q82X4_STRIDE) };

Apply this to the remaining pointer operations, loads, stores and unsafe helper calls in both bodies. Keep the kernel bodies intact and re-pin the resulting unsafe-block counts with a dated reason.

Non-blocking

⚠ Keep the paired scale conversion: crates/qdot/src/lib.rs:4926 converts d and dmin separately; the AVX2 kernel at crates/qdot/src/lib.rs:3809 uses one paired conversion. This adds k/256 source-level F16C conversions per Q4_K row dot [derived]. Reuse the existing helper:

            let (d, dmin) = f16c_pair_to_f32([wb[0], wb[1], wb[2], wb[3]]);

The integer-path reorder needs the owning qdot gate; the dispatch change needs an A/B on the contributor's machine. Provide evidence for the current base and head, including the required nvidia-smi line. The PR body reports earlier commit hashes.

Checked

Duplicates: the repeated lane clause is confirmed. ISA twins follow the kernel exemption. Diagnostics report 0 dryer pairs.
Complexity: diagnostics report dot_row at 18 → 19; the diff adds one ISA guard to its match.
Silent failure: invalid lever values panic by name; the lane kernel's replicated odd column is not returned.
Tests: bit assertions compare dot_row with AVX2/scalar and tile/lanes with dot_row. The selector-off mutant bypasses AVX-512 coverage. The PR reports FAIL-first arithmetic mutants.
Gates: unsafe ratchet 141/77 → 145/79 has a dated PIN. The release allowlist names the guarded AVX-512 bodies.
Escape catalog: no C1–C4 pattern in the changed script; release pipelines use pipefail.

Notes

The PR reports full qdot runs failing on missing fixtures in both arms. Validation was static; no hardware gates were run.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

Comment thread crates/qdot/src/lib.rs Outdated
Comment on lines +4926 to +4927
let d = f16c_to_f32(u16::from_le_bytes([wb[0], wb[1]]));
let dmin = f16c_to_f32(u16::from_le_bytes([wb[2], wb[3]]));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use the existing paired conversion to perform one F16C conversion per weight block.

Suggested change
let d = f16c_to_f32(u16::from_le_bytes([wb[0], wb[1]]));
let dmin = f16c_to_f32(u16::from_le_bytes([wb[2], wb[3]]));
let (d, dmin) = f16c_pair_to_f32([wb[0], wb[1], wb[2], wb[3]]);

Comment thread crates/qdot/tests/qdot.rs Outdated
Comment on lines +5985 to +5988
assert!(
isa || !qdot::q4k_avx512(),
"q4k_avx512 picked the AVX-512 VNNI bodies on a CPU without their ISA"
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An always-disabled AVX-512 selector currently passes this gate; assert the expected arm too.

Suggested change
assert!(
isa || !qdot::q4k_avx512(),
"q4k_avx512 picked the AVX-512 VNNI bodies on a CPU without their ISA"
);
let wanted = std::env::var_os("BLOOMERY_QDOT_AVX512").is_none_or(|v| v == "1");
assert_eq!(qdot::q4k_avx512(), isa && wanted);

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: MUST_FIX: The unsafe-scope fix still groups independent memory operations in single blocks.

Must fix

1. Finish the unsafe-scope fix (kind B, R1)

crates/qdot/src/lib.rs:4976 loads two separate groups in one unsafe block; crates/qdot/src/lib.rs:5576 writes two separate arrays. Other paired loads have the same defect. R1 requires one operation per block; its contiguous vector-load exception does not cover separate groups or arrays. The unsafe checker counts blocks and does not enforce their scope.
Local proofs cost less to fix now than after these bodies gain more access sites.

In both kernels, replace the (h1, h2) bindings with:

// SAFETY: g0's validated group has 8 readable header bytes.
let h1 = unsafe { _mm_loadl_epi64(g0 as *const __m128i) };
// SAFETY: g1's validated group has 8 readable header bytes.
let h2 = unsafe { _mm_loadl_epi64(g1 as *const __m128i) };

Replace both (s1, s2) bindings with:

// SAFETY: offset 8 lies inside g0's validated 144-byte group.
let p0 = unsafe { g0.add(8) };
// SAFETY: offset 8 lies inside g1's validated 144-byte group.
let p1 = unsafe { g1.add(8) };
// SAFETY: p0 points at the group's readable bytes 8..16.
let s1 = unsafe { _mm_loadl_epi64(p0 as *const __m128i) };
// SAFETY: p1 points at the group's readable bytes 8..16.
let s2 = unsafe { _mm_loadl_epi64(p1 as *const __m128i) };

In the tile, replace the mins8 binding and its comment with:

// SAFETY: offset 2 lies inside utmp's four u32 elements.
let min_ptr = unsafe { utmp.as_ptr().add(2) };
// SAFETY: min_ptr points at the final 8 readable bytes of utmp.
let mins8 = unsafe { _mm_loadl_epi64(min_ptr as *const __m128i) };

Replace the tile's half and act closures with:

let half = |o: usize, p: usize| {
    let lo = &q4[o..o + 32];
    let hi = &q4[p..p + 32];
    // SAFETY: lo is a checked 32-byte slice.
    let lo = unsafe { _mm256_loadu_si256(lo.as_ptr() as *const __m256i) };
    // SAFETY: hi is a checked 32-byte slice.
    let hi = unsafe { _mm256_loadu_si256(hi.as_ptr() as *const __m256i) };
    _mm512_inserti64x4::<1>(_mm512_castsi256_si512(lo), hi)
};
let act = |o: usize| {
    // SAFETY: o <= 96; offset 16 + o lies inside g0's group.
    let p0 = unsafe { g0.add(16 + o) };
    // SAFETY: o <= 96; offset 16 + o lies inside g1's group.
    let p1 = unsafe { g1.add(16 + o) };
    // SAFETY: 16 + o + 32 <= 144; p0 has 32 readable bytes.
    let lo = unsafe { _mm256_loadu_si256(p0 as *const __m256i) };
    // SAFETY: 16 + o + 32 <= 144; p1 has 32 readable bytes.
    let hi = unsafe { _mm256_loadu_si256(p1 as *const __m256i) };
    _mm512_inserti64x4::<1>(_mm512_castsi256_si512(lo), hi)
};

In the lane kernel, replace the paired store block with:

// SAFETY: dy[c][ii] is a writable [f32; 8].
unsafe { _mm256_storeu_ps(dy[c][ii].as_mut_ptr(), dyv) };
// SAFETY: my[c][ii] is a writable [f32; 8].
unsafe { _mm256_storeu_ps(my[c][ii].as_mut_ptr(), myv) };

Replace the (q0, q1) binding with:

// SAFETY: c0 < C and at + 16 <= 2 * nb * Q82X4_STRIDE.
let p0 = unsafe { acols[c0].add(at) };
// SAFETY: c1 < C and at + 16 <= 2 * nb * Q82X4_STRIDE.
let p1 = unsafe { acols[c1].add(at) };
// SAFETY: p0 points at 16 readable bytes of column c0.
let q0 = unsafe { _mm_loadu_si128(p0 as *const __m128i) };
// SAFETY: p1 points at 16 readable bytes of column c1.
let q1 = unsafe { _mm_loadu_si128(p1 as *const __m128i) };

Keep these operations inside the existing target-feature bodies. Re-pin the unsafe count with a dated R1 reason after applying the replacements.

Non-blocking

⚠ Validation evidence remains open: crates/qdot/src/lib.rs:4925 now uses the paired conversion. The reported runs name earlier commits. Provide the owning qdot gate in both lever arms and current base/head A/B commands and output (R20), with CONTRIBUTING's evidence list, including the nvidia-smi line.

Checked

Duplicates: 0 new functions/types/constants in this increment; existing paired-conversion owner reused. The duplicate Q4_K lane clause is removed.
Complexity: no control-flow branch added to either kernel; dot_row is unchanged in this increment.
Silent failure: 0 new default/discard sites. Tile and lane callers validate lengths and return named shape errors.
Tests: statically, forcing the selector false fails the new equality assertion when ISA and lever are enabled. The Q4_K synthetic gate retains bit comparisons for rows, tiles and lanes; Q5_K/Q6_K retain their lane assertions.
Gates: clause move and unsafe-ratchet increase have dated PIN reasons; no numeric band moved.
Escape catalog: no C1–C4 match in this increment.
Adversarial: input validation rejects short buffers; chunk tails and odd columns use bounded indices. FMA order is unchanged.

Notes

The reported full qdot runs fail on missing fixtures in both arms. Review validation was static; no hardware gates were run.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@midagedev

Copy link
Copy Markdown
Owner

Sorry, we made a mistake here. While tidying PRs we rebased your branch onto main and pushed two extra commits (ad7a4cb9, 9cc1a203) addressing Shingler's review, which we shouldn't have done without asking. Your original commit is preserved as 43e75820. How would you like us to handle it? We can remove our commits and restore your branch as it was, or you can keep any part that's useful. Sorry for the trouble.

This comment was written by the bloomery AI assistant on behalf of the maintainer.

@juliankang4

Copy link
Copy Markdown
Collaborator Author

No harm done, and thanks for flagging it. Please keep ad7a4cb9 and 9cc1a203: they take care of the review, and building on them beats redoing the same work. The rest of my changes will go on top as new commits, so the branch won't be rewritten under them.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: MUST_FIX: invalid override values bypass scalar-path validation, and the synthetic Q4_K fixture table has two owners.

Must fix

1. Validate the override before choosing a scalar path

Kind A. crates/qdot/src/lib.rs:477 and crates/qdot/src/lib.rs:294: BLOOMERY_QDOT_AVX512=2 with valid Q4_K inputs returns a scalar dot on aarch64 or x86_64 without AVX2, instead of the promised named panic. The x86_64 guard skips the parser when hw is false; the non-x86_64 entry never calls it. Startup does not close this path: crates/levers/src/lib.rs:684 skips Direct rows.
Closing this now keeps invalid configuration from becoming accepted behavior on more backends.

Replace both selector definitions with one implementation:

/// Whether Q4_K uses AVX-512 VNNI; false on other architectures.
/// Reads its override once and refuses values other than 0 or 1 by name.
#[must_use]
pub fn q4k_avx512() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| {
        let wanted = match std::env::var_os("BLOOMERY_QDOT_AVX512") {
            None => true,
            Some(v) if v == "1" => true,
            Some(v) if v == "0" => false,
            Some(v) => panic!("BLOOMERY_QDOT_AVX512={v:?}: takes 0 or 1"),
        };
        #[cfg(target_arch = "x86_64")]
        let isa = has_features(GgmlType::Q4_K)
            && std::arch::is_x86_feature_detected!("avx512f")
            && std::arch::is_x86_feature_detected!("avx512bw")
            && std::arch::is_x86_feature_detected!("avx512vnni");
        #[cfg(not(target_arch = "x86_64"))]
        let isa = false;
        wanted && isa
    })
}

In x86 dot_row, insert this after check_row and change the Q4_K guard from if q4k_avx512() to if avx512:

let avx512 = w == GgmlType::Q4_K && q4k_avx512();

Replace the non-x86 dot_row with:

#[cfg(not(target_arch = "x86_64"))]
pub fn dot_row(w: GgmlType, wrow: &[u8], acol: &[u8], k: usize) -> Result<f32, QdotError> {
    if w == GgmlType::Q4_K {
        let _ = q4k_avx512();
    }
    dot_row_scalar(w, wrow, acol, k)
}

2. Give the Q4_K fixture table one owner

Kind B. crates/qdot/tests/qdot.rs:4381 and crates/qdot/tests/qdot.rs:6023 contain the identical six (k, rows, seed) tuples. Both clauses generate Q4_K rows from this table. R14 requires one owner.
Extracting the table now prevents later coverage changes from requiring two edits.

Add this beside the fixture helpers:

const Q4K_SYNTHETIC_ROWS: [(usize, usize, u64); 6] = [
    (256, 16, 0x5a12_0001),
    (512, 16, 0x5a12_0005),
    (768, 16, 0x5a12_0006),
    (2048, 16, 0x5a12_0002),
    (2304, 16, 0x5a12_0003),
    (4096, 24, 0x5a12_0004),
];

Replace each six-tuple array literal with Q4K_SYNTHETIC_ROWS. Keep the tile loop and the lane test's existing .iter().map(...).collect().

Non-blocking

⚠ Refresh the validation evidence: crates/qdot/tests/qdot.rs:6066 moves tile coverage into the model-dependent gate; the old lane test also loses Q4_K. The PR body still describes their earlier arrangement. Rerun the changed clauses and FAIL-first mutants at this head on the AVX-512 host, and identify clauses completed before missing-model failures.

⚠ Complete the performance evidence: crates/qdot/src/lib.rs:4912 changes the decode and prompt integer path. The CPU, model, arm commands and rates are given, but the required nvidia-smi output is absent. Attach that output with the compared hashes and run output required by CONTRIBUTING.

Checked

Duplicates: 7 new function/constant definitions searched, counting cfg variants separately; both fixture tables confirmed. ISA kernel bodies have the R12 exemption.

Complexity: dot_row gains one guarded ISA arm.

Silent failure: traced the selector, scalar fallback and startup parser. Column-count guards bound the lane pairing and chunk minima.

Tests: read the bit comparisons and NaN canaries. Static mutant checks cover swapped scale fields (:4925), wrong column reduction (:5034), swapped FMAs (:5026–5027), wrong activation half (:5622) and a dropped output copy (:1268). No tests or mutants were run during validation. No scalar-path invalid-override assertion exists.

Gates: unsafe-count increases and coverage moves have dated PIN reasons; no numeric band changes.

Escape catalog: C1–C4 do not match the changed shell code; pipefail is enabled. No ledger lessons are in force.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

juliankang4 and others added 7 commits October 14, 2026 11:13
…odies, picked at run time (qdot::q4k_avx512, BLOOMERY_QDOT_AVX512) and bit-identical to the AVX2 ones, and the release check lists the two bodies as runtime-dispatched; hw_q4k_avx512_matches_avx2_synthetic and the f16 scale sweep hold them to dot_row_avx2 and the scalar mirror (FAIL-first: the tile's sub-block fmas swapped, a sub-block paired with the wrong activations, or a lane half reading the other half's activations turns it red)
… block per operation with its SAFETY line (R1), d and dmin through f16c_pair_to_f32, Q4_K's synthetic lane clause owned by hw_q4k_avx512_matches_avx2_synthetic, and that gate asserts the selector picks AVX-512 exactly where the ISA is present and the lever allows
…lock per pointer offset, load and store (R1), and the synthetic tile fixtures owned by hw_q4k_tile_matches_dot_row
Three AVX2 helpers take over setup that the Q4_K and Q5_K kernels repeated.
q82x4_dy_my reads a column's dy (the eight blocks' bf16 scales as f32) and
my (dy times the blocks' i16 sums) from the heads of super-block i's two
Q8_2_X4 groups. q45k_scales_ps and q45k_mins_ps turn a block's unpacked
scales and mins into eight f32 each. Each kernel still multiplies them by
d and -dmin itself, where it did before.

dot_q4k_q82x4_avx2, dot_q5k_q82x4_avx2, dot_q45k_q82x4_tile_avx2,
pack_lanes_avx2 and dot_lanes_avx2 call them, and so do the two AVX-512
bodies, which also lose their extra block level. The helpers carry
#[target_feature(enable = "avx2")] and #[inline], and keep one unsafe
operation per block with its SAFETY line (R1).

At x86-64-v3 and znver3, every out-of-line AVX2 kernel and tile::<C>
keeps its instructions, and so do dot_lanes_avx2 and
dot_q45k_q82x4_tile_avx2 when they are kept out of line. The two AVX-512
bodies, and dot_lanes_cols, which inlines the AVX2 lanes, compile
differently. The qdot pin in tools/unsafe-ratchet.txt goes from 180 blocks
and 79 fns to 172 and 80.
dot_row_cols now chooses Q4_K's AVX-512 VNNI tile before its column-count
match and calls tile_q4k_avx512::<C>. tile::<C> loses its guard arm and is
main's code again. With the arm inside, it changed the register
allocation of the whole function and slowed the AVX2 tiles too. One local
macro maps the column count to C for both tiles.

dot_lanes_cols picks a LaneKind (Q45K, Q4KAvx512 or Q6K) once a call, and
lanes::<C> matches on it instead of asking q4k_avx512 per chunk.
q4k_synthetic_rows builds Q4_K's seeded row sets and the all-0xFF rows at
k = 4096. hw_q4k_tile_matches_dot_row and
hw_q4k_avx512_matches_avx2_synthetic both read it, so the two clauses no
longer carry their own copies of the same sets. The tile clause's PIN
states where its rows now come from.
…t load

q4k_avx512 is now one function on every architecture. It reads the lever
first, panics by name on any value other than 0 or 1, and only then asks
the CPU; off x86_64 the answer is false. Every Q4_K dot_row asks it,
including the scalar arm off x86_64 and on an x86_64 CPU without AVX2.
model::ops::host_stack_runs asks it first for a Q4_K stack, so a refused
value stops the host tier's load before the server listens.

dot_row_refuses_a_qdot_lever_value_by_name and
host_layer_build_refuses_a_qdot_lever_value_by_name run a Q4_K dot_row and
a Q4_K host layer build in a fresh process with the lever at 2, and hold
the panic to name the lever. Taking the ask out of dot_row's AVX2 Q4_K arm
or out of host_stack_runs turns its test red.

tools/defaults-twins.tsv gets a none row for the refusal probe's value.
The qdot test file's line in tools/levers-direct.txt names the lever,
which the AVX-512 gate reads to know which body q4k_avx512 must pick.
The PIN above DISPATCHED names the check every caller passes before it
reaches qdot's two Q4_K AVX-512 VNNI bodies: AVX-512 F, BW and VNNI beside
the AVX2 kernels' AVX2, FMA and F16C.
README.md, docs/performance.md and tools/release/README.release.md said
the host kernels are AVX2 only. The release README's requirements line
now says AVX-512 is optional.
@juliankang4

Copy link
Copy Markdown
Collaborator Author

Thanks for the third pass. Earlier on this thread I said the branch would not be rewritten under the maintainer's two commits. That did not hold: cff55213 on main conflicts with this branch in tools/release/build.sh, and main takes pull requests by rebase (linear history, CONTRIBUTING.md), so I rebased onto main 33fb317b instead of merging main in. The three commits already on the PR, 43e75820 and the maintainer's ad7a4cb9 and 9cc1a203, keep their authors and their diffs, apart from 43e75820's two lines in build.sh, which now sit in cff55213's new check. Their hashes change: 43e75820 is now f566d8ba, ad7a4cb9 is 2e31d011 and 9cc1a203 is 0f4d36e6. The branch as it was before the rebase stays on the fork as qdot-avx512-q4k-measured-f8e32756. Six new commits sit on top of them, one contract each: ef6e0c45 (the shared helpers), 2fb45954 (where the tile picks its AVX-512 body), 4052f514 (one owner for Q4_K's synthetic rows), d9119c85 (a refused lever value stops dot_row and the host load), e4412d01 (the release PIN) and 0094a925 (docs). The PR body is updated to the new head, and its "Commits" section says what each one holds.

1. Validate the override before choosing a scalar path. Fixed in d9119c85. q4k_avx512() is now one function on every architecture, in the shape the review gave: it reads the lever first, panics by name on any value other than 0 or 1, and only then asks the CPU (the answer is false off x86_64). Off x86_64, dot_row asks it for Q4_K before it runs the scalar mirror.

On x86_64 I used a different form than let avx512 = w == GgmlType::Q4_K && q4k_avx512(); after check_row. The guard arm (GgmlType::Q4_K, true) if q4k_avx512() stays, and a new (GgmlType::Q4_K, false) arm asks q4k_avx512() and then runs the scalar mirror. Both forms read the lever on every Q4_K call. With the suggested form, the compiler inlined dot_q4k_q82x4_avx2 into dot_row at x86-64-v3 and znver3, so the AVX2 Q4_K kernel no longer existed as its own function. With the extra arm, every kernel keeps its machine code at both targets. Only two functions change: dot_row (197 instructions, now 205 in the qdot library and 207 in the kernel bench) and the selector's OnceLock initializer, which now checks the lever before it asks the CPU.

model::ops::host_stack_runs now asks q4k_avx512() first for a Q4_K stack, before it asks whether qdot has a kernel for the type, so the load names the lever on an x86_64 CPU without AVX2 too.

A new test holds the dot_row side: dot_row_refuses_a_qdot_lever_value_by_name (crates/qdot/tests/qdot.rs:6010, a plain #[test] on every architecture). It runs its test binary again in a fresh process with BLOOMERY_QDOT_AVX512=2. There, a Q4_K dot_row must panic, and the panic must name the lever. At f8e32756, the head before the rebase, it passes on the Zen 5 box and on a DGX Spark (aarch64, debug build), on both also with BLOOMERY_QDOT_AVX512=0 set for the whole run. FAIL-first: when the AVX2 Q4_K arm stops asking q4k_avx512(), the test turns red on the Zen 5 box. When the aarch64 dot_row stops asking, it turns red on the Spark (Ok(-572683.25) in place of the panic). The same mutant on the x86_64 arm for a CPU without AVX2 stays green on the Zen 5 box, because that arm runs only on such a CPU. The load test, host_layer_build_refuses_a_qdot_lever_value_by_name, no longer carries #[cfg(target_arch = "x86_64")]. It passes on both machines, and with the q4k_avx512() call taken out of host_stack_runs it turns red on both (Ok(()) in place of the panic).

The test sets BLOOMERY_QDOT_AVX512=2 in a file that gate-qdot runs, so check-defaults asked for a row. tools/defaults-twins.tsv now has a none row with a dated reason, the same shape as the BLOOMERY_QWEN3_KV q6_0 refusal probe: no path runs at a refused value.

2. Give the Q4_K fixture table one owner. Done in 4052f514, as a function rather than the suggested const: q4k_synthetic_rows() (crates/qdot/tests/qdot.rs:5740) returns the six seeded sets and the all-0xFF rows at k = 4096, which lane_fill builds at run time. The tile loop in hw_q4k_tile_matches_dot_row and the set list in hw_q4k_avx512_matches_avx2_synthetic both read it. The tile clause's PIN(2026-10-14) now says where its rows come from.

t0 red on check-levers at 9cc1a203. The AVX-512 gate in crates/qdot/tests/qdot.rs reads BLOOMERY_QDOT_AVX512 with env::var_os, to know which body q4k_avx512() must pick. The line for that file in tools/levers-direct.txt did not name the lever. I reproduced the red at 9cc1a203 (crates/qdot/tests/qdot.rs:6010 there). That line now names the lever. just contrib-check --tier t0 at 0094a925: DONE tier=t0 total=78 red=0.

Non-blocking items.

  • Validation evidence: at f8e32756, the changed clauses ran on the Zen 5 box in both arms, and the eight FAIL-first mutants ran once each with the lever unset (the AVX-512 arm). Seven turn an assertion red; the eighth, the arm for a CPU without AVX2, stays green there (above). The PR body's "Bit checks" says which clauses finish before an input they cannot read: the tile gate's synthetic part passes on every row of the shared list, and the test then opens the model file and stops where the reference dump cannot be read (PermissionDenied).
  • Performance evidence: the body's "Hardware" section now carries the nvidia-smi lines (card and driver). The body also names the base, each build it timed, the model file, and the commands with their output. The timed builds are on the fork as branches named qdot-avx512-q4k-measured-<hash>, so their hashes resolve, and the body's "Machine code" lists, step by step, which functions differ from those builds to the head. Because dot_row changed, I timed the kernel bench of fbf33c06's code (the branch's head before this split, same code apart from the fixes listed here) again against one built just before that change: dot1-l2 moves by -0.6 % to +0.7 % (median of 4 rounds) across both arms and both k, while the 24 cases whose machine code did not change read from -1.1 % to +1.1 % between the same two binaries. The numbers are under "Kernel rates".

The release allowlist (the inline note on #140). e4412d01 adds a dated PIN(2026-10-12) comment above DISPATCHED in tools/release/build.sh. It names the CPU check that every caller passes before it reaches the two AVX-512 bodies: AVX-512 F, BW and VNNI, beside the AVX2 kernels' AVX2, FMA and F16C. At 0094a925, the check from cff55213, which reads each instruction's encoding, passes on the x86-64-v3 server build. With either body taken out of DISPATCHED it fails and names that body's instances (four of dot_lanes_avx512, eight of dot_q4k_q82x4_tile_avx512), and with both taken out it names those twelve and nothing else. The PIN comment itself is not read by the check; taking it out leaves the check green.

What else the new commits do. 0f4d36e6 already split the AVX-512 bodies into one unsafe operation per block. ef6e0c45 keeps that rule in the bodies and in three new AVX2 helpers; the AVX2 kernels that now call the helpers keep main's whole-body unsafe {}. 2fb45954 brings tile::<C> back to main's machine code (the PR body's "The choice inside tile"), with one local macro mapping the column count for both tiles. The bit check prints the same 876 lines for main 5c98cc70, main 33fb317b, and both arms of f8e32756 and of 0094a925 (md5 1f2cf765ffc2d78e92a63e41b8bcb9f2). 0094a925 updates the README, docs/performance.md and the release README. The same AVX2-only wording in AGENTS.md (:3-4 and :128) is left for the maintainer.

@github-actions github-actions Bot added documentation Improvements or additions to documentation model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja labels Oct 14, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: CLEAN: No must-fix finding remains; the reference-backed Q4_K gate still needs a complete run.

Non-blocking

⚠ Complete the reference-backed Q4_K gate: crates/qdot/tests/qdot.rs:4376. The PR reports 41 fixture-read failures in each selector arm, including this test's reference dump read at line 4393. Run both arms at the head on a CPU with AVX-512 F, BW and VNNI and readable model and reference files, and attach the output before release.

BLOOMERY_BOX_LOCAL=1 BLOOMERY_QDOT_AVX512=1 just gate-qdot
BLOOMERY_BOX_LOCAL=1 BLOOMERY_QDOT_AVX512=0 just gate-qdot

Checked

Duplicates: shared factor setup and Q4_K synthetic rows reuse common owners. The dryer pair shares wrapper shape but has different formats and output contracts.

Complexity: crapper reports dot_lanes_cols (13 → 16) and dot_row (18 → 20). Both add dispatch arms; growth alone proves no defect.

Silent failure: 5 added sites checked. Three discarded selector results retain named validation; two empty panic-message defaults fail assertions.

Tests: the PR reports FAIL-first for removed lever checks, swapped FMAs and wrong activation halves. Tile and lane assertions compare output bits; Q5_K/Q6_K lane clauses remain. Hardware tests were not run during validation.

Gates: release ISA exceptions, the unsafe ceiling and the moved Q4_K lane clause have dated reasons. No numerical band changed.

Escape catalog: C1–C4 do not match the changed shell code; the release scan retains pipefail and checks its result.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@midagedev
midagedev merged commit fadec9d into midagedev:main Oct 14, 2026
7 checks passed
@juliankang4

Copy link
Copy Markdown
Collaborator Author

Follow-up on the last review's non-blocking item: the reference-backed Q4_K gate in both selector arms.

Tree: main 65990b09, whose crates/qdot is the same as the reviewed head 0094a925's. CPU: Ryzen 9 9950X, whose /proc/cpuinfo flags include avx2 fma f16c avx512f avx512bw avx512vl avx512_vnni.

Where the PermissionDenied came from. The tests and tools/ref/ref-paths.sh default BLOOMERY_DATA to /root/bloomery-data. A contributor's run is not root and /root is mode 0700, so the read fails at crates/qdot/tests/qdot.rs:4394 with PermissionDenied (reproduced on this tree). Pointing BLOOMERY_DATA at a directory the user owns, as docs/contrib/local-check.md does, removes it. With that directory empty, the error becomes "No such file or directory" and each arm still reads 42 passed, 41 failed.

The reference files. The repository does not pin the ik commit behind $BLOOMERY_DATA/ref, and the refset dataset has no V2-Lite ref set, so I built them on this machine from ik_llama.cpp d4fbf593 (public main, 2026-10-14), CPU only, GGML_NATIVE=OFF with AVX2, FMA and F16C. They are not the maintainers' reference set. tools/ref/dump.sh wrote the V2-Lite set (1155 tensors). The dumpers from build-qdot-ref.sh whose inputs are on this machine ran with that script's flags: q4k_x4_ref, q6k_x4_ref, q5f0_ref, q5f1_ref, q8f0_ref, iq3s_ref, iq4nl_ref, and iq4xs_ref (synthetic blocks, because the UD-Q3_K_XL file is absent).

Commands. just is not installed there, so this is the recipe's body, once per arm, with the machine's environment file (it adds the LLVM 21 llc):

LC_ALL=C BLOOMERY_BOX_LOCAL=1 BLOOMERY_DATA=$DATA BLOOMERY_BOX_ENV='BLOOMERY_QDOT_AVX512=1' \
  ./tools/box.sh 'bash tools/gate.sh --release -p bloomery-qdot --test qdot -- --include-ignored --nocapture'

The second run is the same with BLOOMERY_QDOT_AVX512=0. The lever given as a plain variable, as in the review's commands, selects the arm as well: hw_q4k_avx512_matches_avx2_synthetic alone prints the AVX-512 body under =1 and the AVX2 one under =0.

Result.

BLOOMERY_QDOT_AVX512=1: test result: FAILED. 60 passed; 23 failed
BLOOMERY_QDOT_AVX512=0: test result: FAILED. 60 passed; 23 failed

Both exit with 101, and the 23 failures are the same tests with the same messages in both arms. hw_q4k_avx512_matches_avx2_synthetic passes in both and prints the body it ran: Q4_K AVX-512 VNNI: ... under =1, and Q4_K AVX2 (no AVX-512 VNNI body on this CPU or under BLOOMERY_QDOT_AVX512=0): ... under =0.

The Q4_K clauses that read the references, in both arms:

  • hw_q4k_dot_row_matches_scalar_and_predicts passes. Our 2304 encoder bytes equal ik's quantize_row_q8_2_x4, 1024 rows of the kernel equal the emulator bit for bit, and 64 rows land within 1 ULP of ik's mul_mat_qX_K_q8_2_X4_T.
  • hw_q4k_tile_matches_dot_row (qdot.rs:4376) passes its synthetic rows and the V2-Lite part (blk.0.attn_output.weight, k = 2048, on ik's column and the seeded ones: 20480 calls, bit-identical). It then stops on the V4.1 Q3_K_M shards, which this machine does not have. With BLOOMERY_V41_MODEL set to the V4.1 fixture, it runs to the end in both arms (blk.2.ffn_down_exps.weight, k = 512: 18432 calls, bit-identical), and so does hw_lanes_match_dot_row_v41. The fixture's weights are seeded, so that run only checks our kernels against each other; it reads 66 passed, 17 failed in each arm. Of the four Q4_K checks the PR body named, two still wait for the real V4.1 shards: the V4.1 part of hw_q4k_tile_matches_dot_row and hw_lanes_match_dot_row_v41.

Gate 4 (hw_scalar_fallback_bit_identical_to_avx2, Q3_K, AVX2 against the scalar mirror) reads ffn_norm-1 and kv_compressed-1 from the V2-Lite set and passes in both arms.

Still red, the same in both arms, by missing input:

  • V4.1 Q3_K_M shards (10): hw_q4k_tile_matches_dot_row (after its V2-Lite part), hw_lanes_match_dot_row_v41, hw_q3k_tile_matches_dot_row, hw_q3k_r8_tile_matches_dot_row, hw_q6k_tile_matches_dot_row, hw_q5k_tile_matches_dot_row, hw_q5k_kernel_matches_emulator, hw_q5k_encoder_matches_ik, hw_q5k_kernel_predicts_ik, hw_q5k_dequant_matches_ggml.
  • V4-Flash UD-Q3_K_M (5): hw_iq3xxs_kernel_matches_mirror, hw_iq3xxs_kernel_predicts_ik, hw_mxfp4_encoder_matches_ik, hw_mxfp4_kernel_matches_mirror, hw_mxfp4_kernel_predicts_ik.
  • Qwen3.8 UD-Q3_K_XL (3): hw_iq3xxs_tile_matches_dot_row, hw_iq4nl_tile_matches_dot_row, hw_iq4xs_tile_matches_dot_row.
  • The dumps made from GLM-5.3-Flash UD-Q2_K_XL (4): hw_q2k_kernel_matches_mirror, hw_q2k_kernel_predicts_ik, hw_iq2xs_kernel_matches_mirror, hw_iq2xs_kernel_predicts_ik.
  • hw_iq4xs_kernel_predicts_ik (1): the synthetic IQ4_XS dump written here holds 0 in all 64 rows, so the test compares against zeros. It does not touch Q4_K, and I did not look further.

@juliankang4

Copy link
Copy Markdown
Collaborator Author

A second run of the gate-qdot follow-up above, now with the real files: the V4.1 Q3_K_M shards (vcruz305/DeepSeek-V4.1-Flash-GGUF at c4a08554) and the Qwen3.8 UD-Q3_K_XL shards (unsloth/Qwen3.8-Flash-Next-GGUF at 766911a6). The sha256 of the V4.1 first shard and of all three UD-Q3_K_XL shards matches the SHA256SUMS of those revisions.

Tree: main 8d8ad179. Since 65990b09, nothing changed in crates/qdot, crates/gguf, crates/threads, tools/ref, tools/box.sh or tools/gate.sh. Machine: an RTX 5090 box (AMD Ryzen 9 9950X); the gate runs on the CPU only.

Inputs. The tests open fixed paths: gguf::v41::PUBLIC for V4.1, and for UD-Q3_K_XL the path in iq_tile_real, which no variable overrides. To match them I added two directory symlinks on this machine, one per model, from the directory name the tests expect to the directory that holds the shards. iq4xs_ref writes real rows only when <shard>.done exists, so I also created an empty .done file by hand beside the second UD-Q3_K_XL shard. The reference files are the first run's, built here from public ik_llama.cpp d4fbf593 and not the maintainers' set, with two dumps added or replaced by the same ik build and build-qdot-ref.sh's flags:

  • q5k_x4_ref on the V4.1 first shard (blk.0.ffn_down_exps.weight, k = 2304), new
  • iq4xs_ref on the real UD-Q3_K_XL rows (blk.2.ffn_gate_exps.weight, k = 2560), in place of the synthetic dump whose 64 results were all 0. Why ik returned zeros on those synthetic blocks I did not check.

The command is the same recipe body as before, once per arm, with no BLOOMERY_V41_MODEL. I ran it a second time with --test-threads=1 so each test's lines print whole. The counts and failures were the same.

Result.

BLOOMERY_QDOT_AVX512=1: test result: FAILED. 73 passed; 10 failed
BLOOMERY_QDOT_AVX512=0: test result: FAILED. 73 passed; 10 failed

Both runs exit with 101 and fail the same 10 tests with the same messages. After normalizing run metadata and timings, the only difference between the two logs is the body name that hw_q4k_avx512_matches_avx2_synthetic prints.

The four checks the PR body named as the ones a maintainer's run checks on real weights now all pass in both arms. The two that waited on the V4.1 shards are the two blk.2.ffn_down_exps.weight lines:

hw_q4k_dot_row_matches_scalar_and_predicts:
  gate 0: 2304 encoder bytes bit-identical to ik's quantize_row_q8_2_x4
  gate A: 1024 rows bit-identical (kernel vs emulator)
  gate B: 64 rows within 1 ULP of ik's mul_mat_qX_K_q8_2_X4_T (on ik's own activations)
hw_q4k_tile_matches_dot_row:
  q4k tile: blk.0.attn_output.weight (k = 2048) on ik's column + seeded: 20480 calls, bit-identical
  q4k tile: blk.2.ffn_down_exps.weight (k = 2304): 18432 calls, bit-identical
hw_lanes_match_dot_row_v41:
  Q4_K lanes: blk.2.ffn_down_exps.weight (k = 2304, 256 rows): 5632 calls, bit-identical

The Q3_K paths, including Gate 4 (hw_scalar_fallback_bit_identical_to_avx2), also the same in both arms:

q3k tile: blk.0.ffn_gate_exps.weight (k = 5120): 18432 row calls, c = 1..=8, bit-identical
q3k tile: blk.1.ffn_gate_exps.weight (k = 2048) on six oracle tokens + seeded: 30720 calls, bit-identical
q3k r8 tile: blk.0.ffn_gate_exps.weight (k = 5120, 256 rows): 6912 group calls, c = 1..=8, bit-identical
q3k r8 tile: blk.1.ffn_gate_exps.weight (k = 2048) on six oracle tokens + seeded: 7920 group calls, bit-identical
gate4 ffn_gate_exps(k=2048) 1024 rows bit-identical (avx2 == scalar)
gate4 attn_kv_b(k=512)     1024 rows bit-identical (avx2 == scalar)

13 of the first run's 23 failures now pass: the ten that needed the V4.1 shards (five of them Q5_K) and the three UD-Q3_K_XL tile tests. No test went from pass to fail.

Still red, the same in both arms:

  • V4-Flash UD-Q3_K_M is not on this machine (5): the iq3xxs and mxfp4 kernel tests.
  • The GLM-5.3-Flash UD-Q2_K_XL dumps are missing (4): the q2k and iq2xs kernel tests.
  • hw_iq4xs_kernel_predicts_ik (1): row 0: ours 2.600824535e-1 vs ik 0.2600823: 5 ULP apart. The band is 1 ULP. It has nothing to do with Q4_K.

hw_iq4xs_kernel_predicts_ik. This test is IQ4_XS gate B only. In both arms the kernel passes IQ4_XS gate A (hw_iq4xs_kernel_matches_mirror, including the 64 real rows) and hw_iq4xs_tile_matches_dot_row. To see whether the ik commit matters, I built public ik e4bae240 with the same flags and dumped the same 64 rows with the same Q8_K column. Against that dump the test passes in both arms, at 0 ULP on all 64 rows. Against the d4fbf593 dump it fails as above. In the two dump files the w rows and the column are byte-identical, and 58 of the 64 results differ, by 1 to 304 ULP.

This is consistent with ik_llama.cpp 3dbc2c9f (#2664, 2026-10-13, "Fix AVX2 GEMM for IQ4_XS, IQ4_KSS, IQ5_KS"). Its parent is e4bae240, and of the four commits up to d4fbf593 it is the only one that changes ggml/src/iqk/iqk_gemm_kquants.cpp. In that diff, the AVX2 DequantizerIQ4XS:

  • reads the signed iq4k_values table instead of the table offset by +128;
  • no longer folds -128.f*d through accum_mins in new_block;
  • goes through multiply_add_avx2 in mul_mat_qX_K_q8_K_T.

I did not build 3dbc2c9f by itself. Our IQ4_XS kernel and tools/ref/iq4xs_ref.cpp follow the pairing from before #2664: the +128 table, the -128 bsums fold and the i16 saturation of maddubs that comes with them.

No action on #86 is asked here. One consequence for the maintainers' own reference: once the reference ik moves past #2664 and the IQ4_XS dump is made again, hw_iq4xs_kernel_predicts_ik goes red on any machine. I will raise that as its own item in the index issue #53, not in this thread.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation host Host crates: qdot, threads, engram, engram-lab, runtime, sampler, levers, decision, vision, refset model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants