Skip to content

[Native] Add a batching executor for native-backend packages - #25055

Open
metascroy wants to merge 1 commit into
mainfrom
offgraph-kv-native-executor
Open

metascroy wants to merge 1 commit into
mainfrom
offgraph-kv-native-executor

Conversation

@metascroy

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

NativeExecutor, in the new backends/native/batching/, serves a .ptn exported with --offgraph_cache --logits_to_keep selected behind extension/llm/batching. It's the native counterpart of ModuleExecutor, as CudaExecutor in backends/cuda/batching/ is for CUDA.

  • Setup: reads the cache geometry and context length from the package, and builds the engine's batched cache with room for every resident session's context. Storage grows with the cells in use. The logits are the method's one user output, the engine's output 0 whatever buffer mutations the graph also returns.
  • Sessions: they're the cache's sequences, through SessionTable. A batch puts several sessions in one forward; each forward declares its sequences and selects the logits row each input wants. A clone shares its source's cells.
  • Engine-neutral: the config takes a host factory and the CacheFactory backend ID of that engine's caches, as the native LLM runner does. A model's serving code picks ggml (or another engine with a batched cache) and adds only its own preparation.

Build: native_batching is installed and exported, so out-of-tree projects such as the Muse Glimmer example link it. There's also a Buck target.

Test plan

native_batching_test, given a toy package from test/export_toy_llm.py (ET_NATIVE_BATCHING_PTN; skips without one):

  • sessions decoded together in one batch get exactly the greedy tokens they get alone;
  • a clone continues as its source, including after a prompt wider than the method's token bound;
  • one batch carrying a session's decode and another's prompt wider than the method, so the prompt's last token is selected in a later forward, matches both sessions alone;
  • a batch the cache refuses fails without changing the session, which then continues as it would have.

All pass. Making the engine ignore the cache's mask fails the batching test. The Buck target is unverified.

CI: test-native.sh ggml builds native_batching_test (turning on the LLM extensions it links), exports the toy package, runs the test with it, and fails the job if any case skips.


Authored with Claude Code.

@pytorch-bot

pytorch-bot Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 8 New Failures, 1 Pending, 1 Unrelated Failure

As of commit c0b5411 with merge base 40cf497 (image):

NEW FAILURES - The following jobs have failed:

BROKEN TRUNK - The following job 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 13, 2026
This was referenced Nov 13, 2026
@metascroy
metascroy force-pushed the offgraph-kv-native-executor branch from 834004e to a52159c Compare November 14, 2026 00:18
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.
JakeStevens pushed a commit that referenced this pull request Nov 18, 2026
…#24944)

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

### Summary
`--offgraph_cache` now exports models with sliding-window layers instead
of rejecting them. The window belongs to the cache, not the graph, so it
travels in the package's metadata.

- **Export:** writes the cache geometry (`get_n_caches`, `get_kv_heads`,
`get_head_dims`, `get_windows`). A layer's window follows HF:
`layer_types` when the config has them, else `sliding_window` on every
layer (Mistral). Golden samples come from a reference cache whose
sliding layers are rings.
- **Runner:** reads the windows, checks the shapes against the graph,
and builds ring layers sized for the method's token input (`max_write`).
A package without `get_windows` is refused rather than run as full
attention.
- **ggml cache:** `GgmlSequenceCache` holds a ring layer at `window +
max_write - 1` rows from the start; flat layers still grow on demand.
- **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 its rows in any physical order, and every query
sees only its own window, including within a prefill wider than the
window.

### Test plan
- Engine tests: ring attention against a naive windowed reference
(wraparound, windows 2 and 5, intra-step windowing, fp32/fp16), flat and
ring layers sharing one sequence in one forward, rewind limited to the
rows a ring holds. Also passes on Metal.
- Export tests compare off-graph golden samples with HF's own sliding
mask for Mistral and Gemma3; they fail with the windows dropped.
- End to end: tiny Mistral and Gemma3 (window 8) golden samples replay
on CPU and Metal. `--warmup_prefill` with a chunked 37-token prompt on
Mistral gives the same tokens as without it. A 121-token chunked prefill
matches HF eager to 2.4e-7 on Mistral (0.175 without the windows).

---
Authored with Claude Code.
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** (this PR)
- #24944
- #24943
- #24639
- #24638
- #24637
- #24636
- #24635
- #24634

### Summary
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 `cos`/`sin` in the graph, which ggml can't run. The
pass now recognizes that outer product too. (The ggml engine already
lowers `aten.tanh`, which its logit soft cap uses.)

### Test plan
- `test_passes.py`: the broadcast form fuses to a single `native.rope`
and matches the unfused output.
- The Muse Glimmer export later in the stack exercises it end to end.

---
Authored with Claude Code.
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** (this PR)
- #24945
- #24944
- #24943
- #24639
- #24638
- #24637
- #24636
- #24635
- #24634

### Summary
Muse Glimmer needs a newer transformers than the examples pin (5.11),
and `export_hf_llm.py` didn't run on it.

- **No accelerate:** transformers no longer re-exports accelerate's
`init_empty_weights`, so the export imported it from accelerate, which
isn't otherwise a dependency. GGUF-loaded models are now built 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.
- `dtype` replaces the deprecated `torch_dtype`.
- The GGUF mapping test uses eager attention, since newer sdpa rejects
Gemma 2's softcap.

### Test plan
`test_export_hf_llm.py` passes with transformers 5.11.0 and 5.22.2.

---
Authored with Claude Code.
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** (this PR)
- #24946
- #24945
- #24944
- #24943
- #24639
- #24638
- #24637
- #24636
- #24635
- #24634

### Summary
`--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 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.

### Test plan
- `test_gguf_hf.py`: a truncated model skips later blocks and still
rejects unknown names.
- `test_export_hf_llm.py`: a 1-layer model loaded from a 2-layer GGUF
matches the reference cut to one layer exactly.

---
Authored with Claude Code.
@JakeStevens
JakeStevens added this pull request to stack #25264 November 19, 2026 01:48
@JakeStevens
JakeStevens force-pushed the offgraph-kv-native-executor branch from 478de32 to 34d1bcf Compare November 19, 2026 01:58
@github-actions

Copy link
Copy Markdown

This PR needs a release notes: label

If your change should be included in the release notes (i.e. would users of this library care about this change?), please use a label starting with release notes:. This helps us keep track and include your important work in the next release notes.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "release notes: none"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

JakeStevens pushed a commit that referenced this pull request Nov 19, 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** (this PR)
- #24947
- #24946
- #24945
- #24944
- #24943
- #24639
- #24638
- #24637
- #24636
- #24635
- #24634

### Summary
Maps Muse Glimmer GGUF tensors onto the Hugging Face
`MuseGlimmerForConditionalGeneration` parameters under
`model.language_model`.

- **Names:** gguf-py has no tensor map for the `muse-glimmer`
architecture, so `gguf_hf` gets an explicit table, for architectures
without one. The `attn_q_norm` / `attn_k_norm` tensors are skipped: the
HF QK norm has no weight. llama.cpp's converter stores the query scale
HF reads from the config (`qk_scale_factor`) as `attn_q_norm` and ones
as `attn_k_norm`, so `load_gguf` checks them against the config
(`check_config_tensors`) instead of dropping them silently.
- **Conversion:** undoes llama.cpp's Q/K row permutation, as for Llama,
and the 1 it adds to the four centered decoder norms. The final norm is
a plain gain and stays as stored.

### Test plan
- `test_gguf_hf.py`: names, conversions, and the QK norm check on a tiny
Muse Glimmer. Needs a transformers with Muse Glimmer; skips otherwise.
- The real GGUF's QK norms pass the check in all 52 layers
(`attn_q_norm` = 3.87); a config with another scale is rejected.
- On the first four layers of
`Muse-Glimmer-30B-KQuant-17GB-Q4_K_M.gguf`, HF with this mapping matches
Muse Glimmer's own model and GGUF loader to 4.9e-5 at FP32, with the
same top token at every position. Dropping the Q/K un-permute or the
norm offset breaks it (max errors 7.5 and 13.8).

---
Authored with Claude Code.
@JakeStevens
JakeStevens force-pushed the offgraph-kv-native-executor branch from 34d1bcf to 3260cc4 Compare November 19, 2026 14:13
JakeStevens pushed a commit that referenced this pull request Nov 19, 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** (this PR)
- #24949
- #24947
- #24946
- #24945
- #24944
- #24943
- #24639
- #24638
- #24637
- #24636
- #24635
- #24634

### Summary
`--verify_samples` streamed each generated token through `--tokenizer`,
which only decodes Llama 3 vocabularies and threw on any other model's
token IDs, though replay compares logits and never needs text.
`generate()` now takes the tokenizer as optional and streams text only
when given one; sample replay passes none.

### Test plan
- Muse Glimmer packages, whose token IDs exceed Llama 3's vocabulary,
replay their golden samples.
- Existing packages still verify, and normal generation still streams
text.

---
Authored with Claude Code.
JakeStevens pushed a commit that referenced this pull request Nov 19, 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** (this PR)
- #24950
- #24949
- #24947
- #24946
- #24945
- #24944
- #24943
- #24639
- #24638
- #24637
- #24636
- #24635
- #24634

### Summary
Exports Muse Glimmer through the native backend.

- **Model class:** Transformers builds Muse Glimmer only as
`MuseGlimmerForConditionalGeneration`, not through
`AutoModelForCausalLM`. That class carries a vision tower and scans
`input_ids` for image and video tokens, which the ggml engine can't run.
The export builds it with `AutoModelForImageTextToText` and exports
`MuseGlimmerTextLM` (new `muse_glimmer.py`) instead: its language model
and LM head under their HF parameter names, with the output multiplier
and logit soft cap.
- **`--layers`:** also truncates its per-layer `layer_rope_theta`.
- **Cache:** it exports only with `--offgraph_cache`, which carries its
sliding windows.

```
python -m executorch.backends.native.examples.hf_llm.export_hf_llm \
  --model <meta-models/Muse-Glimmer-30B dir> \
  --gguf Muse-Glimmer-30B-KQuant-17GB-Q4_K_M.gguf \
  --offgraph_cache --output mg.ptn
```

### Test plan
- `test_export_hf_llm.py`: off-graph golden samples of a tiny Muse
Glimmer match HF's full multimodal model; one `update_and_attend` per
layer and no `aten.eq`. Skips without a transformers that has Muse
Glimmer.
- Full 52-layer model (Q4_K_M, transformers 5.22.2): exports in ~3 min
to a 15.6 GB `.ptn` with every weight packed. Its golden samples pass on
Metal (max logit error 0.04–0.20) and CPU (0.43–0.62). `run_hf_llm_ggml`
needs `--allow_activation_quant_for_weight_only` for its GGUF weights.
Greedy continuation of "The capital of France is": " Paris. It is the".
About 24 decode steps/s on an M4 Max.

---
Authored with Claude Code.
JakeStevens pushed a commit that referenced this pull request Nov 19, 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** (this PR)
- #24951
- #24950
- #24949
- #24947
- #24946
- #24945
- #24944
- #24943
- #24639
- #24638
- #24637
- #24636
- #24635
- #24634

### Summary
The native LLM runner derived the off-graph KV cache a method needs in
code private to the runner: layers from the `update_and_attend` calls,
windows from the package metadata. This moves it to the header-only
`backends/native/runtime/OffGraphCache.h`, along with the token bound
that sizes a ring layer, so a serving executor builds the same cache.
The runner's behavior is unchanged.

### Test plan
The runner still verifies golden samples of a sliding-window package and
a Muse Glimmer slice.

---
Authored with Claude Code.
JakeStevens pushed a commit that referenced this pull request Nov 19, 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** (this PR)
- #24954
- #24951
- #24950
- #24949
- #24947
- #24946
- #24945
- #24944
- #24943
- #24639
- #24638
- #24637
- #24636
- #24635
- #24634

### Summary
A serving runtime sizes its sessions from the context a package
publishes, as MLX packages do with `get_max_context_len`, but native
packages carried only the cache geometry. The off-graph export now also
writes the model's `max_position_embeddings` under that name, or the
export's `--max_seq_length` for a config without one. For an off-graph
package this is the longest context the model supports; the runtime
still sizes its own cache. The wrapper's `cache_metadata()` becomes
`metadata()`, since it now carries more than the cache's geometry.

### Test plan
- `test_export_hf_llm.py` on transformers 5.11.0 and 5.22.2. A full Muse
Glimmer export publishes 131072.
- CI: `.ci/scripts/test_native_llm_runner.py` adds an off-graph package
with a 7-token method. The runner installs its cache from the package's
metadata and prefills a 20-token prompt in chunks; its tokens match
eager HF.

---
Authored with Claude Code.
NativeExecutor, in backends/native/batching, serves a .ptn exported with
--offgraph_cache --logits_to_keep selected behind extension/llm/batching:
the native counterpart of ModuleExecutor, as CudaExecutor is for CUDA. It
reads the cache geometry and context length from the package, builds the
engine's batched cache with room for every resident session's context, and
serves sessions as the cache's sequences through SessionTable. A batch puts
several sessions in one forward; each forward declares its sequences and
selects the logits row each input wants; a clone shares its source's cells.

The engine is the caller's: the config takes a host factory and the
CacheFactory backend id of that engine's caches, as the native LLM runner
does, so a model's serving code picks ggml (or another engine with a batched
cache) and adds only its own preparation.

native_batching_test, given a package from test/export_toy_llm.py, checks
that sessions decoded together in one batch get the tokens they get alone
and that a clone continues as its source; it skips without one.

Restacked with Codex.

@digantdesai digantdesai 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.

backends/native/batching/test/export_toy_llm.py is missing from the wheel keep list. Test modules ship only when something imports them or when they are named in the CI entry list, and nothing imports this one, so installed wheels drop it and the documented python command fails. The wheel drift test catches this and now fails. Please add the module next to the CUDA toy export entry.

The entry belongs in _CI_ENTRY_POINTS in setup.py:

"executorch.backends.cuda.batching.test.export_toy_decoder",

.ci/scripts/tests/test_wheel_test_modules.py::test_ci_entry_points_still_match_the_workflows fails at the top of the stack with: "a workflow names these test modules but nothing keeps them: ['executorch.backends.native.batching.test.export_toy_llm']".


#pragma once

// A batching Executor for a native-backend .ptn: the native counterpart of

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.

should we move it out of backends/native?

This branch was previously deployed

1 inactive deployment
cadence — c0b54115 Deployed Nov 19, 2026 by JakeStevens
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