Skip to content

[executorch][native-ggml] Store off-graph KV as Q4_1, packed or emulated - #26081

Open
digantdesai wants to merge 2 commits into
gh/digantdesai/354/headfrom
gh/digantdesai/355/head
Open

digantdesai wants to merge 2 commits into
gh/digantdesai/354/headfrom
gh/digantdesai/355/head

Conversation

@digantdesai

@digantdesai digantdesai commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

GgmlKvPool now takes one storage type per layer. With kv_quant_impl = auto a
Q4_1 layer stores its blocks: set_rows quantizes rows once, and flash
attention reads the blocks directly on a GPU and on the CPU below its tiled
kernel's 64 query rows, converting them to F32 otherwise. With
kv_quant_impl = emulated, rows are rounded through Q4_1 and stored in
kv_dtype. Q4_GS32_ZPF16 is refused at cache creation.

This gives the ggml engine an opt-in compressed KV cache for full-attention
layers, matching the reference codec, with floating storage unchanged.

Authored with assistance from Claude and Codex.

[ghstack-poisoned]
@digantdesai

digantdesai commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor Author

@pytorch-bot

pytorch-bot Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/26081

Note: Links to docs will display an error until the docs builds have been completed.

⏳ No Failures, 3 Pending

As of commit b885cc2 with merge base 4ce60cb (image):
💚 Looks good so far! There are no failures yet. 💚

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Dec 4, 2026
@digantdesai
digantdesai added this pull request to stack #26083 December 4, 2026 20:12
@Gasoonjia

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Claude finished @Gasoonjia's task in 3m 14s —— View job


Summary: There are no CPU correctness bugs. The main concerns are that KVQuantImpl::Auto refuses at compile time where its documented contract says to fall back to Emulated, that the packed Q4_1 flash-attention path is not checked against GPU backend support, and that the packed test cannot tell packed storage from floating storage. Needs Discussion.

Detailed review

PR Review: #26081

Summary

The PR adds per-layer KV storage types to GgmlKvPool. Q4_1 storage is either packed (set_rows quantizes rows, flash attention reads the blocks) or emulated (rows are rounded through Q4_1 and stored as floats).

Two problems need attention:

  • Auto breaks its documented contract when the engine has no packed path.
  • Packed Q4_1 support is only checked on CPU, so GPU behaviour is unknown.

Several test gaps make packed-path regressions hard to catch. All 7 changed files were reviewed.

API Design

  • GgmlCache.cpp:58-61 and GgmlLowerAttention.cpp:691-701: KVQuantImpl::Auto refuses where its contract says it should emulate.
    • extension/llm/cache/cache.h:191 defines Auto as "Packed when the byte layer has a packed path for the type, else Emulated."
    • layer_types() resolves packed versus emulated when the cache is created, and it never sees the engine options. So a cache with layer_storage={Q4_1} and Auto, used with flash_attention=Off (or f32_attention_kv_for_testing=true), throws at compile("forward"). That engine has no packed path, so per the contract it should have fallen back to Emulated.
    • The new test OffGraphPackedQ4_1RefusesUnsupportedAttention locks in the throw.
    • The error also arrives late: the cache is already built and installed before the conflict surfaces.
    • Fix: either make Auto fall back to Emulated in that case, or narrow the Auto wording in cache.h so it says the engine may refuse.
    • (All three reviewers flagged this.)

Infrastructure

  • GgmlLowerAttention.cpp:691-701: packed Q4_1 is not checked against the GPU backend's flash-attention support. (Suspected; ggml is not vendored here, so this was not verified.)
    • The only guards are flash_attention_ and f32_attention_kv_.
    • The GPU flash-attention probe in GgmlExecutor.cpp (around line 1003) only tests F16 K/V.
    • Stock ggml-cuda builds without GGML_CUDA_FA_ALL_QUANTS reject Q4_1/Q4_1 flash_attn_ext. With op_offload on, the scheduler would then likely run attention on CPU and copy the entire Q4_1 cache off the device every step, with no error. Or it fails.
    • The same doubt applies to the emulated path's Q4_1→F32 ggml_cpy at GgmlLowerAttention.cpp:748-755 on non-CPU backends.
    • Fix: probe ggml_backend_dev_supports_op for a Q4_1 flash-attention node, the way the F16 probe works, and refuse (or emulate under Auto) when it is unsupported.
    • The comment at GgmlEngine.h:116 ("CUDA and HIP flash attention reads F16 keys and values either way") is no longer true for packed storage.
    • (All three reviewers flagged this.)

Testing

  • test_ggml_engine.cpp:3329-3363: the packed half of OffGraphQ4_1StorageMatchesTheCodecReference does not prove the storage is packed.
    • The tolerance is 1e-1 and nothing asserts the storage type.
    • If Auto regressed to F32/F16 storage, the error against the Q4_1-rounded reference would probably still be under 0.1 (softmax averages out the per-element rounding), so the test would still pass.
    • Fix: assert k->type == GGML_TYPE_Q4_1 on the pool's layer tensors, and/or tighten the bound. Also consider comparing packed and emulated outputs directly, since the PR claims they match.
  • Paths with no test coverage:
    • Mixed per-layer storage, e.g. {FP32, Q4_1}. This is the reason for having per-layer types.
    • Q4_1 on a ring/windowed layer. layer_types accepts it, even though the description says "full-attention layers". Either restrict it or test it.
    • Q4_1 through GgmlCellCache / the batched kinds. Only the Q4_GS32_ZPF16 refusal covers them.
    • Emulated Q4_1 with kv_dtype=Half (round through Q4_1, then F16).
    • Emulated Q4_1 with flash_attention=Off or f32_attention_kv_for_testing being accepted. GgmlEngine.h:119-120 documents this behaviour.

Code Quality

  • GgmlLowerAttention.cpp:740-756: dead work in write. When emulate is set, the source computed from the skip_f16_cast / as_f32 ternary is discarded right away, and as_f32(step) is called a second time. Picking source in an if/else would avoid the unused node.
  • GgmlCache.cpp:118-127: the head_dim block check is unreachable. checked() → cache::valid() (cache.h:289-293) already rejects head_dim % storage_group_size(...) != 0, and it runs before every pool is constructed.
  • GgmlCache.h:34-47 and GgmlGraphBuilder.h:113-116: emulate is stored in three structs. The copies are GgmlKvPool::LayerType, GgmlKvPool::Layer and OffGraphCacheBinding::Layer. Layer could hold a LayerType (or read types_[i]) instead of a parallel field.
  • GgmlLowerAttention.cpp:696-700: the f32_attention_kv_for_testing refusal over packed storage isn't needed for correctness. attention_kv() only casts F32 tensors, so Q4_1 K/V would pass through unchanged. If the refusal is intentional, say so in GgmlEngine.h:119-120. Otherwise drop it.

Recommendation

Needs Discussion. Before landing, settle the Auto contract mismatch and decide how packed Q4_1 should behave on CUDA/HIP (probe and refuse, or fall back). Strengthening the packed test so it asserts the storage type would make either decision safe to keep.

[ghstack-poisoned]
Copilot AI balanced review requested due to automatic review settings December 4, 2026 23:22
digantdesai added a commit that referenced this pull request Dec 4, 2026
GgmlKvPool now takes one storage type per layer. With kv_quant_impl = auto a
Q4_1 layer stores its blocks: set_rows quantizes rows once, and flash
attention reads the blocks directly on a GPU and on the CPU below its tiled
kernel's 64 query rows, converting them to F32 otherwise. With
kv_quant_impl = emulated, rows are rounded through Q4_1 and stored in
kv_dtype. Q4_GS32_ZPF16 is refused at cache creation.

This gives the ggml engine an opt-in compressed KV cache for full-attention
layers, matching the reference codec, with floating storage unchanged.

Authored with assistance from Claude and Codex.

ghstack-source-id: 453b2f8
ghstack-comment-id: 7422958303
Pull-Request: #26081

Copilot AI 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.

🟡 Changes recommended

Tests do not cover preservation of populated Q4_1 storage across cache growth or GPU-suite validation of packed attention and emulated casts.

2 open issues
What changed in this PR

Adds opt-in, per-layer Q4_1 KV-cache storage to the native ggml backend while preserving floating storage.

Changes:

  • Supports packed Q4_1 and emulated quantization.
  • Converts packed caches to F32 when required by the attention mode.
  • Adds codec-reference accuracy tests and rejection tests for unsupported storage.
File Description
backends/​native/​test/​runtime/​ggml/​test_ggml_engine.cpp Adds quantized-cache and codec compatibility tests.
backends/​native/​runtime/​engine/​ggml/​GgmlLowerAttention.cpp Implements quantized writes and attention conversions.
backends/​native/​runtime/​engine/​ggml/​GgmlGraphBuilder.h Adds emulation metadata to cache bindings.
backends/​native/​runtime/​engine/​ggml/​GgmlExecutor.cpp Forwards per-layer emulation settings.
backends/​native/​runtime/​engine/​ggml/​GgmlEngine.h Documents quantized-cache option behavior.
backends/​native/​runtime/​engine/​ggml/​GgmlCache.h Defines per-layer storage types.
backends/​native/​runtime/​engine/​ggml/​GgmlCache.cpp Selects, validates, and allocates layer storage.

Review effort: Balanced

*t = ggml_new_tensor_3d(
next->context.get(),
type_,
types_[i].storage,
kind,
{kv::KVStorage::Q4_1},
c.impl);
auto host = GgmlEngineHost::create(c.options);

This branch was previously deployed

1 inactive deployment
cadence — b885cc21 Deployed Dec 4, 2026 by digantdesai via hifi-op-test / hifi4 #42435
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants