Skip to content

[Native] Add load-time options to engine contexts - #24636

Merged
JakeStevens merged 1 commit into
offgraph-kv-native-exportfrom
offgraph-kv-engine-options
Nov 18, 2026
Merged

JakeStevens merged 1 commit into
offgraph-kv-native-exportfrom
offgraph-kv-engine-options

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

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.

@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/24636

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

❌ 1 New Failure

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

NEW FAILURE - The following job has failed:

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
@metascroy
metascroy force-pushed the offgraph-kv-engine-options branch from 4b5de65 to 0c97fdf Compare November 5, 2026 22:29
@metascroy
metascroy force-pushed the offgraph-kv-engine-options branch from 0c97fdf to 4ec9257 Compare November 11, 2026 18:05
Comment thread backends/native/runtime/engine/Engine.h Outdated
virtual std::unique_ptr<EngineContext> create_context_with_options(
std::shared_ptr<const Program> program,
std::shared_ptr<const Package> package,
const EngineOptions& options);

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.

EngineOptions reads like the generic form of GgmlEngineOptions. Maybe EngineContextOptions, to match EngineContext?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Renamed to EngineContextOptions.

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.
@metascroy
metascroy force-pushed the offgraph-kv-engine-options branch from 8222fd8 to e613f38 Compare November 18, 2026 00:06
@JakeStevens
JakeStevens added this pull request to stack #25206 November 18, 2026 14:44
@JakeStevens
JakeStevens merged commit 6e864f3 into main Nov 18, 2026
@JakeStevens
JakeStevens deleted the offgraph-kv-engine-options 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** (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.
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** (this PR)
- #24637
- #24636
- #24635
- #24634

### 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.").
JakeStevens pushed a commit that referenced this pull request Nov 18, 2026
…24639)

### 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** (this PR)
- #24638
- #24637
- #24636
- #24635
- #24634

### Summary
**Chunked prefill:** prompts longer than the method's token input used
to be rejected. They're now prefilled in chunks of at most that many
tokens. This applies to in-graph and off-graph packages alike.
`generate` now takes the starting position and returns the last token it
chose but never fed, and whether generation stopped on an EOS.

**`--interactive` chat:** needs an off-graph package.
- Each stdin line is wrapped in the Llama 3 chat template; BOS goes only
on the first turn.
- The conversation stays in the KV cache, so each turn feeds only its
new tokens. The previous reply's last token is fed at the start of the
next turn.
- The next turn always closes the previous reply with `<|eot_id|>`. If
the reply hit `--max_new_tokens`, its last token is fed first. If it
ended on an EOS, the EOS itself is not fed, so `<|end_of_text|>` can't
drift from the template.
- `--warmup_prefill` is rejected with `--interactive`; it would prefill
every turn twice. So is `--dump_first_logits`, since every new
conversation prefills from position 0 again.
- A conversation stays within `--max_seq_length` as well as the cache's
capacity, as one-shot generation does.
- `/reset` clears the cache, a full context starts a new conversation,
and Ctrl-D quits.

```
run_hf_llm_ggml --device gpu --package llama1b_q4km_offgraph.ptn \
  --tokenizer tokenizer.model --interactive --kv_max_capacity 2048 --kv_dtype fp16
```

### Test plan
- CI: `.ci/scripts/test_native_llm_runner.py` adds a package whose
method takes at most 7 tokens, so a 20-token prompt prefills in three
calls; the runner's tokens match eager HF.

On an Apple M4 Max, Llama 3.2 1B Q4_K_M:
- An 821-token prompt (method input 512): the off-graph and in-graph
packages give the same answer.
- Two-turn chat: the second turn recalls facts from the first; `/reset`
forgets them.
- A three-turn chat with `--max_new_tokens 24` and a 16-row initial
cache: turn 1 hits the token limit, turn 2 ends on EOS, and the
conversation stays coherent across both.
- `--interactive` on an in-graph package, or combined with
`--warmup_prefill` or `--dump_first_logits`, fails with a clear error.
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** (this PR)
- #24639
- #24638
- #24637
- #24636
- #24635
- #24634

### Summary
A `.ptn` had no way to carry facts the graph doesn't, such as an LLM's
per-layer sliding windows, which a PTE publishes as constant methods.
This adds the counterpart:

- `to_native(programs, metadata={...})` saves a `metadata.json` member:
names mapped to a bool, number, string, or a flat list of those.
`write_ptn` validates it and rejects non-finite floats.
- `exir.native.read_metadata(path)` reads it back.
- `Package` validates the member's structure at load and reads values by
name with `metadata_int` / `metadata_ints`, which reject integers
outside `int64`.
- `backends/native/README.md` documents the member. LLM exports reuse
the constant-method names from `extension/llm/export/model_metadata.py`
(`get_windows`, ...).

### Test plan
- `exir/native/test/test_native.py`: metadata round-trips, no member
without metadata, invalid names and values rejected.
- `test_package.cpp`: reads by name, rejects wrong types and malformed
members. Run through a local CMake build; that file is only built by
Buck.

---
Authored with Claude Code.

This branch was previously deployed

1 inactive deployment
cadence — e613f38a 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