Skip to content

[executorch][llm-cache] Add per-layer quantized KV storage config - #26079

Open
digantdesai wants to merge 2 commits into
mainfrom
gh/digantdesai/353/head
Open

digantdesai wants to merge 2 commits into
mainfrom
gh/digantdesai/353/head

Conversation

@digantdesai

@digantdesai digantdesai commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Add CacheConfig::layer_storage (one KVStorage per layer; empty keeps
unquantized storage) and kv_quant_impl (auto or emulated).
kv_storage_traits() gives each type's name, group size and group bytes, and
kv_codec.h holds the reference quantize/dequantize for Q4_GS32_ZPF16 (4-bit
codes, FP16 scale and FP16 zero point in scale units per group of 32) and
Q4_1 (ggml block_q4_1). full_attention_storage() selects window-0 layers.
Every cache backend refuses quantized storage until it implements it.

The storage encoding is a runtime choice, independent of kv_dtype, so the
same exported program runs with or without a quantized KV cache.

Authored with assistance from Claude and Codex.

[ghstack-poisoned]
@digantdesai

digantdesai commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Copilot AI balanced review requested due to automatic review settings December 4, 2026 20:11
@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/26079

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

❌ 7 Pending, 2 Unclassified Failures

As of commit bf5341e with merge base 4ce60cb (image):

UNCLASSIFIED FAILURES - DrCI could not classify the following jobs because the workflow did not run on the merge base. The failures may be pre-existing on trunk or introduced by this PR:

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

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

Finite FP32 values in a narrow range, such as 1.0–1.0001, can overflow the stored FP16 zero point and decode the entire group as infinity. Separately, encoding under FE_UPWARD violates the reference ties-to-even behavior; the default empty storage configuration makes storage_for(0) report FP32 while uses(FP32) returns false; and direct MLXSequenceCache construction accepts storage-vector lengths that violate the per-layer contract and are rejected by CacheFactory::build.

4 open issues
What changed in this PR

Adds per-layer KV storage configuration and reference quantization codecs to ExecuTorch’s shared LLM cache API, independently of the model’s floating-point dtype.

Changes:

  • Adds storage selection, quantization mode, and per-layer validation.
  • Implements Q4_GS32_ZPF16 and Q4_1 codecs with layout and rounding tests.
  • Makes existing cache backends reject unsupported quantized storage.
File Description
extension/​llm/​cache/​test/​cache_test.cpp Tests storage configuration and codec behavior.
extension/​llm/​cache/​targets.bzl Exports the codec header and scalar-type dependency.
extension/​llm/​cache/​kv_codec.h Adds reference quantization and dequantization.
extension/​llm/​cache/​cache.h Defines storage options, validation, and selection helpers.
backends/​native/​runtime/​engine/​ggml/​GgmlCache.cpp Rejects quantized storage in ggml caches.
backends/​mlx/​runtime/​MLXSequenceCache.h Rejects quantized storage in MLX sequence caches.
backends/​mlx/​runtime/​MLXCellCache.h Rejects quantized storage in MLX cell caches.
backends/​cuda/​runtime/​cuda_kv_cache.cpp Rejects quantized storage in CUDA cache factories.

Review effort: Balanced

Comment thread extension/llm/cache/kv_codec.h Resolved
@@ -851,6 +851,9 @@ class MLXSequenceCache final : public cache::Cache,
: capacity_(cfg.capacity) {
using sequence::detail::require;
require(cache::valid(cfg), "sequence: invalid config");
Comment thread extension/llm/cache/cache.h Resolved
Comment on lines +98 to +100
const float c = std::nearbyint(v[j + k] / scale - zp);
codes[k] = static_cast<uint8_t>(
c >= 15.0f ? 15 : (c > 0.0f ? static_cast<int>(c) : 0));
@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 4m 35s —— View job


One change is needed before merge: the Q4_GS32_ZPF16 reference codec stores its zero point as FP16 in scale units, which overflows to inf for groups with a small spread and a large offset, so the whole group decodes to inf. The other findings are minor API-naming, consistency and test-coverage issues.

Detailed review

PR Review: #26079

Summary

This PR adds per-layer KVStorage selection to CacheConfig, reference Q4_GS32_ZPF16 and Q4_1 codecs in kv_codec.h, and refusals for quantized storage in the CUDA, MLX and ggml cache builders. The Q4_GS32_ZPF16 format has a numerical defect, and because this header is the oracle the follow-up packed kernels will be checked against, it should be fixed before they build on it. The rest are minor.

Code Quality

  • extension/llm/cache/kv_codec.h:91: the zero point overflows FP16 (major; all three reviewers, also raised by Copilot).
    • Cause: zp = fp16(lo / scale) is roughly 15·lo/span, so any group with |lo| > ~4367·span stores zp = ±inf. Every code then clamps to 0, and decode returns (0 + inf) * scale = inf for all 32 values, which turns into NaN in softmax.
    • Example inputs: 31 × 1000.0f plus one 1000.001f, or a group of 1.0f with one nextafterf(1.0f, 2). The span = |hi| fallback only covers span == 0.
    • Below overflow: once zp is above 2048, FP16 rounding of zp alone shifts the result by whole quantization steps. With FP16 inputs {2048, 2050}, zp ≈ 15364 rounds to 15360, and the top value would need code 19, so it is clamped to 15.
    • Contrast: Q4_1 handles the same rows because it stores the minimum itself, not the minimum in scale units.
    • Fix: store an FP16 bias, as Q4_1 and MLX do, or bound |zp| by raising the scale. Do this now, while Q4_GS32_ZPF16 = 1 has no users, because the enum is append-only and the format can't change after follow-ups ship.
    • Test: add a regression test for a near-constant group with an offset.
  • kv_codec.h:118: Q4_GS32_ZPF16 decode always rounds to BF16, but Q4_1 decodes in FP32 (:150). Emulated mode stores the result in kv_dtype (cache.h:193-195). With kv_dtype set to Half or Float, the value is rounded twice, and an FP16 or FP32 packed kernel can't match the reference bit for bit. Either tie this rounding to kv_dtype or write down why BF16 is fixed.
  • kv_codec.h:76-81: NaN handling depends on where the NaN is. lo and hi start at v[0], and std::min(NaN, x) returns NaN. A NaN in v[0] therefore poisons scale, zp and the whole group, while a NaN anywhere else is skipped. Q4_1 starts from ±FLT_MAX and skips NaN at every position, so the two reference codecs disagree.
  • backends/mlx/runtime/MLXSequenceCache.h:853: only valid(cfg) is checked, not valid(geometry, cfg).
    • An all-FP32 layer_storage of the wrong length is accepted here.
    • CUDA and ggml reject the same config, and any later storage_for(i) call on it throws std::out_of_range.
  • kv_codec.h:37, cache.h:220: new exceptions in a library that otherwise reports errors through ET_CHECK/Error.
    • encode_row/decode_row throw std::invalid_argument, and storage_for uses .at().
    • extension/llm/cache/README.md:186-191 lists the files and whether each is "neutral", but has no entry for kv_codec.h. That header depends on ET Half/BFloat16 and throws, so a -fno-exceptions translation unit can't include it.
  • backends/cuda/runtime/cuda_kv_cache.cpp:1365,1390,1425: CUDA's refusal doesn't say quantization was the cause.
    • It is folded into the existing condition, so the user sees "invalid cache geometry or config" and CacheFactory reports Internal "builder returned null".
    • MLX and ggml throw a specific message instead.
    • A separate log line on the CUDA path would make this obvious.
  • Small cleanups:
    • CacheConfig::uses(KVStorage) (cache.h:223) has no callers; add it in the PR that needs it.
    • In encoded_row_bytes (kv_codec.h:34), storage == KVStorage::FP32 || is already covered by the next clause.

API Design

  • cache.h:172: KVStorage::FP32 means "unquantized, stored as kv_dtype". kv_dtype is usually BF16, and CUDA defaults to BF16, so {KVStorage::FP32, ...} reads as a request for FP32 storage. Rename it to something like Float/Native/None while that is still cheap; the enum is append-only.
  • cache.h:213-217, 284-287: CacheConfig now depends on the geometry.
    • Trigger: examples/models/muse-glimmer/runtime/mlx_executor.cpp:322 copies the target config (auto dc = cache_config;) and uses it for the DFlash draft geometry, which has a different layer count.
    • Result: once a follow-up fills layer_storage for the target, valid(dg, dc) fails on the size check and the runner returns InvalidProgram with no message.
    • Fix: define who owns per-cache storage, or clear or rebuild it at copy sites like this one.
  • cache.h:190-196: KVQuantImpl has no "packed or refuse" option. Auto silently falls back to Emulated, which by its own comment saves no memory. A caller who sized capacity expecting 4-bit KV can't detect the fallback. This is low priority since the API is ET_EXPERIMENTAL.

Testing

  • extension/llm/cache/test/cache_test.cpp:148,190: both codec tests use kDim = 32, a single group.
    • The Q4_GS32_ZPF16 layout (all code bytes first, then a scale/zp pair per group at pairs + 4*g) and the Q4_1 b * 20 block stride are never exercised.
    • A per-group interleaved layout would produce identical bytes at one group, so it would pass.
    • Add a head_dim = 64 case that checks byte offsets.
  • Edge cases with no test:
    • a group with a near-constant value plus an offset (the overflow above);
    • a NaN in the first position of a group;
    • an all-zero group or a -0 minimum (the lo += 0.0f path and the 2^-24 scale floor);
    • a positive constant group (the span = |hi| path).
  • Backend refusals: no test checks that any builder refuses quantized layer_storage while accepting an all-FP32 layer_storage. The ggml and MLX checks run on the host and are cheap to cover.

Recommendation

Request Changes. The FP16 zero-point overflow is a defect in a reference format that is meant to be frozen, and fixing it later means a new enum value. The rest can be handled in this PR or a follow-up.

[ghstack-poisoned]

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

Direct construction of MLXSequenceCache and MLXBatchedCache accepts an all-FP32 layer_storage list with the wrong entry count, violating the one-entry-per-layer contract enforced by CacheFactory. Separately, codec encode/decode tests use only 32-value inputs, leaving multi-group offsets and the distinct Q4_GS32_ZPF16 and Q4_1 layouts unverified.

3 open issues
2 resolved since last review

Review effort: Balanced

}
}

// Q4_GS32_ZPF16 rows: all head_dim / 2 code bytes first (value 2m in the low

This branch was previously deployed

1 inactive deployment
cadence — bf5341e9 Deployed Dec 4, 2026 by digantdesai via hifi-op-test / hifi4 #42436
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