Skip to content

[Native] Run off-graph KV cache packages in the LLM runner - #24638

Merged
JakeStevens merged 1 commit into
offgraph-kv-ggml-enginefrom
offgraph-kv-runner
Nov 18, 2026
Merged

JakeStevens merged 1 commit into
offgraph-kv-ggml-enginefrom
offgraph-kv-runner

Conversation

@metascroy

@metascroy metascroy commented Nov 5, 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

run_hf_llm_ggml (via LlmRunner) can now run packages exported with --offgraph_cache.

  • Cache shape: the runner reads it from the graph. Each update_and_attend call's layer_id and K shape give one flat layer, so the .ptn format doesn't change.
  • Setup: it builds the engine's single-sequence cache with CacheFactory::build(backend_id, kind::kSingle, ...) and publishes it with an InstallGuard. It passes the registry key to create_context_with_options, and keeps the cache alive longer than the context.
  • New flags:
    • --kv_max_capacity: tokens, named as MLX's runners name it; defaults to --max_seq_length.
    • --kv_dtype: fp32 or fp16.
    • --kv_initial_capacity: rows allocated up front.
  • --verify_samples clears the cache between samples instead of recreating the context, and --warmup_prefill clears it after its warmup prefill, since the next step must start at the cache's length.
  • run_llm takes the engine's cache backend id. run_hf_llm_ggml registers the ggml cache builders and passes NativeGgml.
  • --kv_max_capacity, --kv_dtype and --kv_initial_capacity are errors on an in-graph package instead of being silently ignored.
  • extension_llm_cache is now also built when EXECUTORCH_BUILD_NATIVE_LLM_RUNNER is on.
run_hf_llm_ggml --device gpu --package llama1b_q4km_offgraph.ptn \
  --tokenizer tokenizer.model --kv_max_capacity 2048 --kv_dtype fp16 --prompt ...

Test plan

On an Apple M4 Max:

  • Tiny 2-layer random-weight off-graph export, CPU, --verify_samples golden --kv_initial_capacity 1: 0 calls failed, max error about 1.5e-5.
  • Llama 3.2 1B Q4_K_M off-graph, Metal, --verify_samples golden: 0 calls failed (atol 2, rtol 0.05; max error 0.05-0.14).
  • A chat-templated prompt on the off-graph and in-graph packages: same output ("The capital of France is Paris.").

@pytorch-bot

pytorch-bot Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (2 Unrelated Failures)

As of commit 6074d95 with merge base 94313c9 (image):

BROKEN TRUNK - The following jobs failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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 5, 2026
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_max_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.
@JakeStevens
JakeStevens added this pull request to stack #25206 November 18, 2026 14:44
@JakeStevens
JakeStevens merged commit a7ff4b2 into main Nov 18, 2026
@JakeStevens
JakeStevens deleted the offgraph-kv-runner branch November 18, 2026 15:56
JakeStevens pushed a commit that referenced this pull request Nov 18, 2026
### 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.
- #24957
- #24956
- #25055
- #25009
- #25008
- #25007
- #25006
- #24955
- #24954
- #24951
- #24950
- #24949
- #24947
- #24946
- #24945
- #24944
- #24943
- #24639
- #24638
- #24637
- #24636
- #24635
- **#24634** (this PR)

### Summary
Moves the HuggingFace attention function that routes attention through
`torch.ops.kvcache.update_and_attend` from
`backends/mlx/llm/hf_attention.py` to
`extension/llm/cache/hf_attention.py`, so backends other than MLX can
export with an off-graph KV cache.

Nothing in it was MLX-specific: it only emits the cache op, works out
the YOCO donor cache id, and replaces HF's mask with a pass-through. The
new module exposes `offgraph_attention_forward`,
`sdpa_mask_passthrough`, and `register_offgraph_attention(name)`. The
MLX module keeps the names its exporters import
(`register_mlx_offgraph_attention`, `OffGraphExportWrapper`, ...), so
MLX callers are unchanged.

Also adds a `hf_attention` BUCK target in `extension/llm/cache`.

### Test plan
- Imported every name the MLX exporters use (`export_llm_hf.py`,
`dflash/export.py`) and checked that `register_mlx_offgraph_attention()`
registers the shared function.
- The native export tests in the next PR export through the new module.
JakeStevens pushed a commit that referenced this pull request Nov 18, 2026
### 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.
- #24957
- #24956
- #25055
- #25009
- #25008
- #25007
- #25006
- #24955
- #24954
- #24951
- #24950
- #24949
- #24947
- #24946
- #24945
- #24944
- #24943
- #24639
- #24638
- #24637
- #24636
- **#24635** (this PR)
- #24634

### Summary
Adds `--offgraph_cache` to the native backend's HF LLM export
(`backends/native/examples/hf_llm/export_hf_llm.py`). With it, attention
runs through `kvcache::update_and_attend`, so the exported `.ptn` holds
no KV cache buffers; the runtime supplies the cache.

- The native partitioner accepts
`torch.ops.kvcache.update_and_attend.default`.
- `OffGraphLastTokenLM` wraps the model with `use_cache=False` and
positions taken from `cache_position`. While computing golden samples,
it installs the reference `SequenceReferenceCache` in the Python
`REGISTRY`; export only traces the op and needs no cache.
- `--max_context_length` and `--kv_cache_dtype` only describe an
in-graph cache, so combining them with `--offgraph_cache` is rejected.
- Models with any attention layer other than full attention are
rejected: sliding-window layers (Gemma 3, Mistral, or Qwen 2/3 with
`use_sliding_window`) and chunked layers (Llama 4). The cache op attends
every position it holds, so they would silently attend past their span,
in eager and at runtime alike.
- The reference cache is installed in the global `REGISTRY` only inside
`cache_scope()`, and uninstalled on exit.
- Adds the missing `if __name__ == "__main__"` guard. Without it,
`python -m ...export_hf_llm` exited without exporting anything.

Example (Llama 3.2 1B, Q4_K_M GGUF):
```
python -m executorch.backends.native.examples.hf_llm.export_hf_llm \
  --model unsloth/Llama-3.2-1B-Instruct \
  --gguf Llama-3.2-1B-Instruct-Q4_K_M.gguf \
  --offgraph_cache --max_seq_length 512 --samples 2 \
  --output llama1b_q4km_offgraph.ptn
```

### Test plan
- `test_export_hf_llm.py` adds five tests:
- `test_offgraph_cache_matches_the_static_cache`: off-graph eager logits
match the static cache within 1e-5. The exported graph has one
`update_and_attend` per layer, no `index_copy_`, and no mutated buffers,
and `to_native` lowers it to one native delegate. It fails if the
partitioner drops `update_and_attend`.
  - `test_offgraph_cache_excludes_in_graph_cache_flags`.
  - `test_offgraph_cache_rejects_sliding_window_layers` (tiny Gemma 3).
- `test_offgraph_cache_rejects_other_attention_layer_types`
(`chunked_attention`).
  - `test_offgraph_cache_scope_uninstalls_its_reference_cache`.
- `test_export_hf_llm.py` passes on transformers 5.11 (the examples
pin).
JakeStevens pushed a commit that referenced this pull request Nov 18, 2026
### 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.
- #24957
- #24956
- #25055
- #25009
- #25008
- #25007
- #25006
- #24955
- #24954
- #24951
- #24950
- #24949
- #24947
- #24946
- #24945
- #24944
- #24943
- #24639
- #24638
- #24637
- **#24636** (this PR)
- #24635
- #24634

### Summary
Adds `EngineHost::create_context_with_options(program, package,
options)`, where `EngineContextOptions` is a `std::map<std::string,
std::string>` of named load-time settings for one context. The next PR
uses it to pass the registry key of a KV cache the caller installed
(`llm_cache_registry_key`).

The default implementation throws `std::invalid_argument` on any option
and otherwise calls `create_context`, so each engine opts in to the
options it understands. `create_context` and its callers (Session,
Module) are unchanged.

An option can bind caller-owned state, like a KV cache, into several
contexts. The doc comment says those contexts aren't isolated from each
other: the caller must serialize their executables as if they shared one
context.

This PR doesn't depend on the two below it; it's stacked to keep the
series linear.

### Test plan
- Built the ggml engine and `run_hf_llm_ggml`, and ran
`native_ggml_engine_test`: 36 passed. `GpuUnavailableOnCpuVariant` fails
as it does on `main`, because this build has Metal enabled.
- The next PR tests the ggml engine's handling of options, including
rejecting an unknown one.
JakeStevens pushed a commit that referenced this pull request Nov 18, 2026
### 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.
- #24957
- #24956
- #25055
- #25009
- #25008
- #25007
- #25006
- #24955
- #24954
- #24951
- #24950
- #24949
- #24947
- #24946
- #24945
- #24944
- #24943
- #24639
- #24638
- **#24637** (this PR)
- #24636
- #24635
- #24634

### Summary
The native ggml engine can now run graphs exported with an off-graph KV
cache (`kvcache::update_and_attend`).

**Cache:** `GgmlSequenceCache` (new, `GgmlCache.{h,cpp}`)
- It's a `SequenceCache`, so it uses the neutral sequence controller
(`SequenceControl`/`SequencePlanner`). It adds K/V storage per layer,
laid out `[head_dim, rows, n_kv_heads]` in the engine backend's default
buffer type.
- Storage starts at the config's `initial_capacity` rows and doubles
toward `capacity`, copying existing rows across. Short sequences don't
pay for the full context.
- Each allocation is a reference-counted `Storage`. An executable holds
the storage its graphs point into until it rebinds, so a regrow by
another executable never leaves dangling tensors behind.
- Like `SequenceCache`, it isn't thread-safe. Contexts bound to one
cache must be serialized; `create_context_with_options` documents this.
- `register_ggml_cache_builders()` registers it with the `CacheFactory`
under backend id `NativeGgml`, kind `single`. Registration is an
explicit call rather than a static initializer, so a static link can't
drop it.

**Engine**
- `GgmlEngineHost` implements `create_context_with_options`. The
`llm_cache_registry_key` option resolves the cache from the
`CacheRegistry`. A missing key or an unknown option throws.
- `update_and_attend` lowers to `ggml_set_rows` into the layer's cache,
a view of the filled prefix, and `ggml_flash_attn_ext` with an F16
causal mask. The rows and mask are per-step uploads shared by all
layers.
- How many cache rows to attend is part of the graph cache key. It's
`max(position) + 1`, rounded up to 256 and capped at the allocated rows.
`HostIntEvaluator` learns `select.int` so it can evaluate HF's
`position_ids[0]`.
- Before each call, the executor reads the positions once on the host,
then:
1. checks there is one per token (`[T]` or `[T, 1]`), consecutive,
fitting the capacity, and starting at the sequence's length. One past
the length would attend rows nothing wrote, and running earlier
positions again takes an explicit rewind through the cache's control, as
DFlash does;
2. grows the cache, and on a regrow rebinds the storage and drops cached
graphs built over the old one;
  3. plans every layer, then fills the rows and mask from the plan.

It commits only after the call succeeds. A step starts at the length, so
whatever a failed call wrote lies past it, and the sequence is
unchanged.

An F16 step written into an F32 cache is converted first:
`ggml_set_rows` doesn't convert F16 to F32 on every backend (CUDA
aborts, Metal falls back to CPU).

The cache builder reports a geometry or config the engine can't serve
through `CacheFactory::build`'s error result rather than an exception.

**Limits:** flat layers only (sliding-window layers are rejected), batch
1, fp32 or fp16 storage.

### Test plan
New `test_ggml_engine.cpp` tests. Each runs `update_and_attend` against
a naive softmax attention over everything the cache should hold:
- `OffGraphAttentionMatchesReferenceAsTheCacheGrows`:
- a 3-token prefill, then decode steps, in two contexts sharing one
cache;
- storage starts at one row, so it regrows during the prefill and the
decode;
  - with 0, 1, and 4 cached graphs, and fp32 and fp16 storage.
- `OffGraphAttentionReplaysFromEmptyAfterClear`, including an executable
whose binding went stale because another one regrew the cache.
- `OffGraphAttentionContinuesFromARewind`.
- `OffGraphStepsStartAtTheLength`: re-running positions without a
rewind, or skipping past the length, is rejected; after a rewind they
run again.
- `FailedOffGraphStepLeavesTheSequence`: a step that fails on a
host-side row check leaves the sequence's length where it was.
- `RejectsOffGraphStepsPastCapacityOrNotConsecutive`.
- `OffGraphAttentionNeedsAMatchingCache`: no key, an unknown key, an
unknown option, a layer out of range, and K/V shaped unlike the cache.

Checked that the tests catch real bugs: skipping the row copy on regrow
fails 3 of them, dropping the causal mask fails 4, and dropping the
start-position check fails 2.

`native_ggml_engine_test`: 43 passed. `GpuUnavailableOnCpuVariant` fails
as it does on `main`, because this build has Metal enabled.

This branch was previously deployed

1 inactive deployment
cadence — 6074d95d Deployed Nov 18, 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.

3 participants