Skip to content

[Native] Serve many sequences from one ggml engine KV cache - #25007

Merged
JakeStevens merged 1 commit into
offgraph-kv-ggml-kv-poolfrom
offgraph-kv-ggml-cell-cache
Nov 19, 2026
Merged

JakeStevens merged 1 commit into
offgraph-kv-ggml-kv-poolfrom
offgraph-kv-ggml-cell-cache

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

The ggml engine's off-graph cache held one sequence, so a batching runtime couldn't put several sessions in one forward, clone a prefix, or share a pool between sessions.

  • Cache: GgmlCellCache is the neutral CellCache over a GgmlKvPool whose rows are its cells, registered for kind::kBatched and kind::kBatchedCell. It offers BatchControl to the control plane.
  • Engine: a context accepts either cache through llm_cache_registry_key. With a cell cache, the executor:
    • places the forward's tokens at their positions before building the graph (the control plane declared their sequences);
    • grows storage to the step's read extent;
    • fills each window's cache rows and mask straight from the cache's step: rows are the step's cells, and the mask keeps each query to its own sequence's earlier cells within its window.
  • Windows: a windowed layer keeps every cell, so a rewind or clone never needs history the cache dropped.
  • Step lifecycle: CellCache gains end_step() and abandon_step(), which the executor calls after each forward. A forward that succeeds ends its step, so running it again without a new declaration is refused rather than re-served. One that fails after placement gives its cells back: each of the step's sequences drops to its first position in the step, so they continue where they were. Other backends don't call these, so they're unaffected.

Test plan

New engine tests against a multi-sequence reference (naive attention per sequence):

  • two sequences prefilling separately, then decoding in one forward, with and without graph caching, on fp32 and fp16 storage, starting from one row so storage regrows;
  • a clone sharing its source's prefix as both continue, plus rewinds and closing the clone;
  • sliding windows, including inside a prefill wider than the window;
  • undeclared steps and positions that don't continue a sequence are refused;
  • a sliding and a full layer served from the same cells in one two-layer forward;
  • a full pool refusing a step until a rewind frees cells;
  • a forward failing after placement (a host-side row check) gives its cells back; this fails without the undo;
  • a forward that ran can't be replayed without a declaration, so a failing replay can't undo it; this fails without end_step().

cache_test.cpp adds CellEndedStepIsNotReServed and CellAbandonedStepGivesBackItsCells.

All pass on CPU, and on Metal through a temporary local change. Making the executor ignore the cache's mask fails three of the four.


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/25007

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

❌ 1 Unclassified Failure

As of commit 59ddbdc with merge base 520c55b (image):

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

  • MLX / test-mlx / test-mlx (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    RuntimeError: Command bash /Users/runner/work/_temp/exec_script failed with exit code 1

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
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.
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.
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-ggml-cell-cache branch from 803c46b to 3463fb1 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.
The ggml engine's off-graph cache held one sequence, so a batching runtime
could not put several sessions in one forward, clone a prefix, or share a
pool between sessions. GgmlCellCache is the neutral CellCache over a
GgmlKvPool whose rows are its cells, registered for kind::kBatched and
kind::kBatchedCell; it offers BatchControl to the control plane.

A context accepts either cache. With a cell cache, the executor places the
forward's tokens at their positions before building the graph (the control
plane declared their sequences), grows storage to the step's read extent,
and fills each window's cache rows and mask from the cache's step: rows are
the step's cells, and the mask keeps each query to its own sequence's
earlier cells within its window. A windowed layer keeps every cell, so a
rewind or clone never needs history the cache dropped. A forward that fails
after placement leaves its cells claimed, as a failed MLX forward does.

# Conflicts:
#	backends/native/runtime/engine/ggml/GgmlExecutor.cpp

Restacked with Codex.
@JakeStevens
JakeStevens force-pushed the offgraph-kv-ggml-cell-cache branch from 3463fb1 to 59ddbdc 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.

This branch was previously deployed

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