Skip to content

Feature/pq2 0m - Enable MMQ path - #451

Open
bestbug456 wants to merge 20 commits into
PrismML-Eng:prismfrom
bestbug456:feature/pq2_0m
Open

bestbug456 wants to merge 20 commits into
PrismML-Eng:prismfrom
bestbug456:feature/pq2_0m

Conversation

@bestbug456

Copy link
Copy Markdown

What

Finalize the work done in #428: enable the MMQ Flash attention for PQ2_0M path.

Why

I think is important to enable the MMQ path when possible, I did also metion in the previous PR that I was working on, so here we are

Additional information

While working on this one I realize that when head_dim < 128 the math was wrong and I'm not sure that can be fixed, therefore I just add a unsupported warning for those one, fallback to f16. From my understanding the head_dim 64 is something more used for older model. Newer one usually came with head_dim of 128 and 256, where is also easier for us to work. I also add the support to coopmat2 that is nvidia only, making follow the coopmat1. While I do not have a NVIDIA card to test it I think is reasonable safe as change.

Requirements

bestbug456 and others added 20 commits November 20, 2026 14:56
New quant type GGML_TYPE_PQ2_0M = 144, KV-cache only. Model weights keep
existing PQ2_0 (matmul) unchanged.

Format: block_pq2_0m { fp16 d; fp16 m; uint8_t qs[32]; }  (24 B / 128)
  Quantize: d = (max-min)/3, m = min, q = clamp(round((w-min)/d), 0, 3)
  Dequant:  y = m + q*d   (levels {min, min+d, min+2d, min+3d=max})
  Worst-case error: d/2 = (max-min)/6

MMQ correction (Bk=0 form): Qf.ds.y * m

Files:
  ggml:   type enum, struct, quantize/dequant ref impl, type-traits row
  common: arg.cpp allowed KV type list
  shaders: types.glsl, ggml_type_ids.glsl, copy_to_quant.comp,
           fa_types.glsl, flash_attn_mmq_funcs.glsl,
           flash_attn_dequant.glsl, dequant_funcs.glsl,
           dequant_pq2_0m.comp (new), vulkan-shaders-gen.cpp
  backend: ggml-vulkan.cpp (pipelines, SET_ROWS, MMQ gate, fa_kv_ok,
           supports_op SET_ROWS case)
  kv:     llama-kv-cache.cpp allowed type + bias warning

Validation (Vulkan/RX 9070):
  CPU codec round-trip: PASS (max_err 0.3267 < bound 0.3325)
  GPU KLD: 0.05 (mix K=q4_0+bias / V=pq2_0m)
         0.06 (KV pq2_0m)
  vs PQ2_0 codec floor 0.258 (no-bias K+V) — ~4x improvement
PQ2_0M was a valid KV-cache type in llama-server (added in the
PQ2_0M commit) but llama-bench's ggml_type_from_name did not know
the string, so -ctk/-ctv pq2_0m failed with 'invalid parameter'.

Add the pq2_0m -> GGML_TYPE_PQ2_0M mapping so bench can select the
new range-scale KV type.
The K shmem-staging path indexed the packed scale with a_offset + buf_ib/4
in the wrong field; index by a_offset + global_ib instead. Also correct the
PQ2_0M dequant formula comments from y = m + (q-1) * d to y = m + q * d
(PQ2_0M uses q in {0..3} directly, unlike PQ2_0 which uses (q-1)).
…PU/HIP)

Add PQ2_0M support to the flash-attention vector kernel and the GPU
set_rows write path so --cache-type-k pq2_0m / --cache-type-v pq2_0m
work end-to-end on AMD (HIP/ROCm) and NVIDIA.

- fatnn-common.cuh: vec_dot_fattn_vec_KQ_pq2_0m + dequantize_V_pq2_0m
  and dispatch registration (in-kernel K/V dequant, no f16 pre-pass).
- dequantize.cuh: dequantize_pq2_0m __device__ kernel.
- convert.cu: 6 new GGML_TYPE_PQ2_0M to_*_f32/f16/bf16 cases.
- cpy-utils.cuh: quantize_f32_pq2_0m_block (range-scale d=(max-min)/3,
  m=min, 2-bit q packing matching quantize_row_pq2_0m_ref).
- set-rows.cu: block_pq2_0m dispatch in set_rows_cuda_quant.
- ggml-cuda.cu: pq2_0m in SET_ROWS op whitelist + fattn kv gate.
- fatnn.cu: FATTN_VEC_CASES_ALL_D entries.
- common.cmake: FA_TYPES += pq2_0m.
- template-instances/: 15 new fatnn-vec-instance-*.cu (fatnn- prefix).

Verified: build clean (exit 0), llama-server loads and serves with
-ctk pq2_0m -ctv pq2_0m, no SET_ROWS abort, 47.34 tok/s eval.
dequantize_V_pq2_0m read only 2 of 4 two-bit codes per byte and
broadcast each via __half2half2 / repeated shift, producing
[c0,c0,c1,c1] instead of [c0,c1,c2,c3] — the missing c2,c3
inflated KV-cache KLD (1.6) vs the Vulkan reference (0.05).

Now extracts all four codes explicitly and writes them to dst[0..3],
matching dequant_pq2_0m.comp (m + q*d, q in {0..3}).
static_assert(std::is_same<T, void>, "bad type") is a type template
specialization, not a bool constant expression -- invalid under static_assert
and a parse error. Add the _v variable template so the dead else-branch
asserts a bool. Required for the vec-kernel build (GPU/HIP).
Adds the missing CPU-side dot product for the PQ2_0M KV-cache quant type so
CPU flash-attention with --cache-type-v pq2_0m and --cache-type-k q4_0 stops
dereferencing a NULL vec_dot (null pointer segfault at threadpool init).

Files:
  quants.h          declarations
  quants.c          quantize_row_pq2_0m + ggml_vec_dot_pq2_0m_q8_K_generic
  ggml-cpu.c       type_traits_cpu[GGML_TYPE_PQ2_0M] entry
  arch-fallback.h  per-arch #define alias (8 arch sections incl. x86_64/aarch64)
Add GGML_TYPE_PQ2_0M to:
- all_types[] (drives SET_ROWS and other all_types-driven op tests)
- the FLASH_ATTN_EXT nested type_KV sweep list
- a standalone ARC-LAB decode-kernel block mirroring the q4_0 block
  (Bonsai 27B shape: D 256, 4 KV heads x GQA 6, kv 256..16384, nb
  1..8, plus a 1024/1 no-mask case)

So CUDA and Vulkan FA kernels are checked against CPU for PQ2_0M.

Signed-off-by: bestbug456 <6997001+bestbug456@users.noreply.github.com>
The test-backend-ops addition of PQ2_0M made init_tensor_uniform call
ggml_quantize_chunk on PQ2_0M tensors, but the switch had no case for it,
so the default arm left result=0 and the final assert fired (SIGABRT in
release builds). Add the missing wrapper:

- ggml-quants.h: declare quantize_pq2_0m (mirrors quantize_pq2_0)
- ggml-quants.c: implement quantize_pq2_0m, calling quantize_row_pq2_0m_ref
  per row (same shape as quantize_pq2_0)
- ggml.c: add case GGML_TYPE_PQ2_0M in ggml_quantize_chunk

This is a CPU-side quantize fix; it is separate from the GPU FA kernel
correctness work.

Signed-off-by: bestbug456 <6997001+bestbug456@users.noreply.github.com>
In flash_attn.comp (SHMEM block8 fast path) the K-quants for PQ2_0M were
unpacked with nibble masks (& 0x0F0F0F0F, >> 4), which is the Q4_0 layout.
PQ2_0M stores raw 0..3 codes in each byte (one byte per quad of 4 codes),
so no nibble unpack is needed -- the current code zeroed half the codes and
gave a wrong KQ dot.

- flash_attn.comp: in the block8 fast path, take PQ2_0M out of the nibble
  unpack and copy raw bytes directly into k_quants[0..7].
- flash_attn_mmq_funcs.glsl: get_k_qs_block8 (non-shmem path) had no PQ2_0M
  case, so it returned zeros. Add a PQ2_0M case that reads two bytes per
  quad and packs the raw codes into r.qs[d] and r.qs[d+4].

Signed-off-by: bestbug456 <6997001+bestbug456@users.noreply.github.com>
The hsk=256 block8_fast path (get_k_qs_block8) read the wrong bytes of the
packed PQ2_0M K buffer. Each sub-block starts at a different byte offset inside
the 32-byte block, so the quad byte offset must be byte_offset + d (and
+ d + 4 for the second quad), not just d / d + 4.

- get_k_qs_block8: new byte_offset parameter, call site passes iqs/4
- k_block_to_shmem: new block parameter (dead code on AMD, SHMEM_STAGING=0)
- Q4_0/Q5_0/Q5_1/Q4_1/Q5_1 sub-blocks now use bi = d*2 / d to match the
  per-sub-block layout

This is the hsk=256 fix (ERR 0.27 -> 0.12); the generic hsk=64 path is a
separate, still-open bug.
get_k_qs_block8 read all 8 bytes from the same block (byte_offset + d)
even when the 8-byte span crossed a block boundary. When the span
crosses, each byte must come from its own block (ib + byte/32 at
byte % 32), matching the generic get_k_qs path (ib + elem/128).

K-only asymmetric (K=pq2_0m/V=f16, hsk=256, block8 path) drops from
0.1875 to ~0.12 on RX 9070. V-side (K=f16/V=pq2_0m) unaffected.

On top of commit 1a07825 (byte_offset + d byte-mapping fix).
Slot 144 is taken by the unmerged Q1_0 group-64 type (feat/pq1_0-g64);
reusing it would silently misread one of the two types. Move PQ2_0M to the
next free slot so both can coexist.

- ggml.h: GGML_TYPE_PQ2_0M 144 -> 145, GGML_TYPE_COUNT 145 -> 146
- ggml_type_ids.glsl: mirror the new id (hand-maintained, must match ggml.h)

All other code references the type by symbol, so nothing else changes.
…d_dim

Replace the hard-fail block-alignment gate in llama_context with a warning
and a drop to GGML_TYPE_F16. This prevents misaligned head dimensions
(e.g. 64/72 with PQ2_0M block 128) from aborting context creation.
Aligned models (head_dim % 128 == 0) are unaffected.
Co-authored-by: GaelicThunder <48930397+GaelicThunder@users.noreply.github.com>
Co-authored-by: GaelicThunder <48930397+GaelicThunder@users.noreply.github.com>
@bestbug456

Copy link
Copy Markdown
Author

Hello @bri-prism! I noticed that our previous PR was merged, I'm really happy to be part of this project! This PR wraps up what I had originally planned, along with a couple of extra fixes I found along the way. Hope this helps! 

Looking ahead, I think this work would be really valuable upstream as well. I started looking into how to port it over and realized your quant work isn't in upstream yet. While I saw that you're actively working on bringing PTQ1_0 upstream, I didn't see a PR for PQ2_0. 

So I have two questions for you: 

  1. Are there plans to bring PQ2_0 upstream as well?
  2. If so, I'd love to help kick off the discussion (at least by opening a Discussion or RFC issue on upstream). Between PQ2_0 for model weights and PQ2_0M for the KV cache, I think we can significantly push forward the accessibility of local models. On this fork now it's already possible to run a full-context 27B Bonsai 2 model with MTP on Vulkan under the 12 GB VRAM threshold. Would you be okay with me opening a discussion upstream to showcase what we've built?

Let me know! :)

@bri-prism bri-prism left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for following up on #428. The non-staged MMQ K path looks right to me: the byte offset in get_k_qs_block8, the 2-bit spread in get_k_qs, and the (d, m) correction term all line up with the Q8 ordering.

The shared-memory staging path has two problems, though, and NVIDIA takes that path for head dims under 256 (and for every decode step, since n_rows == 1 forces the scalar shader):

  1. The staging loop in flash_attn.comp walks 32-element sub-blocks (global_ib = kcol * k_stride + block with block < HSK/32), but for PQ2_0M a K block is 128 elements. The new k_block_to_shmem case always reads raw bytes 0-7 of global_ib, so sub-blocks 1-3 come from the next block instead of from bytes 8-31 of the current one. The index should be block / 4, with a raw byte offset of 8 * (block % 4).
  2. The packing doesn't match what the consumers expect. get_k_qs_shmem and the staged block8 read assume int d holds elements 4d..4d+3 in the low nibbles and 16+4d..16+4d+3 in the high nibbles (the Q4 layout). The current code puts elements 0, 2, 4, 6 in the low nibbles of int 0, so they get multiplied with Q elements 0, 1, 2, 3. Building int d from raw byte 8s+d (low) and 8s+4+d (high) with the same spread you use in get_k_qs_block8 should fix it.

The existing FLASH_ATTN_EXT case at D=128 with a PQ2_0M K cache should show this on any NVIDIA Vulkan device with integer dot. If you can't test there, gating the PQ2_0M MMQ path off when shmem staging is enabled would be a safe interim.

On the llama-context change: falling back to F16 for every quantized cache type and every backend is a bigger behavior change than this PR needs, and it hides a large memory increase behind a warning. For PQ2_0M the head-dim case was already a configuration error (the type needs ne0 % 128 == 0), so I'd prefer to keep the hard error here and discuss a fallback separately.

Could you also add the test-backend-ops FLASH_ATTN_EXT results for the device you tested on, a quick perplexity or KLD check with the MMQ path on and off, and a llama-bench comparison against the dequant path? That will help us judge whether the extra unpacking pays off. Please squash as well, since the branch still carries the #428 commits.

@bri-prism bri-prism left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for following up on #428! I went through the shader changes against the PQ2_0M layout (y = m + q*d, four consecutive codes per byte, 128 per block).

The direct read path looks right to me. get_k_qs, get_k_qs_block8 with the new byte_off, get_k_scale and the k_dot_correction term (same shape as Q4_1) all line up with how the Q8 side expects elements 4k..4k+3 in int k.

I think the shared-memory staging path (SHMEM_STAGING != 0) is off in two places:

  1. Block addressing. In the MMQ staging loop, block counts 32-element sub-blocks (HSK / 32 per row), but global_ib = kcol * k_stride + block is then used as a PQ2_0M block index, which is 128 elements. Also, k_block_to_shmem reads qs[iqs * 2] and qs[iqs * 2 + 1] with iqs < 4, so it only ever touches bytes 0-7, the first 32 elements of each 128-element block. I think it needs global_ib / 4 for the block and a (block % 4) * 8 byte offset.
  2. Element order. The new k_block_to_shmem case packs codes 0,1 into byte 0, codes 2,3 into byte 1, and so on, so the low nibbles of the int are codes 0,2,4,6. The block8 shared-memory reader treats low nibbles as consecutive elements (like Q4_0, low nibbles = elements 4d..4d+3 of the first half, high nibbles = the second half). So the order would need to be codes 0-3 in the low nibbles of qs[0] and codes 16-19 in the high nibbles, mirroring Q4_0.

These might also explain the head_dim < 128 trouble you saw.

Could you run test-backend-ops -b Vulkan0 -o FLASH_ATTN_EXT -p type_KV=pq2_0m on a device that reports int dot: 1, ideally with a shape that takes the staging path, and paste the output? I can't run the MMQ path here: MoltenVK on Apple reports int dot: 0 and runs no FLASH_ATTN_EXT cases.

On the llama-context.cpp change: turning the error into a silent fallback to F16 changes behavior for every quantized K/V type, not just PQ2_0M, and a user who asked for a quantized cache would get F16 with only a warning. Could you split it out of this PR? I'd rather keep the error, or limit the fallback to the case this PR needs.

The branch is also 78 commits behind prism, so a rebase would help before merge.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants