Repository navigation
[Native] Publish the context length with off-graph packages - #24955
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/24955
Note: Links to docs will display an error until the docs builds have been completed. ❌ 4 New Failures, 5 Unrelated FailuresAs of commit 00b15b8 with merge base feeb4b6 ( NEW FAILURES - The following jobs have failed:
FLAKY - The following jobs failed but were likely due to flakiness present on trunk:
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. |
1119461 to
649456f
Compare
### 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).
### 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.
### 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.
### 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.").
…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.
### 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.
…#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.
### 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.
### 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.
### 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.
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. The wrapper's cache_metadata() becomes metadata(), since it is no longer only the cache's. Restacked with Codex.
48348a1 to
00b15b8
Compare
This PR needs a
|
### 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.
### 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.
### 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.
### 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.
…he (#25006) ### 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** (this PR) - #24955 - #24954 - #24951 - #24950 - #24949 - #24947 - #24946 - #24945 - #24944 - #24943 - #24639 - #24638 - #24637 - #24636 - #24635 - #24634 ### Summary `GgmlSequenceCache` owned its K/V tensors, their growth, and the row copies a regrow makes. The cell cache in the next PR needs the same storage, so it moves to `GgmlKvPool`, which the sequence cache now holds; the executor binds the pool's storage. Each pool layer records: - its window, which groups layers that share a mask; - whether it's a ring, which decides whether attention reads all its rows or a prefix. The lowering keys the read extent off `ring` rather than off the window. That's the same for the sequence cache, but lets a cell cache's windowed layers read a prefix. No change in behavior. ### Test plan - Engine tests pass. - The runner still verifies golden samples of a sliding-window package and a Muse Glimmer slice. --- Authored with Claude Code.
### 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** (this PR) - #25006 - #24955 - #24954 - #24951 - #24950 - #24949 - #24947 - #24946 - #24945 - #24944 - #24943 - #24639 - #24638 - #24637 - #24636 - #24635 - #24634 ### 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.
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
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'smax_position_embeddingsunder that name, or the export's--max_seq_lengthfor 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'scache_metadata()becomesmetadata(), since it now carries more than the cache's geometry.Test plan
test_export_hf_llm.pyon transformers 5.11.0 and 5.22.2. A full Muse Glimmer export publishes 131072..ci/scripts/test_native_llm_runner.pyadds 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.