Skip to content

[Native] Run GGUF Q5_K weights in the ggml engine - #24948

Closed
metascroy wants to merge 12 commits into
offgraph-kv-gguf-layersfrom
offgraph-kv-ggml-q5k
Closed

metascroy wants to merge 12 commits into
offgraph-kv-gguf-layersfrom
offgraph-kv-ggml-q5k

Conversation

@metascroy

@metascroy metascroy commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Stack

Off-graph KV cache for the native ggml engine, through serving Muse Glimmer on it. Review bottom-up; each PR builds and passes its tests on its own.

Summary

The ggml engine took packed GGUF weights only as Q4_K or Q6_K, but K-quant mixes such as Q4_K_M store some tensors as Q5_K; Muse Glimmer's LM head is one. Export already carries any GGUF type as a gguf:<type> PackedQuant, so only the engine needed it. A table of K-quant codecs (ggml type and block bytes) replaces the Q4_K/Q6_K conditionals, with Q5_K added.

Test plan

New engine test: a packed Q5_K linear with every fifth bit set computes the expected dot product, on CPU and on Metal.


Authored with Claude Code.

The HF attention function that routes attention through
kvcache::update_and_attend is backend-neutral: it only emits the cache op.
Move it from backends/mlx/llm into extension/llm/cache so other backends can
export with an off-graph KV cache. register_mlx_offgraph_attention and the
other names MLX exporters import are unchanged.
@pytorch-bot

pytorch-bot Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 138 New Failures, 7 Unrelated Failures, 10 Unclassified Failures

As of commit acd0758 with merge base c7f7931 (image):

NEW FAILURES - The following jobs have failed:

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:

FLAKY - The following jobs failed but were likely due to flakiness present on trunk:

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 Nov 12, 2026
Add --offgraph_cache to the native HF LLM export. Attention routes through
kvcache::update_and_attend, so the exported graph holds no KV cache buffers;
the runtime supplies the cache. The native partitioner accepts the op, and
golden samples come from the reference sequence cache.

Also add the missing __main__ guard, without which python -m on the export
script silently did nothing.
EngineHost::create_context_with_options takes named string options for one
context, such as the registry key of a KV cache the caller installed. The
default implementation rejects any option, so engines opt in to the options
they understand; create_context and its callers are unchanged.
The ggml engine now runs graphs exported with an off-graph KV cache.

- GgmlSequenceCache is the ggml SequenceCache: the neutral sequence
  controller plus K/V storage per layer in the engine's backend buffer.
  Storage starts at the config's initial_capacity rows and doubles toward
  capacity, so short sequences do not pay for the full context.
- register_ggml_cache_builders() registers it with the CacheFactory under
  backend id NativeGgml, kind single.
- A context created with the llm_cache_registry_key option resolves the cache
  from the CacheRegistry.
- update_and_attend lowers to ggml_set_rows into the cache and
  flash_attn_ext over the filled prefix, with per-step rows and causal mask
  uploads. Before each call the executor checks positions, grows the cache,
  rebinds storage (dropping cached graphs on a regrow), and plans every
  layer; it commits after the call succeeds.

Flat layers, batch 1, and fp32/fp16 storage only.
When a method calls kvcache::update_and_attend, the runner derives the cache
geometry from the graph, builds the engine's single-sequence cache through
the CacheFactory, publishes it with an InstallGuard, and passes its registry
key to the engine context. New flags --kv_capacity, --kv_dtype, and
--kv_initial_capacity size the cache. Sample verification clears the cache
between samples instead of recreating the context. run_hf_llm_ggml registers
the ggml cache builders.
Prompts longer than the method's token input are now prefilled in chunks
instead of rejected, for both in-graph and off-graph packages.

--interactive chats on stdin with the Llama 3 chat template, keeping the
conversation in the off-graph KV cache so each turn feeds only its new
tokens. /reset clears the cache, a full cache starts a new conversation,
and Ctrl-D quits.
to_native takes metadata, the package's counterpart to a PTE's constant
methods, and save writes it as a metadata.json member: names mapped to a
bool, number, string, or flat list of those. Package validates the member
at load and reads integers and integer lists by name; exir.native's
read_metadata reads it back in Python. LLM exports can then publish facts
the graph does not carry, such as the per-layer sliding windows of an
off-graph KV cache, under the names extension/llm/export/model_metadata.py
already defines.
--offgraph_cache now exports models with sliding-window layers instead of
rejecting them. The window is a property of the cache, not the graph, so the
export writes the cache geometry (get_n_caches, get_kv_heads, get_head_dims,
get_windows) to the package's metadata, and the golden samples come from a
reference cache whose sliding layers are rings. A layer's window follows HF:
layer_types when the config has them, else sliding_window on every layer.

The runner reads the windows from the metadata, checks the shapes against the
graph, and builds ring layers sized for the method's token input.
GgmlSequenceCache holds a ring layer at window + max_write - 1 rows from the
start. The executor fills one set of row and mask uploads per window from the
cache's plan: each row is masked by the logical position it holds, so a ring
layer attends all its rows in any physical order, and a query sees only its
own window, including within a prefill wider than the window.
Muse Glimmer's Hugging Face rotary embedding builds its angles as
position_ids[..., None] * inv_freq rather than HF's batched matmul, so
FuseRoPEPass left the cos/sin tables in the graph, which the ggml engine
cannot run. The pass now recognizes that outer product too. The ggml engine
also lowers aten.tanh, which Muse Glimmer's final logit soft cap uses.
transformers no longer re-exports accelerate's init_empty_weights, so
export_hf_llm failed to import. Build GGUF-loaded models with a local context
that puts parameters on the meta device and leaves buffers on the CPU, as
init_empty_weights did; a plain meta device would also empty computed buffers
such as RoPE frequencies. Pass dtype rather than the deprecated torch_dtype.

Newer StaticLayer.lazy_initialization also takes the value states, so the FP16
KV cache passes them where the signature asks. The tests cover both versions:
the GGUF mapping test uses eager attention, since newer sdpa rejects Gemma 2's
softcap, and the FP16 sliding-window rejection test skips where transformers
keeps sliding layers in StaticLayer and windows them through the mask.

Tested with transformers 5.0.0rc1 and 5.22.2.
--gguf excluded --layers because every GGUF tensor must name a parameter, and
a truncated model has none for the later blocks. gguf_to_hf and load_gguf now
take truncated=True to skip the blocks past the model's last layer, and the
export passes it when --layers is set. That exports a few layers of a large
GGUF checkpoint to test the lowering quickly. Without the flag, a tensor that
names no parameter still raises.
The engine took packed GGUF weights only as Q4_K or Q6_K, but K-quant mixes
such as Q4_K_M store some tensors as Q5_K; Muse Glimmer's LM head is one.
Export already carries any GGUF type as a gguf:<type> PackedQuant, so only
the engine needed it. A table of K-quant codecs (ggml type and block bytes)
now replaces the Q4_K/Q6_K conditionals, with Q5_K added.

@SS-JIA SS-JIA 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.

Q5_K support already landed in master, so this PR should not be needed anymore

@metascroy

Copy link
Copy Markdown
Contributor Author

Closing: Q5_K support landed on main in #24845 (fcc9575), which this duplicated; the stack is rebased onto main without it.

@metascroy metascroy closed this Nov 17, 2026

This branch had an error being deployed

1 failed deployment
cadence — acd07589 Deployed Nov 14, 2026 by metascroy
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.

2 participants